Token refresh store to allow refresh_token - identityserver4

I have IS4 configured and all works fine except refresh_token where I get BAD REQUESTS (400) back all the time.
I have implemented the PersistedGrantStore to store the tokens since reading the logs I could see:
2020/09/01 17:57:25.589|TRACE|Processing token request. |IdentityServer4.Endpoints.TokenEndpoint|
2020/09/01 17:57:25.616|DEBUG|Start token request. |IdentityServer4.Endpoints.TokenEndpoint|
2020/09/01 17:57:25.624|DEBUG|Start client validation |IdentityServer4.Validation.ClientSecretValidator|
2020/09/01 17:57:25.638|DEBUG|Start parsing Basic Authentication secret |IdentityServer4.Validation.BasicAuthenticationSecretParser|
2020/09/01 17:57:25.638|DEBUG|Start parsing for secret in post body |IdentityServer4.Validation.PostBodySecretParser|
2020/09/01 17:57:25.701|DEBUG|client id without secret found |IdentityServer4.Validation.PostBodySecretParser|
2020/09/01 17:57:25.701|DEBUG|Parser found secret: PostBodySecretParser |IdentityServer4.Validation.SecretParser|type=PostBodySecretParser
2020/09/01 17:57:25.720|DEBUG|Secret id found: autosmoraga_transportes_mobile_app |IdentityServer4.Validation.SecretParser|id=autosmoraga_transportes_mobile_app
2020/09/01 17:57:25.734|TRACE|Calling into client configuration validator: IdentityServer4.Validation.DefaultClientConfigurationValidator |IdentityServer4.Stores.ValidatingClientStore|validatorType=IdentityServer4.Validation.DefaultClientConfigurationValidator
2020/09/01 17:57:25.749|DEBUG|client configuration validation for client autosmoraga_transportes_mobile_app succeeded. |IdentityServer4.Stores.ValidatingClientStore|clientId=autosmoraga_transportes_mobile_app
2020/09/01 17:57:25.749|DEBUG|Public Client - skipping secret validation success |IdentityServer4.Validation.ClientSecretValidator|
2020/09/01 17:57:25.766|DEBUG|Client validation success |IdentityServer4.Validation.ClientSecretValidator|
2020/09/01 17:57:25.785|TRACE|Calling into token request validator: IdentityServer4.Validation.TokenRequestValidator |IdentityServer4.Endpoints.TokenEndpoint|type=IdentityServer4.Validation.TokenRequestValidator
2020/09/01 17:57:25.799|DEBUG|Start token request validation |IdentityServer4.Validation.TokenRequestValidator|
2020/09/01 17:57:25.825|DEBUG|Start validation of refresh token request |IdentityServer4.Validation.TokenRequestValidator|
2020/09/01 17:57:25.856|TRACE|Start refresh token validation |IdentityServer4.Validation.TokenValidator|
2020/09/01 17:57:25.928|DEBUG|refresh_token grant with value: lSWqDibFzKevkEI6KMNQyGimeK7MS7Yrjenk34XEDNQ
not found in store. |IdentityServer4.Stores.DefaultRefreshTokenStore|grantType=refresh_token, key=lSWqDibFzKevkEI6KMNQyGimeK7MS7Yrjenk34XEDNQ
2020/09/01 17:57:25.939|WARN|Invalid refresh token |IdentityServer4.Validation.TokenValidator|
2020/09/01 17:57:25.961|WARN|Refresh token validation failed. aborting, {"ClientId":"XXX", "ClientName":"XXX", "GrantType":"refresh_token", "Raw":{"client_id":"XXX","redirect_uri\n":"http:\/\/localhost:8100\/auth-callback","grant_type":"refresh_token","refresh_token":"***REDACTED***"}} |IdentityServer4.Validation.TokenRequestValidator|details={
"ClientId": "XXXX",
"ClientName": "XXX",
"GrantType": "refresh_token",
"Raw": {
"client_id": "XXXX",
"redirect_uri\n": "http://localhost:8100/auth-callback",
"grant_type": "refresh_token",
"refresh_token": "***REDACTED***"
}
}
I have registered the .AddPersistedGrantStore<PersistedGrantStore>() method however I still can see in the logs that DefaultRefreshTokenStore is being called however I see in the database I have records of type refresh_token stored. I'm not sure if I'm missing something. All works fine except the refresh token part. The client configuration is set with online access enabled:
new Client
{
ClientId = "XXXX",
ClientName = "XXX",
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
RequireClientSecret = false,
AllowedScopes = new List<string> { "openid", "profile", "myapi" },
RedirectUris = new List<string> {
$"{mobileBaseUrl}/auth-callback",
$"{mobileAppBaseUrl}auth-callback",
$"{mobileAppOrigin}/auth-callback",
},
PostLogoutRedirectUris = new List<string> {
$"{mobileBaseUrl}/end-session",
$"{mobileAppBaseUrl}end-session",
$"{mobileAppOrigin}/end-session",
},
AllowedCorsOrigins = new List<string> {
mobileBaseUrl,
mobileAppOrigin
},
AllowOfflineAccess = true,
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true,
}
so I'm not entirely sure what else to check. For reference I have the issue fully explained here: https://github.com/wi3land/ionic-appauth/issues/33

