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;
            }
        }
        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 = await _usersService.FindUserAsync(userId);

            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.");
            }

            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.UpdateUserLastActivityDateAsync(userId);
        }
示例#3
0
        private static async Task OnTokenValidatedAsync(TokenValidatedContext context)
        {
            var userValidator = context.HttpContext.RequestServices.GetRequiredService <IUserValidator>();
            var username      = context.Principal.Identity.Name;
            var doesUserExist = await userValidator.CheckIsUsernameAlreadyTakenAsync(username);

            if (!doesUserExist)
            {
                context.Fail("Unauthorized");
            }
        }
示例#4
0
        private Task OnTokenValidated(TokenValidatedContext context)
        {
            var validIssuers = FakeDatabaseService.Tenants.Select(t => $"https://login.microsoftonline.com/{t}/v2.0");

            if (!validIssuers.Contains(context.Principal.Claims.FirstOrDefault(c => c.Type == "iss").Value))
            {
                context.Fail("Issuer Validation failed!");
            }

            return(Task.FromResult(0));
        }
        static Task AccountActiveValidate(TokenValidatedContext context)
        {
            var activeClaim = context.Principal.FindFirst("lockout");

            if (activeClaim != null && activeClaim.Value.Equals("1"))
            {
                context.Fail("账号被锁定");
            }

            return(Task.CompletedTask);
        }
        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 userId = claimsIdentity.FindAll(ClaimTypes.NameIdentifier).Last().Value;

            if (string.IsNullOrWhiteSpace(userId))
            {
                context.Fail("This is not our issued token. It has no user-id.");
                return;
            }


            var accessToken = context.SecurityToken as JwtSecurityToken;

            if (accessToken == null || string.IsNullOrWhiteSpace(accessToken.RawData))
            {
                context.Fail("This token is not in our database.");
                return;
            }

            var r         = _dbContext.UserTokens.Count();
            var userToken = await
                            _dbContext.UserTokens.FirstOrDefaultAsync(x => x.AccessToken == accessToken.RawData &&
                                                                      x.OwnerUserId == Int32.Parse(userId));


            if (userToken?.AccessTokenExpiration >= DateTime.UtcNow)
            {
            }
            else
            {
                context.Fail("This token is not in our database.");
            }
        }
        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 phoneNumberClaim = claimsIdentity.FindFirst(ClaimTypes.MobilePhone);

            if (phoneNumberClaim == null)
            {
                context.Fail("This is not our issued token. It has no phone.");
                return;
            }

            var customerIdString = claimsIdentity.FindFirst(ClaimTypes.UserData).Value;

            if (!int.TryParse(customerIdString, out int customerId))
            {
                context.Fail("This is not our issued token. It has no customer-id.");
                return;
            }

            var customer = _customerService.GetCustomerById(customerId);

            if (customer == null || !customer.Active)
            {
                // customer has changed his/her password/roles/stat/IsActive
                context.Fail("This token is expired. Please login again.");
            }

            var accessToken = context.SecurityToken as JwtSecurityToken;

            if (string.IsNullOrWhiteSpace(accessToken?.RawData) || !_tokenStoreService.IsValidToken(accessToken.RawData, customerId))
            {
                context.Fail("This token is not in our database.");
            }
        }
示例#8
0
        private static Task OnTokenValidated(TokenValidatedContext context)
        {
            var acrClaim = context.Principal.FindFirst("acr");

            if (acrClaim == null)
            {
                context.Fail("Unauthorized!");
            }

            if (string.IsNullOrEmpty(acrClaim.Value))
            {
                context.Fail("Unauthorized!");
            }

            if (context.Properties.GetParameter <bool>(Insolvency.Interfaces.Constants.ShouldUseMfaKey) && acrClaim.Value.Trim().ToLower() != AcrMfaChallengeClaimValue)
            {
                context.Fail("Unauthorized!");
            }

            return(Task.CompletedTask);
        }
示例#9
0
        public override async Task TokenValidated(TokenValidatedContext context)
        {
            if (!(await PopulateCurrentUserFromDb(context.Principal)))
            {
                context.Fail("Access Denied");
                return;
            }

            _curentUser.UserInfo = await _userService.GetCurrentUserAsync();

            AddClaimsFromUserInfo(context.Principal, _curentUser.UserInfo);
        }
示例#10
0
        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 userId      = claimsIdentity.FindFirst("ID").Value;
            var accessToken = context.SecurityToken as JwtSecurityToken;

            if (accessToken == null || string.IsNullOrWhiteSpace(accessToken.RawData) || !await jwtToken.IsValidTokenAsync(accessToken.RawData, userId))
            {
                context.Fail("This token is not in our database.");

                return;
            }
        }
示例#11
0
        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;

            var cancellationTokenSource = new CancellationTokenSource();
            var user = await _usersStoreService.FindByIdAsync(userIdString, cancellationTokenSource.Token);

            if (user == null || user.SecurityStamp != serialNumberClaim.Value)
            {
                // 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, userIdString))
            {
                context.Fail("This token is not in our database.");
                return;
            }
            await _lastLoggedIn.UpdateUserLastActivityDateAsync(userIdString, cancellationTokenSource.Token);
        }
