public async Task <ActionResult> RequestToken([FromBody] LoginCommandDTO request)
        {
            if (request == null)
            {
                return(BadRequest());
            }

            // larsson:这里必须startup中设置禁用自动400响应,SuppressModelStateInvalidFilter = true。否则Model验证失败后这里的ProductResource永远是null
            if (!ModelState.IsValid)
            {
                // larsson:如果要自定义422之外的响应则需要新建一个类继承UnprocessableEntityObjectResult
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var(isAuth, result) = await _auth.IsAuthenticated(request);

            if (isAuth)
            {
                return(Ok(result));
            }

            return(BadRequest("wrong user name or password"));
        }
Exemplo n.º 2
0
        public async Task <(bool IsAuthenticated, LoginResultDTO Token)> IsAuthenticated(LoginCommandDTO request)
        {
            var loginCommand = _mapper.Map <LoginCommand>(request);

            // larsson:这里应可以用消息队列(如MediatR)来解耦,实现CQRS
            var loginResult = await _userService.IsUserLoginValid(loginCommand.Username, loginCommand.Password);

            if (!loginResult.IsValid)
            {
                return(false, null);
            }

            LoginResultDTO loginResultDTO = null;

            loginResultDTO = new LoginResultDTO()
            {
                UserId   = loginResult.UserId.ToString(),
                UserName = loginCommand.Username
            };

            var dict = new Dictionary <string, string>();

            dict.Add("UserName", loginResultDTO.UserName);
            dict.Add("UserId", loginResultDTO.UserId);

            var claims      = dict?.Select(x => new Claim(x.Key, x.Value));
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken    = new JwtSecurityToken(
                issuer: _tokenManagement.Issuer,
                audience: _tokenManagement.Audience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration),
                signingCredentials: credentials);

            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            loginResultDTO.Token = token;

            return(true, loginResultDTO);
        }