Related

IdentityServer4 - access token only contains sub claim

I've finally been able to get an access token from IdentityServer, and use it to retrieve the UserInfo.
However it seems that the access token I'm getting from IdentityServer only contains the sub claim.
Here is an example token
eyJhbGciOiJSUzI1NiIsImtpZCI6IjVCOTBDN0JBNkExMjI2RjEyMEU0QzJGOEQzMjIwMzAxIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2MzcwNTI5MDIsImV4cCI6MTYzNzEzOTMwMiwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNTkiLCJhdWQiOiJ3ZWF0aGVyZm9yZWNhc3RzIiwiY2xpZW50X2lkIjoiU3NvQXBwbGljYXRpb25DbGllbnQiLCJjZW50cmFsLXRoZWNsaWVudCI6IlRoZSBTU08gY2xpZW50Iiwic3ViIjoiYTUxYjBkZWMtODQyYS00ZWMyLTgwMGEtMzRmYWQyNTRjZTBlIiwiYXV0aF90aW1lIjoxNjM3MDUyMDcyLCJpZHAiOiJsb2NhbCIsImp0aSI6IkQ3Rjc2MzgwQzNERDkzMzVERDVFMTE1NjE4MDkzNEUwIiwic2lkIjoiOEY1OUZFMjRDNkY1NTM2ODhEQzVCMTM5QjNFQUU1MTMiLCJpYXQiOjE2MzcwNTI5MDIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJlbWFpbCIsIndlYXRoZXJmb3JlY2FzdHMucmVhZCIsIndlYXRoZXJmb3JlY2FzdHMud3JpdGUiXSwiYW1yIjpbInB3ZCJdfQ.MiDmgc7AzbVpogbp8ID3WvJ0eo4a30_taxR9EI9ylyJASSdOiNSsk-sGuW-YnJIzf668EQGkTym6FMIvOyTxem9DxxIs8nI_rboHLvuvj4e7CtJeELwbZyraZtAxjVjm9tn0BVRZxuskzb6XSq4xGrt2ag_E0Re5MeQOjtyL0EeMS5md5IEywfD7ThH7pIu8SofFvV5tAYbwO-OPd5YyqpPGKXslRtFlyc7lj9faQh-e2CRMql5rSwhJRqCiaIaLxvXk8ZwISfdhmuyzHA88xrzXkqTK_RElhq4PY_GqpRe64nMvIBrkSeoOGLzlQNE9wa58UypZFFV4l8Cpy3_P2Q
Here is the decoded token
I should be able to use this token to call the /connect/userinfo endpoint
And I can see this in the Output window:
IdentityServer4.Hosting.EndpointRouter: Debug: Request path /connect/userinfo matched to endpoint type Userinfo
IdentityServer4.Hosting.EndpointRouter: Debug: Endpoint enabled: Userinfo, successfully created handler: IdentityServer4.Endpoints.UserInfoEndpoint
IdentityServer4.Hosting.IdentityServerMiddleware: Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.UserInfoEndpoint for /connect/userinfo
IdentityServer4.Endpoints.UserInfoEndpoint: Debug: Start userinfo request
IdentityServer4.Validation.BearerTokenUsageValidator: Debug: Bearer token found in header
IdentityServer4.Endpoints.UserInfoEndpoint: Trace: Calling into userinfo request validator: IdentityServer4.Validation.UserInfoRequestValidator
IdentityServer4.Validation.TokenValidator: Trace: Start access token validation
IdentityServer4.EntityFramework.Stores.ClientStore: Debug: SsoApplicationClient found in database: True
IdentityServer4.Stores.ValidatingClientStore: Trace: Calling into client configuration validator: IdentityServer4.Validation.DefaultClientConfigurationValidator
IdentityServer4.Stores.ValidatingClientStore: Debug: client configuration validation for client SsoApplicationClient succeeded.
IdentityServer4.EntityFramework.Stores.ClientStore: Debug: SsoApplicationClient found in database: True
IdentityServer4.Stores.ValidatingClientStore: Trace: Calling into client configuration validator: IdentityServer4.Validation.DefaultClientConfigurationValidator
IdentityServer4.Stores.ValidatingClientStore: Debug: client configuration validation for client SsoApplicationClient succeeded.
IdentityServer4.Validation.TokenValidator: Debug: Calling into custom token validator: IdentityServer4.Validation.DefaultCustomTokenValidator
IdentityServer4.Validation.TokenValidator: Debug: Token validation success
{
"ValidateLifetime": true,
"AccessTokenType": "Jwt",
"ExpectedScope": "openid",
"JwtId": "2FB8F8A941528DAF18D8C523BCC9A770",
"Claims": {
"nbf": 1637062004,
"exp": 1637148404,
"iss": "https://localhost:44359",
"aud": "weatherforecasts",
"client_id": "SsoApplicationClient",
"central-theclient": "The SSO client",
"sub": "959c9bfa-ed30-4638-9986-63cf1589eff8",
"auth_time": 1637060908,
"idp": "local",
"jti": "2FB8F8A941528DAF18D8C523BCC9A770",
"sid": "75C294FC15A544FE60E361B495EE5BCA",
"iat": 1637062004,
"scope": [
"openid",
"profile",
"email",
"weatherforecasts.read",
"weatherforecasts.write"
],
"amr": "pwd"
}
}
IdentityServer4.Endpoints.UserInfoEndpoint: Trace: Calling into userinfo response generator: IdentityServer4.ResponseHandling.UserInfoResponseGenerator
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Debug: Creating userinfo response
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Debug: Scopes in access token: openid profile email weatherforecasts.read weatherforecasts.write
IdentityServer4.EntityFramework.Stores.ResourceStore: Debug: Found openid, profile, email identity scopes in database
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Debug: Requested claim types:
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Information: Profile service returned the following claim types:
IdentityServer4.Endpoints.UserInfoEndpoint: Debug: End userinfo request
You can even see my custom dedicated client claims being appended during the token validation.
But yet only the sub claim is returned from the identityserver userinfo endpoint...
How can I fix this?
Edit
I added the ProfileService, and it's being called. But as Dejan already mentioned, RequestedClaimTypes is empty. However I updated the database by adding
[{"type":"email","identityResourceId":1003},{"type":"sub","identityResourceId":1003}]
records to the IdentityResourceClaim table. In the output window I can now see that the email and sub claims are requested:
IdentityServer4.Validation.TokenValidator: Debug: Token validation success
{
"ValidateLifetime": true,
"AccessTokenType": "Jwt",
"ExpectedScope": "openid",
"JwtId": "C37AF164BF3A7DE6A28FA7538683248F",
"Claims": {
"nbf": 1637069285,
"exp": 1637155685,
"iss": "https://localhost:44359",
"aud": "weatherforecasts",
"client_id": "SsoApplicationClient",
"central-theclient": "The SSO client",
"sub": "959c9bfa-ed30-4638-9986-63cf1589eff8",
"auth_time": 1637067659,
"idp": "local",
"email": "pieterjan#example.com",
"name": "Pieterjan",
"jti": "C37AF164BF3A7DE6A28FA7538683248F",
"sid": "BBFA9FD0A06824FA4E982DB1D3669A86",
"iat": 1637069285,
"scope": [
"openid",
"profile",
"email",
"weatherforecasts.read",
"weatherforecasts.write"
],
"amr": "pwd"
}
}
IdentityServer4.Endpoints.UserInfoEndpoint: Trace: Calling into userinfo response generator: IdentityServer4.ResponseHandling.UserInfoResponseGenerator
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Debug: Creating userinfo response
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Debug: Scopes in access token: openid profile email weatherforecasts.read weatherforecasts.write
IdentityServer4.EntityFramework.Stores.ResourceStore: Debug: Found openid, profile, email identity scopes in database
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Debug: Requested claim types: email sub
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Information: Profile service returned the following claim types: email name
IdentityServer4.Endpoints.UserInfoEndpoint: Debug: End userinfo request
IdentityServer4.Hosting.IdentityServerMiddleware: Trace: Invoking result: IdentityServer4.Endpoints.Results.UserInfoResult
The code finally enters the ExternalLoginCallback, but the await signInManager.GetExternalLoginInfoAsync() returns null now.
The response from https://localhost:44359/connect/userinfo is
{
"email": "pieterjan#example.com",
"name": "Pieterjan",
"sub": "959c9bfa-ed30-4638-9986-63cf1589eff8"
}
The userinfo endpoint calls GetProfileDataAsync from IdentityServer4.Services.IProfileService to obtain the requested claim values. So the simple solution would be to implement that service.
Assuming you have your user manager defined as IMyUserManager and that it has the methods referenced here (GetClaimsForUser and IsActive), the simplified implementation might look like this:
public class MyProfileService : IProfileService
{
private readonly IMyUserManager userManager;
public MyProfileService(IMyUserManager usermanager)
{
this.userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
// context.RequestedClaimTypes will contain the claims you requested when invoking the token endpoint
var myClaims = await userManager.GetClaimsForUser(context.Subject, context.RequestedClaimTypes);
context.IssuedClaims = myClaims;
}
public async Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = await userManager.IsActive(context.Subject);
}
}
You would then need to configure IdentityServer4 to use this implementation, by calling AddProfileService at startup like this:
services.AddIdentityServer()
// ...
.AddProfileService<MyProfileService>();
I should also add that, in order for your wanted claim to be present in context.RequestedClaimTypes, it needs to be associated with the scopes you directly request when making a call to token endpoint.
At startup, when configuring IdentityServer4, make sure the identity resources you supplied to your AddIdentityResources call contains the required claim.

