Exemplo n.º 1
0
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            //根据context.UserName和context.Password与数据库的数据做校验,判断是否合法
            if (!string.IsNullOrWhiteSpace(context.UserName) && !string.IsNullOrWhiteSpace(context.Password))
            {
                AdminUsers user = await _adminUsers.FindByLoginAsync(context.UserName, context.Password);

                if (user != null)
                {
                    context.Result = new GrantValidationResult(
                        subject: context.UserName,
                        authenticationMethod: "custom",
                        claims: new Claim[] { new Claim(JwtClaimTypes.Role, "admin") },
                        authTime: DateTime.Now.AddDays(1)
                        );
                }
                else
                {
                    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "invalid custom credential");
                }
            }
            else
            {
                //验证失败
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            }
        }
Exemplo n.º 2
0
        public async Task <IActionResult> login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                AdminUsers user = await _dapper.FindByLoginAsync(model.UserName, model.Password);

                if (user != null)
                {
                    AuthenticationProperties props = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1)),
                        AllowRefresh = true
                    };
                    //var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    //                identity.AddClaim(new Claim(ClaimTypes.Sid, userName));
                    //                identity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
                    //                 identity.AddClaim(new Claim(ClaimTypes.Role, user.Role));

                    //var Claims = new List<Claim>() { new Claim(JwtClaimTypes.Role, "admin") };
                    await HttpContext.SignInAsync(user.Id.ToString(), user.LoginName, props, new Claim(JwtClaimTypes.Role, "admin"));

                    return(Redirect(model.ReturnUrl ?? "/"));
                }
                else
                {
                    View(model.ReturnUrl);
                }
            }
            return(View(model.ReturnUrl));
        }