private async Task <bool> AddAuthClaims(TokenValidatedContext context) { // should never be null or not a JwtSecurityToken if (context.SecurityToken is JwtSecurityToken token) { // Get the usersId from JWT string userId = token.Payload["user_id"].ToString(); if (context.Principal.Identity is ClaimsIdentity identity) { // Check if credential or token is null or is the token is expired or expiring if (credential == null || credential.Token == null || credential.Clock == null || credential.Token.IsExpired(credential.Clock)) { // Get access token for database using private key credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(Config["Firebase:client_email"]) { Scopes = scopes }.FromPrivateKey(Config["Firebase:private_key"]) ); // Retrieving Token from credentials async. // Why do I assign to task? // What does CancellationToken.None do var task = await credential.RequestAccessTokenAsync(CancellationToken.None); } if (credential != null && credential.Token != null && credential.Clock != null && !credential.Token.IsExpired(credential.Clock)) { // Get access token from creds string accessToken = credential.Token.AccessToken; // Add Auth Claims await AddRoleClaims(identity, accessToken, userId); } else { // Should not get here // creds are bad or token is expired even after a refresh check } // Add Auth role claim regardless of admin status identity.AddClaim(new Claim(ClaimTypes.Role, "Auth")); return(true); } } return(false); }
//public static Guid SubjectId { get; private set; } public static TokenValidatedContext ResolveClaims(this TokenValidatedContext context) { //Get jwt token issued by identityProvider var jwt = context.SecurityToken; var subjectId = jwt.Subject; if (subjectId != null) { //SubjectId = Guid.Parse(subjectId); Startup.subjectId = Guid.Parse(subjectId); } //Extract claims from jwt token var claims = new List <Claim>(jwt.Claims); //Check if the claims contain a claim of the type 'name' if (claims.Exists(x => x.Type.Equals(TypeName))) { //Gets the claim typeOf 'name' var authLvl = claims.Where(x => x.Type.Equals(TypeName)).SingleOrDefault(); //Try and parse the authLvl to a int value; if (authLvl.Value.Equals(UserRoles.Admin.ToString())) { context.Principal.AddIdentity(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, UserRoles.Admin.ToString()) })); } if (authLvl.Value.Equals(UserRoles.Administrative.ToString())) { context.Principal.AddIdentity(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, UserRoles.Administrative.ToString()) })); } if (authLvl.Value.Equals(UserRoles.Manager.ToString())) { context.Principal.AddIdentity(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, UserRoles.Employee.ToString()) })); } if (authLvl.Value.Equals(UserRoles.Employee.ToString())) { context.Principal.AddIdentity(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, UserRoles.Unknown.ToString()) })); } } return(context); }
public async Task ValidateAsync(TokenValidatedContext context) { var userPrincipal = context.Principal; var claimsIdentity = context.Principal.Identity as ClaimsIdentity; if (claimsIdentity?.Claims == null || !claimsIdentity.Claims.Any()) { context.Fail("This is not our issued token. It has no claims."); return; } var serialNumberClaim = claimsIdentity.FindFirst(ClaimTypes.SerialNumber); if (serialNumberClaim == null) { context.Fail("This is not our issued token. It has no serial."); return; } var userIdString = claimsIdentity.FindFirst(ClaimTypes.UserData).Value; if (!int.TryParse(userIdString, out int userId)) { context.Fail("This is not our issued token. It has no user-id."); return; } var user = await _usersService.FindByIdAsync(userId.ToString()); if (user == null || user.SerialNumber != serialNumberClaim.Value || !user.IsActive) { // user has changed his/her password/roles/stat/IsActive context.Fail("This token is expired. Please login again."); } var accessToken = context.SecurityToken as JwtSecurityToken; if (accessToken == null || string.IsNullOrWhiteSpace(accessToken.RawData) || !await _tokenStoreService.IsValidTokenAsync(accessToken.RawData, userId)) { context.Fail("This token is not in our database."); return; } await _usersService.UpdateUserLastActivityDateAsync(userId); }
private static void MapKeycloakRolesToRoleClaims(TokenValidatedContext context) { //var resourceAccess = JObject.Parse(context.Principal.FindFirst("resource_access").Value); //var clientResource = resourceAccess[context.Principal.FindFirstValue("aud")]; var clientRoles = context.Principal.Claims.Where(w => w.Type == "user_realm_roles").ToList(); var claimsIdentity = context.Principal.Identity as ClaimsIdentity; if (claimsIdentity == null) { return; } foreach (var clientRole in clientRoles) { claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, clientRole.Value)); } }
public override async Task TokenValidated(TokenValidatedContext context) { var userId = context.Principal.Identity.Name; var mediator = context.HttpContext.RequestServices.GetRequiredService <IMediator>(); try { var user = await mediator.Send(new GetUserByIdQuery() { UserId = userId }); } catch (NotFoundException e) { context.Fail(e.Message); } }
public async Task Valid_NotFoundCoustomer_ReturnFalse() { var httpContext = new Mock <HttpContext>(); var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions()); IList <Claim> claims = new List <Claim> { new Claim("Email", "*****@*****.**"), new Claim("Token", "123") }; context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "")); _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny <string>())).Returns(() => Task.FromResult <Customer>(null)); var result = await _jwtBearerAuthenticationService.Valid(context); Assert.IsFalse(result); Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(), "Email not exists/or not active in the customer table"); }
private static async Task OnTokenValidated(TokenValidatedContext context) { // get current principal var principal = context.Ticket.Principal; // get current claim identity var claimsIdentity = context.Ticket.Principal.Identity as ClaimsIdentity; // build up the id_token and put it into current claim identity var headerToken = context.Request.Headers["Authorization"][0].Substring(context.Ticket.AuthenticationScheme.Length + 1); claimsIdentity?.AddClaim(new Claim("id_token", headerToken)); await Task.FromResult(0); }
private static void MapKeycloakRolesToRoleClaims(TokenValidatedContext context) { var resourceAccess = JObject.Parse(context.Principal.FindFirst("resource_access").Value); var clientResource = resourceAccess[context.Options.ClientId]; var clientRoles = clientResource["roles"]; var claimsIdentity = context.Principal.Identity as ClaimsIdentity; if (claimsIdentity == null) { return; } foreach (var clientRole in clientRoles) { claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, clientRole.ToString())); } }
public override Task TokenValidated(TokenValidatedContext context) { ClaimsPrincipal = context.Principal.Transform(ClaimType); BedrockUser = SecurityModel.BedrockUser.CreateFromPrincipal(ClaimsPrincipal, ClaimType); var bedrockIdentity = new BedrockIdentity(BedrockUser); var bedrockPrincipal = new BedrockPrincipal(BedrockUser, bedrockIdentity); bedrockIdentity.AddClaims(ClaimsPrincipal.Claims); bedrockPrincipal.AddIdentity(bedrockIdentity); context.Principal = bedrockPrincipal; Thread.CurrentPrincipal = bedrockPrincipal; ClaimsPrincipal = bedrockPrincipal; return(base.TokenValidated(context)); }
/// <summary> /// Invoked when an IdToken has been validated and produced an AuthenticationTicket. /// See: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.openidconnect.openidconnectevents.ontokenvalidated?view=aspnetcore-3.1 /// </summary> /// <param name="context"></param> /// <returns></returns> private static async Task OnTokenValidatedFunc(TokenValidatedContext context) { // Record the user login var loggerFactory = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger <Startup>(); var clientIP = context.HttpContext.Connection.RemoteIpAddress; var userName = context.Principal.Identity.Name; var status = "Successful login"; logger.LogInformation("User login - {ClientIp} - {UserName} - {Status}", clientIP, userName, status); // Query additional user properties from Graph API await GetGraphClaims(context).ConfigureAwait(false); await Task.CompletedTask.ConfigureAwait(false); }
public void Validate(TokenValidatedContext context) { ClaimsPrincipal userPrincipal = context.Principal; ClaimsIdentity claimsIdentity = context.Principal.Identity as ClaimsIdentity; if (claimsIdentity?.Claims == null || !claimsIdentity.Claims.Any()) { context.Fail("This is not our issued token. It has no claims."); return; } Claim serialNumberClaim = claimsIdentity.FindFirst(ClaimTypes.SerialNumber); if (serialNumberClaim == null) { context.Fail("This is not our issued token. It has no serial."); return; } string userIdString = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value; if (!int.TryParse(userIdString, out int userId)) { context.Fail("This is not our issued token. It has no user-id."); return; } Models.DbModels.User user = userService.FindUser(userId); if (user == null || user.SerialNumber != serialNumberClaim.Value || user.IsDeleted) { // user has changed his/her password/roles/stat/IsActive context.Fail("This token is expired. Please login again."); } JwtSecurityToken accessToken = context.SecurityToken as JwtSecurityToken; if (accessToken == null || string.IsNullOrWhiteSpace(accessToken.RawData) || !tokenStoreService.IsValidToken(accessToken.RawData, userId)) { context.Fail("This token is not in our database."); return; } //userService.UpdateUserLastActivityDate(userId); }
/// <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 async Task ValidateAsync(TokenValidatedContext context) { var claimsIdentity = context.Principal.Identity as ClaimsIdentity; if (claimsIdentity?.Claims == null || !claimsIdentity.Claims.Any()) { context.Fail("This is not our issued token. It has no claims."); return; } var serialNumberClaim = claimsIdentity.FindFirst(ClaimTypes.SerialNumber); if (serialNumberClaim == null) { context.Fail("This is not our issued token. It has no serial."); return; } var userIdString = claimsIdentity.FindFirst(ClaimTypes.UserData).Value; if (!int.TryParse(userIdString, out int userId)) { context.Fail("This is not our issued token. It has no user-id."); return; } var user = _usersService.GetUserById(userId); if (user == null || user.Deleted != 0) { // user has changed his/her password/roles/stat/IsActive context.Fail("This token is expired. Please login again."); } if (user.LockoutEnabled) { context.Fail("Tài khoản đã bị bán"); } if (!(context.SecurityToken is JwtSecurityToken accessToken) || string.IsNullOrWhiteSpace(accessToken.RawData) || !_tokenStoreService.IsValidToken(accessToken.RawData, userId)) { context.Fail("This token is not in our database."); return; } AccessControl.User = user; }
/// <summary> /// Called every time that a request arrives in a method with '[Authorize]' decorator. /// </summary> /// <param name="context"></param> /// <returns></returns> public override Task TokenValidated(TokenValidatedContext context) { // Get the name associated with the token. var userName = context.Ticket.Principal.Identity.Name; // Get the global repository. var repository = context.HttpContext.RequestServices.GetService(typeof(IRepository)) as IRepository; // if NOT exist a register in db corresponding to the identity name of the token. if (!repository.Exist <User>(c => c.FirstName == userName)) { // then return Unauthorized. context.Response.StatusCode = 401; context.SkipToNextMiddleware(); } // Auth successful. return(Task.FromResult(0)); }
private static bool IsTokenValid(TokenValidatedContext context) { const string claimTypeClientId = "clientId"; var accessToken = context.SecurityToken as JwtSecurityToken; if (!CheckRoleInAccessToken(accessToken)) { return(false); } if (!context.Principal.HasClaim(claim => claim.Type == claimTypeClientId)) { return(false); } var clientId = context.Principal.Claims.First(claim => claim.Type == claimTypeClientId).Value; context.Request.Headers["X-GatewayID"] = clientId; return(true); }
private async Task JwtValidated(TokenValidatedContext context) { var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>(); var userIdStr = context.Principal.Identity.Name; if (!int.TryParse(userIdStr, out var userId)) { //TODO logger.LogError($"User {userIdStr} have invalid Id"); return; } var user = await userService.GetByIdAsync(userId); if (user == null) { context.Fail("Unauthorized"); } }
private async Task <UserDetail> GetUserDetails(TokenValidatedContext context) { var email = context.Principal.Identity.Name; var results = await _cpClient.User.SearchAsync(new UserSearchRequest { Filter = FilterBase.FromExpression <User>(u => u.EmailAddress, email) }); if (results.Results.Count != 1) { throw new Exception("Unable to find the logged-in user in CP"); } var userId = results.Results.Single().Id; return(await _cpClient.User.GetAsync(userId)); }
public async Task ValidateAsync(TokenValidatedContext context) { var userPrincipal = context.Principal; var claimsIdentity = userPrincipal.Identity as ClaimsIdentity; if (claimsIdentity?.Claims == null || !claimsIdentity.Claims.Any()) { context.Fail("This is not our issued token. It has no claims."); return; } var serialNumber = claimsIdentity.FindFirst(ClaimTypes.SerialNumber); if (serialNumber == null) { context.Fail("This is not our issued token. It has no serial."); return; } var userIdString = claimsIdentity.FindFirst(ClaimTypes.UserData).Value; if (!int.TryParse(userIdString, out int userId)) { context.Fail("This is not our issued token. It has no user-id."); return; } var user = await _usersService.GetUserAsync(userId); if (user == null || user.SerialNumber != serialNumber.Value || !user.IsLocked) { context.Fail("This token is expired. Please login again."); } if (!(context.SecurityToken is JwtSecurityToken accessToken) || string.IsNullOrWhiteSpace(accessToken.RawData) || !await _tokenStoreService.IsValidTokenAsync(accessToken.RawData, userId)) { context.Fail("This token is not in our database."); return; } await _usersService.UpdateUserLastActivityAsync(userId); }
public async Task ValidateAsync(TokenValidatedContext context) { var principal = context.Principal; var claimsIdentity = principal.Identity as ClaimsIdentity; if (claimsIdentity?.Claims == null || !claimsIdentity.Claims.Any()) { context.Fail("This is not our issued token. It has no claims."); return; } var serialNumberClaim = claimsIdentity.FindFirst(UserClaimTypes.SerialNumber); if (serialNumberClaim == null) { context.Fail("This is not our issued token. It has no serial-number."); return; } var userIdString = claimsIdentity.FindFirst(UserClaimTypes.UserId).Value; if (!long.TryParse(userIdString, out var userId)) { context.Fail("This is not our issued token. It has no user-id."); return; } var user = await FindUserAsync(userId); if (!user.HasValue || user.Value.SecurityStamp != serialNumberClaim.Value || !user.Value.IsActive) { // user has changed his/her password/permissions/roles/stat/IsActive context.Fail("This token is expired. Please login again."); return; } if (!(context.SecurityToken is JwtSecurityToken token) || string.IsNullOrWhiteSpace(token.RawData) || !await _token.IsValidTokenAsync(userId, token.RawData)) { context.Fail("This token is not in our database."); } }
public async Task TokenValidated(TokenValidatedContext context) { //Add the access token to the claims var claimsId = context.Principal.Identity as ClaimsIdentity; if (claimsId != null) { claimsId.AddClaim(new Claim(AuthCore.ClaimTypes.AccessToken, (context.SecurityToken as JwtSecurityToken).RawData)); } var jwt = context.SecurityToken as JwtSecurityToken; //This algorithm check NEEDS to stay, we have to make sure it is not set to none //If this were to be set to none, the signature check would pass since it //would be set to none, this would make it trivial to forge jwts. if (!jwt.Header.Alg.Equals(securityTokenAlgo, StringComparison.Ordinal)) { throw new InvalidOperationException($"Algorithm must be '{securityTokenAlgo}'"); } var now = DateTime.UtcNow; if (now < (jwt.ValidFrom - clockSkew) || now > (jwt.ValidTo + clockSkew)) { //Check dates, return unauthorized if they do not match context.Fail($"Dates not valid. Time is {now} token valid from: {jwt.ValidFrom} to: {jwt.ValidTo}"); context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; } var authContext = new AuthorizeUserContext(context.Principal, context.HttpContext); if (OnAuthorizeUser != null) { await OnAuthorizeUser.Invoke(authContext); } if (authContext.IsRejected) { //Check that the rejected claim was not set somewhere, keep this last to ensure its picked up context.Fail("Principal was rejected."); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; } }
private static Task OnTokenValidatedAsync(TokenValidatedContext context) { if (context.SecurityToken is JwtSecurityToken accessToken && context.Principal.Identity is ClaimsIdentity identity && identity.IsAuthenticated) { // add the access token to the identity claims in case it is needed later identity.AddClaim(new Claim(AuthConstants.PRIME_ACCESS_TOKEN_KEY, accessToken.RawData)); identity.AddClaim(new Claim(ClaimTypes.Name, accessToken.Subject)); // flatten realm_access because Microsoft identity model doesn't support nested claims AddRolesForRealmAccessClaims(identity); // flatten resource_access because Microsoft identity model doesn't support nested claims AddRolesForResourceAccessClaims(identity); } return(Task.CompletedTask); }
public override async Task TokenValidated(TokenValidatedContext context) { await Task.Run(() => { context.NoResult(); if (context.SecurityToken is JwtSecurityToken accessToken) { string cachedToken = _jwtService.Find(accessToken.Id); if (!string.IsNullOrEmpty(cachedToken)) { context.Success(); } else { context.Fail("Cannot find token in identity server"); } } }); }
public override Task TokenValidated(TokenValidatedContext context) { var identity = (ClaimsIdentity)context.Principal !.Identity !; if (!string.IsNullOrWhiteSpace(options.OidcRoleClaimType) && options.OidcRoleMapping?.Count >= 0) { var role = identity.FindFirst(x => x.Type == options.OidcRoleClaimType)?.Value; if (!string.IsNullOrWhiteSpace(role) && options.OidcRoleMapping.TryGetValue(role, out var permissions) && permissions != null) { foreach (var permission in permissions) { identity.AddClaim(new Claim(SquidexClaimTypes.Permissions, permission)); } } } return(base.TokenValidated(context)); }
public override async Task TokenValidated(TokenValidatedContext context) { var email = context.Ticket.Principal.Claims.Where(c => c.Type == ClaimTypes.Email) .Select(c => c.Value).SingleOrDefault(); var sentMail = await _mailSentRepository.GetRegisterAsync(email); if (sentMail == null) { var firstName = context.Ticket.Principal.Claims.Where(c => c.Type == ClaimTypes.GivenName) .Select(c => c.Value).SingleOrDefault(); var message = NotificationMessageHelper.GenerateRegistrationMessage(firstName, email); await _emailsQueue.PutMessageAsync(message); await _mailSentRepository.SaveRegisterAsync(email); } await base.TokenValidated(context); }
private static async Task OnTokenValidated(TokenValidatedContext tokenContext) { var identity = tokenContext.Ticket.Principal.Identity as ClaimsIdentity; var providerId = identity?.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value; if (providerId == null) { return; } var userHandler = tokenContext.HttpContext.RequestServices.GetRequiredService <UserHandler>(); var userId = await userHandler.GetUserIdOrNullAsync(providerId); if (userId != null) { identity.AddClaim(new Claim("GaverUserId", userId.Value.ToString(), ClaimValueTypes.Integer32)); } }
/// <summary> /// 验证 /// </summary> /// <param name="context"></param> /// <returns></returns> public static Task JWTValidateAsync(TokenValidatedContext context) { if (context == null) { throw new System.ArgumentNullException(nameof(context)); } var userId = context.Principal.Claims.FirstOrDefault(claim => claim.Type == JwtRegisteredClaimNames.NameId || claim.Type == ClaimTypes.NameIdentifier || claim.Type == "Id")?.Value; if (userId == null) { context.NoResult(); //返回 400 验证错误 context.Response.StatusCode = 400; context.Response.ContentType = "text/plain"; context.Response.WriteAsync("Authenrize Failed-No User KeyId").Wait(); } //// Get an instance using DI //var dbContext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>(); //var user = dbContext.Users.Find(userId); //if (user == null) //{ // context.NoResult(); // //返回 400 验证错误 // context.Response.StatusCode = 400; // context.Response.ContentType = "text/plain"; // context.Response.WriteAsync("Authenrize Failed-No User Find").Wait(); //} //else //{ // var SecurityStamp = context.Principal.Claims.FirstOrDefault(claim => claim.Type == JwtRegisteredClaimNames.Jti || claim.Type == "AspNet.Identity.SecurityStamp")?.Value; // if(user.SecurityStamp != SecurityStamp) // { // context.NoResult(); // //返回 400 验证错误 // context.Response.StatusCode = 400; // context.Response.ContentType = "text/plain"; // context.Response.WriteAsync("Authenrize Failed-User Refreshed").Wait(); // } //} return(Task.CompletedTask); }
public override Task TokenValidated(TokenValidatedContext context) { var identity = (ClaimsIdentity)context.Principal !.Identity !; if (!string.IsNullOrWhiteSpace(options.OidcRoleClaimType) && options.OidcRoleMapping?.Count >= 0) { var permissions = options.OidcRoleMapping .Where(r => identity.HasClaim(options.OidcRoleClaimType, r.Key)) .SelectMany(r => r.Value) .Distinct(); foreach (var permission in permissions) { identity.AddClaim(new Claim(SquidexClaimTypes.Permissions, permission)); } } return(base.TokenValidated(context)); }
public static Task OnTokenValidated(TokenValidatedContext context) { var userId = context.Principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Sid)?.Value; if (!string.IsNullOrWhiteSpace(userId)) { var cachingProvider = context.HttpContext.RequestServices.GetService(typeof(ICachingProvider)) as ICachingProvider; if (cachingProvider != null) { var key = CacheKey.Token(userId); var token = cachingProvider.CreateCaching().Get <Token>(key); if (token != null) { var accessToken = (context.SecurityToken as JwtSecurityToken).RawData; if (!string.IsNullOrWhiteSpace(accessToken)) { if (token.AccessToken != accessToken) { context.ValidateFail("access token invalid"); } } else { context.ValidateFail("access token exception"); } } else { context.ValidateFail("token invalid"); } } else { context.ValidateFail("internal exception"); } } else { context.ValidateFail("uid invalid"); } return(Task.FromResult(0)); }
private Task TokenValidated(TokenValidatedContext context) { // Retriever caller data from the incoming principal string issuer = context.SecurityToken.Issuer; string subject = context.SecurityToken.Subject; string tenantID = context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; // Build a dictionary of approved tenants IEnumerable <string> approvedTenantIds = new List <string> { "9188040d-6c67-4c5b-b112-36a304b66dad" // MSA Tenant }; if (!approvedTenantIds.Contains(tenantID)) { throw new SecurityTokenValidationException(); } return(Task.FromResult(0)); }
public async static Task ValidatedTokenAsync(TokenValidatedContext context) { if (context.HttpContext.RequestServices == null) { throw new InvalidOperationException("RequestServices is null"); } var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>(); var signInManager = context.HttpContext.RequestServices.GetRequiredService <JwtBearerSignInManager>(); var userId = userService.GetProperUserId(context.Ticket.Principal); var user = await userService.GetUserByIdAsync(userId.Value); // validate security token if (!await signInManager.ValidateSecurityStampAsync(user, context.Ticket.Principal)) { throw new SecurityTokenValidationException("Bad security stamp."); } }