Unable to configure ASP.NET for Azure Access Token

I was hoping that someone might be able to shed some light on issues that I'm having with authentication. I've mostly used this guidance: https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-overview
I've got a react app that is successfully (I think...) retrieving access tokens for my API:
const account = msalInstance.getActiveAccount();
if (account) {
msalInstance.acquireTokenSilent({
...apiToken,
account: account
}).then((response) => {
setToken(response.accessToken);
});
}
My requests place the token in the authorization header:
Headers
My token looks looks like: Token
API Registration
My API returns 401 whenever I use the Authorize attribute. Because my client is retrieving a token that looks correct, I'm assuming the issue is on my API. This is what I have in my startup auth:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenFormat = new JwtFormat(
new TokenValidationParameters
{
// Check if the audience is intended to be this application
ValidAudiences = new[] { [MY_API_CLIENT_ID (SAME AS AUDIENCE IN TOKEN)], [MY API REGISTRATION URI] },
// Change below to 'true' if you want this Web API to accept tokens issued to one Azure AD tenant only (single-tenant)
// Note that this is a simplification for the quickstart here. You should validate the issuer. For details,
// see https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore
ValidateIssuer = false,
ValidateAudience = false,
ValidateTokenReplay = false,
ValidateIssuerSigningKey = false,
ValidateLifetime = false,
ValidateActor = false, //all false for testing
},
new OpenIdConnectSecurityKeyProvider("https://login.microsoftonline.com/[MY_TENANT_ID]/v2.0/.well-known/openid-configuration")
),
});
Tough silent error here. I noticed that none of the validation callbacks were being invoked. I was missing the package Microsoft.Owin.Host.SystemWeb

