I need to change the token on the client when changing user data on the server. For example, after changing some data on the server, I do a re-login. I see these changes, but the web application does not update this data automatically, that is, to use them, I need to exit the application and log in again to receive a new token. The documentation for IdentityServer 4 says that the token update option does not work for Implicit flow. But probably there are some ways to update the token (is it possible to do this by setting a timeout or something else)?
IdentityServer4 settings for client:
// React AOO Client
new Client
{
ClientId = "airvector",
ClientName = "Airvector Ordering Online",
//AccessTokenType = AccessTokenType.Reference,
//AccessTokenLifetime = 30,
//IdentityTokenLifetime = 10,
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
//RefreshTokenUsage = TokenUsage.OneTimeOnly,
AccessTokenLifetime = 3600 * 24,
RedirectUris = {
"http://localhost:3000/callback"
},
PostLogoutRedirectUris = { "http://localhost:3000/login" },
AllowedCorsOrigins = { "http://localhost:3000" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"aoo_api",
"Schedules.API",
"Ordering.API",
"Catalog.API"
}
},
userManager in React:
import { createUserManager } from 'redux-oidc';
import { UserManagerSettings } from 'oidc-client';
const userManagerConfig: UserManagerSettings = {
client_id: 'airvector',
redirect_uri: `${window.location.protocol}//
${window.location.hostname}${window.location.port ?
`:${window.location.port}` : ''}/callback`,
response_type: 'token id_token',
scope:"openid profile aoo_api Schedules.API Ordering.API Catalog.API",
authority: 'http://localhost:5000', // DEV
silent_redirect_uri: 'http://localhost:3000/login',
automaticSilentRenew: true,
filterProtocolClaims: true,
loadUserInfo: true,
monitorSession: true
};
const userManager = createUserManager(userManagerConfig);
export default userManager;
Related
I am currently implementing OAuth Server with IdentityServer4 using .NET Core 3.1 and React for client SPA.
When I click logout I get the following:
React JS:
const handleLogout = async () => {
const token = sessionStorage.getItem("id_token");
userManager.signoutRedirect({
id_token_hint: token
});
};
IdentityServer4 Configuration:
new Client
{
ClientId = _mobileAuthorizationCodeClientId,
ClientName = _mobileAuthorizationCodeClientName,
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
RequireClientSecret = false,
RequireConsent = false,
AllowAccessTokensViaBrowser = true,
AllowOfflineAccess = true,
AllowedScopes =
{
_avlApi, _clearingApi, _reportingApi, _assetManagementApi, _ticketingApi,
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OfflineAccess,
},
RedirectUris = { "https://localhost:3000/signin-callback" },
PostLogoutRedirectUris = { "https://localhost:3000/signout-callback" },
AllowedCorsOrigins = { "https://localhost:3000" },
},
Startup.cs relevant parts:
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.Password.RequiredLength = 4;
config.Password.RequireDigit = false;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer(options =>
{
options.IssuerUri = publicOrigin;
options.PublicOrigin = publicOrigin;
options.UserInteraction = new UserInteractionOptions()
{
LogoutUrl = "/account/logout",
LoginUrl = "/account/login",
LoginReturnUrlParameter = "returnUrl",
CustomRedirectReturnUrlParameter = "returnUrl",
};
})
.AddAspNetIdentity<ApplicationUser>()
.AddInMemoryIdentityResources(Config.GetResources())
.AddInMemoryApiResources(Config.GetApis())
.AddInMemoryClients(Config.GetClients())
.AddDeveloperSigningCredential()
.AddProfileService<IdentityProfileService>();
services.AddAuthentication();
I don't see any error logs from IDP.
I've tried to get some workaround around similar issue. https://github.com/IdentityServer/IdentityServer4/issues/3854
The weird thing. If connect/endsession is not canceled - the logout works as expected.
We using https://github.com/maxmantz/redux-oidc for client react js.
Versions:
<PackageReference Include="IdentityServer4" Version="3.1.3" />
<PackageReference Include="IdentityServer4.AspNetIdentity" Version="3.1.3" />
Question is: why connect/endsession is cancelled?
Any information will be highly appreciated!
Are you missing an await on the below line?
await userManager.signoutRedirect({
id_token_hint: token
});
usually, the requests will be canceled when the user gets redirected to a new page, I see the subsequent call after the canceled call is authorize which will redirect the user...
hopefully adding await may solve the problem.
For unknown reason to me the "aud" claim is not present in access token (it is present in id token though).
Once access token is being sent to the API i get the following error:
Bearer was not authenticated. Failure message: IDX10214: Audience
validation failed. Audiences: 'empty'. Did not match:
validationParameters.ValidAudience: 'productconfigurationapi' or
validationParameters.ValidAudiences: 'null'.
I know i can turn off audience validation and everything works then but i don't get why "aud" is not part of the access token.
Here's my IS4 configuration:
the client:
new Client
{
ClientId = "Spa",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true,
AccessTokenType = AccessTokenType.Jwt,
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"productconfigurationapi"
},
RequireConsent = false
}
the api resource:
new ApiResource("productconfigurationapi")
{
UserClaims =
{
JwtClaimTypes.Audience
}
}
the API Scope:
return new List<ApiScope>
{
new ApiScope("productconfigurationapi")
};
and here's how IS4 is configured within its host application:
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddConfigurationStore(options =>
{
})
.AddOperationalStore(options =>
{
})
.AddAspNetIdentity<IdentityUser>()
.AddJwtBearerClientAuthentication();
You should tie the ApiScope to the ApiResource by setting the Scopes property:
var api = new ApiResource("productconfigurationapi")
{
UserClaims =
{
//...optional user claims...
},
Scopes = new List<string>
{
"productconfigurationapi"
},
};
To complement this answer, I write a blog post that goes into more detail about this topic:
IdentityServer – IdentityResource vs. ApiResource vs. ApiScope
We have an SPA, written in React together with ASP.net core for hosting.
To authenticate the app, we are using IdentityServer4 and use a cookie. The client is configured according to the sample, described here: https://github.com/IdentityServer/IdentityServer4/tree/main/samples/Quickstarts/4_JavaScriptClient/src
For authenticating a user, everythings works fine. It will be redirected to the login page. After signing in, redirection to the SPA is done. The authentiation cookie is set as expected with:
HttpOnly = true
Secure = true
SameSite = None
Expires / Max-age = one week from login time
The cookie is used also in other MVC (.net core and MVC 5) applications for authentication reasons.
In the SPA, we are also using SignalR, which needs the cookie for authentication.
Our issue:
After about 30 minutes of idle time in the browser and either doing a refresh or navigating, the authentication cookie (and only that, other remains) is disappearing from the browser automatically. Then the user has to sign in again. Why does this happen together with the SPA?
Code
Complete code can be found in github
Client
Snippets of UserService.ts
const openIdConnectConfig: UserManagerSettings = {
authority: baseUrls.person,
client_id: "js",
redirect_uri: joinUrl(baseUrls.spa, "signincallback"),
response_type: "code",
scope: "openid offline_access profile Person.Api Translation.Api",
post_logout_redirect_uri: baseUrls.spa,
automaticSilentRenew: true
};
export const getUserService = asFactory(() => {
const userManager = new UserManager(openIdConnectConfig);
return createInstance(createStateHandler(defaultUserState), userManager, createSignInProcess(userManager));
}, sameInstancePerSameArguments());
Server
Snipped of Startup.cs
public void ConfigureServices(IServiceCollection services)
{
Log.Information($"Start configuring services. Environment: {_environment.EnvironmentName}");
services.AddControllersWithViews();
services.AddIdentity<LoginInputModel, RoleDto>()
.AddDefaultTokenProviders();
var certificate = LoadSigningCertificate();
var identityServerBuilder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddSigningCredential(certificate)
.AddProfileService<ProfileService>()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(new ClientConfigLoader().LoadClients(Configuration));
if (_environment.IsDevelopment())
{
identityServerBuilder.AddDeveloperSigningCredential();
}
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(_sharedAuthTicketKeys))
.SetApplicationName("SharedCookieApp");
services.AddAsposeMailLicense(Configuration);
var optionalStartupSettings = SetupStartupSettings();
if (optionalStartupSettings.IsSome)
{
var settings = optionalStartupSettings.Value;
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = new PathString("/Account/AccessDenied");
options.Cookie.Name = ".AspNetCore.Auth.Cookie";
options.Cookie.Path = "/";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.LoginPath = new PathString("/account/login");
options.Cookie.SameSite = SameSiteMode.None;
});
var authBuilder = services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "Identity.Application"; });
authBuilder = ConfigureSaml2(authBuilder, settings);
authBuilder = ConfigureGoogle(authBuilder);
authBuilder.AddCookie();
}
else
{
throw new InvalidOperationException($"Startup settings are not configured in appsettings.json.");
}
SetupEntityFramework(services);
}
Snippet of identity server client config from appsettings.json
{
"Enabled": true,
"ClientId": "js",
"ClientName": "JavaScript Client",
"AllowedGrantTypes": [ "authorization_code" ],
"RequirePkce": true,
"RequireClientSecret": false,
"RedirectUris": [ "https://dev.myCompany.ch/i/signincallback", "https://dev.myCompany.com/i/signincallback", "https://dev.myCompany.de/i/signincallback" ],
"PostLogoutRedirectUris": [ "https://dev.myCompany.ch/i/", "https://dev.myCompany.com/i/", "https://dev.myCompany.de/i/" ],
"AllowedCorsOrigins": [],
"AllowedScopes": [ "openid", "offline_access", "profile", "Translation.Api", "Person.Api" ],
"RequireConsent": false,
"AllowOfflineAccess": true
}
Update
In the meantime I discovered that the cookie, while requesting https://ourdomain/.well-known/openid-configuration after 30 minutes idle time, has lost the values of Domain, Path, Expires/Max-Age, HttpOnly, Secure and SameSite.None. Those values have definitely been set after signing in.
The response cookie has the value of Expires/Max-Age set to a time in the past and therefore the cookie will be dropped by the browser.
Has anyone an idea, why those values got lost after some time?
Finally, I figured out how to tackle this.
It had to do with the configuration of IdentityServer. The missing part was the method AddAspNetIdentity<LoginInputModel>().
Before:
var certificate = LoadSigningCertificate();
var identityServerBuilder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddSigningCredential(certificate)
.AddProfileService<ProfileService>()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(new ClientConfigLoader().LoadClients(Configuration));
Now:
var certificate = LoadSigningCertificate();
var identityServerBuilder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddSigningCredential(certificate)
.AddAspNetIdentity<LoginInputModel>()
.AddProfileService<ProfileService>()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(new ClientConfigLoader().LoadClients(Configuration));
With that additional configuration line, Identity Server is handling the cookie correctly.
You can add below code in Configure method in Startup.cs :
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always,
MinimumSameSitePolicy=SameSiteMode.None
});
add this before using identity server service:
app.UseIdentityServer();
You need to check "HttpOnly" option for your situation because it can give trouble with oidc client on react.
I'm creating an application for my web app but I want to only use Microsoft.Graph instead ActiveDirectory.GraphClient that is possible,if yes then how?
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
NameClaimType = ClaimTypes.Name,
RoleClaimType = ClaimTypes.Role,
};
options.Scope.Add("openid profile User.ReadWrite User.ReadBasic.All Sites.ReadWrite.All Contacts.ReadWrite People.Read Notes.ReadWrite.All Tasks.ReadWrite Mail.ReadWrite Files.ReadWrite.All Calendars.ReadWrite");
options.Events = new OpenIdConnectEvents
{
OnTicketReceived = context =>
{
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
context.Response.Redirect("/Error");
context.HandleResponse(); // Suppress the exception
return Task.CompletedTask;
},
};
});
The simplest answer for you is to follow the "Get Started of ASPNET", and then change the logic to suit your requirement.
Do it your by yourself:
Use the Nuget to install the "Microsoft.Graph" and then modify the GraphScopes in configuration file of project(appsettings.json for NETCore).
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"CallbackPath": "/signin-oidc",
"BaseUrl": "https://localhost:44334",
"ClientId": "your client id",
"ClientSecret": "your secret", // This sample uses a password (secret) to authenticate. Production apps should use a certificate.
"Scopes": "openid email profile offline_access",
"GraphResourceId": "https://graph.microsoft.com/",
"GraphScopes": "User.Read User.ReadBasic.All Mail.Send
}
Modify the configure service code as below:
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(options => Configuration.Bind("AzureAd", options))
.AddCookie();
I've a test project with this client configuration:
public class Clients : IClientStore
{
public Task<Client> FindClientByIdAsync(string clientId)
{
return Task.FromResult(new Client
{
ClientId = "client.webforms",
ClientName = "WebForms Client",
AllowedGrantTypes = GrantTypes.Hybrid,
AllowAccessTokensViaBrowser = false,
ClientSecrets =
{
new Secret("1234".Sha256())
},
RedirectUris = { "http://localhost:9869/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:9869/" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
CstIdSrvScopeTypes.TestWebForms
},
AllowOfflineAccess = false,
RequireConsent = false,
AlwaysIncludeUserClaimsInIdToken = true
});
}
}
When I try to validate it in LoginController I'm getting false result (this is from Immediate Window:
returnUrl
"http://localhost:9869/signin-oidc"
this.identityServer.IsValidReturnUrl(returnUrl)
false
Also this.identityServer.GetAuthorizationContextAsync(returnUrl) result is null. Am I doing something wrong?
Yes - you need to add a single RedirectUri when you configur your client that is one of the RedirectUris that is in the list you have above.
Something like
#
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
SignInAsAuthenticationType = Settings.AuthenticationType,
Authority = config.Authority,
RedirectUri = config.RedirectUri
}