示例#12
0
        private async Task OnTokenValidated(TokenValidatedContext arg)
        {
            var provider = arg.HttpContext.RequestServices.GetRequiredService <IPersonProjectionStore>();
            var profile  = await provider.GetProfileAsync(arg.Scheme.Name, arg.Principal.FindFirstValue("sub"));

            if (profile == null)
            {
                arg.Fail("Unable to find a valid userId");
                return;
            }

            arg.Principal = new ClaimsPrincipal(YayNayIdentity.Create(profile, arg.Scheme.Name));
        }
示例#13
0
        private Task OnTokenValidated(TokenValidatedContext context)
        {
            var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
            var userId      = int.Parse(context.Principal.Identity.Name);
            var user        = userService.GetById(userId);

            if (user == null)
            {
                // return unauthorized if user no longer exists
                context.Fail("Unauthorized");
            }
            return(Task.CompletedTask);
        }
示例#14
0
        /// <summary>
        /// Token验证通过时,从OnlineUser缓存或数据库查找用户的最新信息附加到有效的 ClaimPrincipal 上
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task TokenValidated(TokenValidatedContext context)
        {
            ClaimsPrincipal user     = context.Principal;
            ClaimsIdentity  identity = user.Identity as ClaimsIdentity;

            IUserClaimsProvider accessClaimsProvider = context.HttpContext.RequestServices.GetService <IUserClaimsProvider>();
            OperationResult <ClaimsIdentity> result  = await accessClaimsProvider.RefreshIdentity(identity);

            if (!result.Succeeded)
            {
                context.Fail(result.Message);
            }
        }
示例#15
0
        private Task OnTokenValidatedHandler(TokenValidatedContext context)
        {
            var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
            var userId      = int.Parse(context.Principal.Identity.Name);
            var user        = userService.GetByIdAsync(userId);

            if (user == null)
            {
                context.Fail(AppConfiguration.Unauthorized);
            }

            return(Task.CompletedTask);
        }
示例#16
0
        public async ValueTask ValidateAsync(TokenValidatedContext context)
        {
            var claimsIdentity = context.Principal.Identity as ClaimsIdentity;

            if (claimsIdentity?.Claims is null || !claimsIdentity.Claims.Any())
            {
                context.Fail("This is not our issued token.");
                return;
            }

            var jtiString = claimsIdentity.FindFirst(JwtRegisteredClaimNames.Jti)?.Value;

            if (jtiString is null || !Guid.TryParse(jtiString, out var jti))
            {
                context.Fail("This is not our issued token.");
                return;
            }

            var token = await _jwtIdentityDb.AccessTokens.FirstOrDefaultAsync(t => t.Id == jti);

            if (token is null || token.ExpiresTime < DateTime.Now)
            {
                if (token.ExpiresTime < DateTime.Now)
                {
                    _jwtIdentityDb.Remove(token);
                    await _jwtIdentityDb.SaveChangesAsync();
                }
                context.Fail("Token is not valid");
            }

            token.LastLoginTime      = DateTime.Now;
            token.LastLoginIp        = _context.Connection.RemoteIpAddress.ToString();
            token.LastLoginUserAgent = _context.Request.Headers["User-Agent"][0];
            _jwtIdentityDb.Update(token);
            await _jwtIdentityDb.SaveChangesAsync();

            context.Success();
        }
        public override Task TokenValidated(TokenValidatedContext context)
        {
            var _principal = context.Principal;
            var _username  = _principal.Identity.Name;

            if (!AppSettings.Username.Equals(_username))
            {
                Log.LogInformation($"Benutzername '{ _username}' nicht identisch.");
                context.Response.StatusCode = 401;
                context.Fail("Token invalid");
            }

            return(Task.CompletedTask);
        }
        public override Task TokenValidated(TokenValidatedContext context)
        {
            if (context.SecurityToken is JwtSecurityToken accessToken)
            {
                var result = _tokenFactory.RefreshCacheToken(accessToken.RawData);

                if (!result)
                {
                    context.Fail("UnAuthorized. Session Jwt token not valid in Service store.");
                }
            }

            return(Task.CompletedTask);
        }
        /// <summary>
        /// The user may be authenticated but the security stamp could
        /// have been changed and therefore not be authenticated anymore.
        /// In the claims principal of <paramref name="context"/> we rely on
        /// <see cref="ClaimsIdentityOptions.UserIdClaimType"/> and
        /// <see cref="ClaimsIdentityOptions.SecurityStampClaimType"/>.
        /// Therefore it should be in need of, that
        /// <see cref="ValidateRefreshTokenIdClaim(TokenValidatedContext)"/>
        /// is called first.
        /// </summary>
        public static async Task ValidateSecurityStamp(TokenValidatedContext context)
        {
            var signInManager = context.HttpContext.RequestServices.GetService <SignInManager <UserEntity> >();
            // Why does this works?? IdentityOptions.ClaimIdentity.UserIdClaimType is by default
            // ClaimTypes.NameIdentifier, and this one will be grabbed, if not user will be null.
            var user = await signInManager.ValidateSecurityStampAsync(context.Principal);

            /// The result of <see cref="TokenValidatedContext.Result"/> will be set.
            /// And when it is faulty, then this result will be the http response.
            if (user == null)
            {
                context.Fail("You are not authenticated anymore.");
            }
        }