Identity Server 4 Silent Renew ErrorResponse: login_required

I have cloned the repo from the redux-oidc-example and it works for the most part but after a few hours it gives the following error:
Action payload: ErrorResponse: login_required
at new e (oidc-client.min.js:1)
at t [as _processSigninParams] (oidc-client.min.js:1)
at t [as validateSigninResponse] (oidc-client.min.js:1)
at oidc-client.min.js:1
UserManager.js looks like this:
const userManagerConfig = {
client_id: 'js.dev',
client_secret: 'secret',
redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}/callback`,
response_type: 'id_token token',
scope: 'openid email profile role offline_access',
authority: 'http://localhost:8080',
silent_redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}/silent_renew.html`,
automaticSilentRenew: true,
filterProtocolClaims: true,
loadUserInfo: true
};
and my identity server config:
{
"Enabled": true,
"ClientId": "js.dev",
"ClientName": "Javascript Client",
"ClientSecrets": [ { "Value": "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=" } ],
"AllowedGrantTypes": [ "implicit", "authorization_code" ],
"AllowedScopes": [ "openid", "email", "profile", "role", "offline_access" ],
"AllowOfflineAccess": true,
"AllowAccessTokensViaBrowser":true,
"RedirectUris": [
"http://localhost:8081/callback",
"http://localhost:8081/silent_renew.html"
],
"PostLogoutRedirectUris": [
"http://localhost:8081"
],
"AccessTokenLifetime": 900,
"RequireConsent": false
}
I noticed that prior to error last valid response had one cookie response(idsrv.session) with empty value with the expiry date set to the previous year:
I believe this to be the root cause of the issue, I searched it on related Github repo and tried to add the Cookie.SameSite to none but it didn't help:
services.AddAuthentication()
.AddSaml(Configuration,externalProviders.UseSaml)
.AddCookie(options => {
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.Cookie.SameSite = SameSiteMode.None;
});
Any idea!
This is likely due to your IDP session expiring - if you call the authorize endpoint with prompt=none but it's unable to satisfy that request because no valid session exists (i.e. authentication cookie does not exist or has expired) then it will return error=login_required.
If this occurs then the correct course of action is to do an interactive (i.e. prompt=login) sign in request in the top level browser window.
After searching the Identity Server 4 repo, I made the following changes to my code:
services.AddIdentityServer(options=>
{
options.Authentication.CookieLifetime = TimeSpan.FromDays(30);
options.Authentication.CookieSlidingExpiration = true;
})
.AddProfileService<ProfileService>()
.AddSigningCertificate(Configuration)
.AddInMemoryClients(Configuration.GetSection("IdentityServer:Clients"))
.AddInMemoryIdentityResources(Resources.GetIdentityResources());
It started working afterward, but you would have to login again after you close the browser or reopen a new tab I guess it's because of the sessionStorage.
When the session expires the signin-callback is being called by STS having a query parameter called 'error' with the value 'login_required'.
In the signin-callback, before completing sign-in, you can check for this query parameter and if it's found you can sign-out also from your web client.
I had the same issue and tried the proposed above, but for me, it actually was SameSiteMode not set correctly on IdentityServer Cookies. It caused Callback error: ErrorResponse: login_required right after login and after N attempts user was logged out.
This helped me https://github.com/IdentityServer/IdentityServer4/blob/main/src/IdentityServer4/host/Extensions/SameSiteHandlingExtensions.cs
What they do is based on this article https://devblogs.microsoft.com/dotnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
Hope this is useful.
Update.
I had another issue related to this when the user was logged out after re-opening a browser (especially on Android Chrome). login_required error was shown. I noticed that session cookie Expires/Max-Age was set to Session and not some future date. Probably because of that check session iframe (with src={identity server url}/connect/checksession) failed as Identity Server thought there was no session as cookie expired.
I tried setting cookie lifetime via options, but it didn't work as expected for some reason. Lifetime was always 14 days:
services.AddIdentityServer(options=>
options.Authentication.CookieLifetime = TimeSpan.FromDays(30);
options.Authentication.CookieSlidingExpiration = true;
})
Then I tried this and it worked for me:
services.ConfigureApplicationCookie(options => {
options.ExpireTimeSpan = sessionCookieLifetime;
options.SlidingExpiration = true;
})

