private Task AfterTokenValidated(IConfiguration configuration, Microsoft.AspNetCore.Authentication.OpenIdConnect.TokenValidatedContext ctx) { //ctx.Properties.RedirectUri = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}", configuration.GetValue<String>(ConfigurationSectionKeys.RedirectHost), "/"); // ////To Do: Logic to get the User GUID from the ID Token. //string id = ctx.Principal.Claims.First(x => x.Type == ClaimTypeKeys.ObjectIdentifier).Value; // //var idToken = ctx.SecurityToken.RawData; //Task<List<string>> userGroups = membershipProvider.GetGroupsByUserAsync(id, idToken); // //List<string> allowedGroups = configuration.GetValue<String>(ConfigurationSectionKeys.AllowedGroups).Split(';').ToList<string>(); // //var claims = new List<Claim> //{ // new Claim(ClaimTypes.Role, Roles.EchoWebApiUserRequester) // //}; // //foreach (var allowedGroup in allowedGroups) //{ // //Determine claims based on group // if (userGroups.Result.Contains(allowedGroup)) // { // Claim group = new Claim(ClaimTypes.GroupSid, allowedGroup); // claims.Add(group); // var appIdentity = new ClaimsIdentity(claims); // ctx.Principal.AddIdentity(appIdentity); // break; // } //} return(Task.CompletedTask); }
internal static Task TokenValidated(TokenValidatedContext context) { Helpers.ThrowIfConditionFailed(() => context.Ticket != null, "context.Ticket is null."); Helpers.ThrowIfConditionFailed(() => context.Ticket.Principal != null, "context.Ticket.Principal is null."); Helpers.ThrowIfConditionFailed(() => context.Ticket.Principal.Identity != null, "context.Ticket.Principal.Identity is null."); Helpers.ThrowIfConditionFailed(() => !string.IsNullOrWhiteSpace(context.Ticket.Principal.Identity.Name), "context.Ticket.Principal.Identity.Name is null."); eventsFired.Add(nameof(TokenValidated)); return Task.FromResult(0); }
/// <summary> /// [not recommended] In a Web App, adds, to the MSAL.NET cache, the account of the user authenticating to the Web App. /// An On-behalf-of token is added to the cache, so that it can then be used to acquire another token on-behalf-of the /// same user in order for the Web App to call a Web APIs. /// </summary> /// <param name="tokenValidationContext">Token validation context passed to the handler of the OnTokenValidated event /// for the OpenIdConnect middleware</param> /// <param name="scopes">[Optional] scopes to pre-request for a downstream API</param> /// <remarks>In a Web App, it's preferable to not request an access token, but only a code, and use the <see cref="AddAccountToCacheFromAuthorizationCode"/></remarks> /// <example> /// From the configuration of the Authentication of the ASP.NET Core Web API: /// <code>OpenIdConnectOptions options;</code> /// /// Subscribe to the token validated event: /// <code> /// options.Events.OnAuthorizationCodeReceived = OnTokenValidated; /// </code> /// /// And then in the OnTokenValidated method, call <see cref="AddAccountToCacheFromJwt(OpenIdConnect.TokenValidatedContext)"/>: /// <code> /// private async Task OnTokenValidated(TokenValidatedContext context) /// { /// var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>(); /// _tokenAcquisition.AddAccountToCache(tokenValidationContext); /// } /// </code> /// </example> public void AddAccountToCacheFromJwt(Microsoft.AspNetCore.Authentication.OpenIdConnect.TokenValidatedContext tokenValidatedContext, IEnumerable <string> scopes = null) { if (tokenValidatedContext == null) { throw new ArgumentNullException(nameof(tokenValidatedContext)); } this.AddAccountToCacheFromJwt(scopes, tokenValidatedContext.SecurityToken, tokenValidatedContext.Principal, tokenValidatedContext.HttpContext); }
/// <summary> /// [not recommended] In a Web App, adds, to the MSAL.NET cache, the account of the user authenticating to the Web App. /// An On-behalf-of token is added to the cache, so that it can then be used to acquire another token on-behalf-of the /// same user in order for the Web App to call a Web APIs. /// </summary> /// <param name="tokenValidationContext">Token validation context passed to the handler of the OnTokenValidated event /// for the OpenIdConnect middleware</param> /// <param name="scopes">[Optional] scopes to pre-request for a downstream API</param> /// <remarks>In a Web App, it's preferable to not request an access token, but only a code, and use the <see cref="AddAccountToCacheFromAuthorizationCode"/></remarks> /// <example> /// From the configuration of the Authentication of the ASP.NET Core Web API: /// <code>OpenIdConnectOptions options;</code> /// /// Subscribe to the token validated event: /// <code> /// options.Events.OnAuthorizationCodeReceived = OnTokenValidated; /// </code> /// /// And then in the OnTokenValidated method, call <see cref="AddAccountToCacheFromJwt(OpenIdConnect.TokenValidatedContext)"/>: /// <code> /// private async Task OnTokenValidated(TokenValidatedContext context) /// { /// var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>(); /// _tokenAcquisition.AddAccountToCache(tokenValidationContext); /// } /// </code> /// </example> public void AddAccountToCacheFromJwt(OpenIdConnect.TokenValidatedContext tokenValidatedContext, IEnumerable <string> scopes = null) { if (tokenValidatedContext == null) { throw new ArgumentNullException(nameof(tokenValidatedContext)); } AddAccountToCacheFromJwt(scopes, tokenValidatedContext.SecurityToken, tokenValidatedContext.Properties, tokenValidatedContext.Principal, tokenValidatedContext.HttpContext); }
private async Task OpenIdTokenValidated(Microsoft.AspNetCore.Authentication.OpenIdConnect.TokenValidatedContext context) { _logger.LogDebug("TokenValidated!"); // Acquire a Token for the Graph API and cache it using ADAL. string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; var userJson = await b2cGraph.GetUserByObjectId(userObjectId); var user = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(userJson); // Get the users roles and groups from the Graph Api. Then return the roles and groups in a new identity ClaimsIdentity identity = await GetUsersRoles(userObjectId); // Add the roles to the Principal User context.Ticket.Principal.AddIdentity(identity); // return Task.FromResult(0); }
/// <summary> /// Invoked when an IdToken has been validated and produced an AuthenticationTicket. /// </summary> public virtual Task TokenValidated(TokenValidatedContext context) => OnTokenValidated(context);
/// <summary> /// Method that is called by the OIDC middleware after the authentication data has been validated. This is where most of the sign up /// and sign in work is done. /// </summary> /// <param name="context">An OIDC-supplied <see cref="Microsoft.AspNetCore.Authentication.OpenIdConnect.AuthenticationValidatedContext"/> containing the current authentication information.</param> /// <returns>a completed <see cref="System.Threading.Tasks.Task"/></returns> public override async Task TokenValidated(TokenValidatedContext context) { var principal = context.Ticket.Principal; var userId = principal.GetObjectIdentifierValue(); var tenantManager = context.HttpContext.RequestServices.GetService<TenantManager>(); var userManager = context.HttpContext.RequestServices.GetService<UserManager>(); var issuerValue = principal.GetIssuerValue(); _logger.AuthenticationValidated(userId, issuerValue); // Normalize the claims first. NormalizeClaims(principal); var tenant = await tenantManager.FindByIssuerValueAsync(issuerValue) .ConfigureAwait(false); if (context.IsSigningUp()) { // Originally, we were checking to see if the tenant was non-null, however, this would not allow // permission changes to the application in AAD since a re-consent may be required. Now we just don't // try to recreate the tenant. if (tenant == null) { tenant = await SignUpTenantAsync(context, tenantManager) .ConfigureAwait(false); } // In this case, we need to go ahead and set up the user signing us up. await CreateOrUpdateUserAsync(context.Ticket, userManager, tenant) .ConfigureAwait(false); } else { if (tenant == null) { _logger.UnregisteredUserSignInAttempted(userId, issuerValue); #if NET451 throw new SecurityTokenValidationException($"Tenant {issuerValue} is not registered"); #else throw new SecurityException($"Tenant {issuerValue} is not registered"); #endif } await CreateOrUpdateUserAsync(context.Ticket, userManager, tenant) .ConfigureAwait(false); } }
public virtual Task TokenValidated(TokenValidatedContext context) => OnTokenValidated(context);