示例#20
0
        public override async Task TokenValidated(TokenValidatedContext context)
        {
            PopulateCurrentUser(context.Principal);

            if (_curentUser.UserGuid == null)
            {
                context.Fail("Access Denied");
                return;
            }

            var userExists = await _userService.ProcessFirstUserLoginAsync();

            if (!userExists)
            {
                context.Fail($"Access Denied - User[{_curentUser.UniversalId}] does not exist");
                return;
            }

            _curentUser.UserInfo = await _userService.GetCurrentUserAsync();

            AddClaimsFromUserInfo(context.Principal, _curentUser.UserInfo);

            await Task.CompletedTask;
        }
示例#21
0
        private static async Task OnTokenValidatedFunc(TokenValidatedContext context)
        {
            string?email = context.Principal?.Identity?.Name;
            var    readCmsItemService = context.HttpContext.RequestServices.GetRequiredService <IReadCmsItem>();

            var(users, total) = await readCmsItemService.List(CmsUser.DefaultCmsType, null, null, searchQuery : email);

            if (users.Count == 0 || string.IsNullOrWhiteSpace(email))
            {
                context.Fail($"User ({email}) not added to the CMS.");
            }

            // Custom code here
            await Task.CompletedTask.ConfigureAwait(false);
        }
示例#22
0
        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;
            }
            // claimsIdentity.
            var userId = int.Parse(userPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value);

            var user = await GetByIdAsync(userId);

            if (user == null)
            {
                context.Fail("This is not our issued token. It has no user-id.");
                return;
            }

            await _userData.Init(user);
        }
示例#23
0
        public override async Task TokenValidated(TokenValidatedContext context)
        {
            var(username, userGuid, directory) = context.Principal.GetUserInfo();

            var user = _dbContext.LoadUser(username, userGuid);

            if (user == null)
            {
                context.Fail("Access Denied");
                return;
            }

            context.Principal = user.ToClaimsPrincipal(JwtBearerDefaults.AuthenticationScheme);

            await Task.CompletedTask;
        }
示例#24
0
        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);
            }
        }
示例#25
0
        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");
            }
        }
 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");
             }
         }
     });
 }
        /// <summary>
        /// Sets the user principal
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        private async Task SetPrincipal(TokenValidatedContext ctx)
        {
            if (ctx.Principal != null && ctx.Principal.Identity.IsAuthenticated)
            {
                try
                {
                    // Set user principal. Replace with your custom logic if needed
                    var identity = ctx.Principal.Identity as ClaimsIdentity;
                    var user     = new ClaimsPrincipal(identity);

                    user.AddIdentity(identity);
                    ctx.Principal = user;
                }
                catch (Exception ex)
                {
                    var logger = ctx.HttpContext.RequestServices.GetRequiredService <ILogger <JwtEventHelper> >();
                    logger.LogError(ex, "Setting user principal failed.");
                    ctx.Fail("Setting user principal failed.");
                }
            }
        }
        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;
        }
示例#29
0
        private static Task AdditionalValidation(TokenValidatedContext context)
        {
            var    accessToken     = context.SecurityToken as JwtSecurityToken;
            var    jsonTokenString = accessToken.Payload;
            string role            = jsonTokenString["role"].ToString();

            if (role == "2")
            {
                string query  = "/api/query";
                string search = "/api/search/";
                var    path   = context.Request.Path.Value;
                if (path == query + "/QueryParams" || path.Contains(query + "/List/") || path == search + "Excel" || path == search || path == query)
                {
                    return(Task.CompletedTask);
                }
                else
                {
                    context.Fail("Failed additional validation");
                }
            }

            return(Task.CompletedTask);
        }
示例#30
0
        private async Task OnTokenValidated(TokenValidatedContext context)
        {
            using (var scope = this._provider.CreateScope())
            {
                var db         = scope.ServiceProvider.GetRequiredService <QpancContext>();
                var loggedUser = scope.ServiceProvider.GetRequiredService <ILoggedUser>();
                var sessionId  = Guid.Parse(context.Principal.Claims
                                            .Where(x => x.Type == JwtRegisteredClaimNames.Jti)
                                            .Select(x => x.Value)
                                            .FirstOrDefault());

                var session = await db.Sessions.FindAsync(sessionId);

                if (session == null)
                {
                    context.Fail("");
                }
                else
                {
                    context.Success();
                }
            }
        }