Test Refresh Tokens in IdentityServer4

We are using IdentityServer4 to protect our APIs with EntityFrameworkCore to store configuration and operational data.
Here is our client data:
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "api1" },
AllowOfflineAccess=true
},
new Client
{
ClientId = "client2",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "sup_api" },
AllowOfflineAccess=true
}
};
}
We posted request to connect/token endpoint,with following data in "x-www-form-urlencoded" format
client_id:client2
client_secret:secret
grant_type:client_credentials
scope:sup_api
and we have got the following response:
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjM2ZWE2MGZlNGY2NDZkYjIxZjI0Y2ExNjEzZTBmMTgyIiwidHlwIjoiSldUIn0.eyJuYmYiOjE1MTk4OTM1MTYsImV4cCI6MTUxOTg5MzU2NiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJzdXBfYXBpIl0sImNsaWVudF9pZCI6ImNsaWVudDIiLCJzY29wZSI6WyJzdXBfYXBpIl19.cOznF6F6AL8onLZvvJaSX137P19k6doNa2BoJJTs6WY1LL47UOWoPhR7xIffQVSKyxGp4r-Z02kZrABjjyXzcdTaCR4538Pexep2sjlPobmKI0rfjR2apBSaMBVFXqDW-3VLTnMPyqicIBYjll5iS8YFGpUh0jZwq4rzNvYR4OooHssijQtkhpWxGzuokjKj8ZK1conySqEqorlaFJevY2x4jNlP3v0wpJ_6p77H4Lh12XENw4laGlrejtOkilnRaT7V8CclRGNsgPc81NLJhQZEp89cl37iQ1vLH74hCSs4MllO_eAZ_3Rmdan6QWUM1_zbcCEjGbXJM0QQ2qCpHw",
"expires_in": 3600,
"token_type": "Bearer"
}
But now, how we can test refresh tokens?
One way to do this is check if user still has access after the access token expiration time.
E.g.
At a high level this is what it would look like
Set access token lifetime to 1 minute
Run access test against API at 6 minute mark (there is a inbuilt delay when it actually expires the token)
You should assert that 401 will return, if it does then pass
Activate offline token
Run access test after 6 minute mark
Assert that you get non 401 response, if so then pass
It more testing of

How to request additional claims for access token in identity server 4 / auth code flow?

How do you request additional claims for the access token jwt in identity server 4 / auth code flow? My custom profile service always shows RequestedClaimTypes of 0 during my auth code flow signin so the resulting access token jwt has my subject claim but no firstname, lastname, or email claim.
Here are my requested scopes from the client:
"TestApi openid profile email"
Here is my client definition on identity server:
new Client {
ClientId = "authorizationCodeClient2",
ClientName = "Authorization Code Test",
ClientSecrets = {
new Secret("secret".Sha256())
},
Enabled = true,
AllowedGrantTypes = GrantTypes.Code,
RequireConsent = true,
AllowRememberConsent = false,
RedirectUris =
new List<string> {
"http://localhost:5436/account/oAuth2"
},
AllowedScopes = { "TestApi", "openid", "profile", "email" },
AccessTokenType = AccessTokenType.Jwt
}
Using https://github.com/bayardw/IdentityServer4.Authorization.Code for the test client.
I discovered that identity server will let you optionally stamp the id token with the user profile claims (instead of having to call the userinfo endpoint). You basically set a Boolean property for that particular client:
AlwaysIncludeUserClaimsInIdToken = true;
Note, you will want to request the following scopes on your auth request : (openid profile email)

Resources