コード例 #1
0
        public async Task <IActionResult> Token(LoginForm loginForm)
        {
            if (loginForm.Grant_Type == "password")
            {
                if (!string.IsNullOrWhiteSpace(loginForm.Username))
                {
                    var username = _context.Students.Where(s => s.Username == loginForm.Username).FirstOrDefault()?.Username;
                    if (username == null)
                    {
                        return(Unauthorized(new { error = "Incorrect username." }));
                    }
                    var user = await _userManager.FindByNameAsync(username);

                    Microsoft.AspNetCore.Identity.SignInResult password_check =
                        await _signInManager.CheckPasswordSignInAsync(user, loginForm.Password, false);

                    if (!password_check.Succeeded)
                    {
                        return(Unauthorized(new { error = "Incorrect password." }));
                    }
                    _refreshTokenManager.RemoveByUsername(username);
                    var claims = new[]
                    {
                        new Claim("Username", username)
                    };
                    var secretBytes = Encoding.UTF8.GetBytes(Constants.Secret);
                    var key         = new SymmetricSecurityKey(secretBytes);
                    var algorithm   = SecurityAlgorithms.HmacSha256;

                    var signingCredentials = new SigningCredentials(key, algorithm);
                    var now   = DateTime.Now;
                    var token = new JwtSecurityToken(
                        Constants.Issuer,
                        Constants.Audiance,
                        claims,
                        notBefore: now,
                        expires: now.AddMinutes(5),
                        signingCredentials);

                    var access_token  = new JwtSecurityTokenHandler().WriteToken(token);
                    var refresh_token = GenerateRefreshTokenString();
                    _refreshTokenManager.Add(new RefreshToken(username, refresh_token, now.AddHours(1)));
                    return(Ok(new { current_time = now, access_token, access_token_expires = now.AddMinutes(5), refresh_token, refresh_token_expires = now.AddHours(1) }));
                }
                return(Unauthorized(new { error = "Missing username." }));
            }
            if (loginForm.Grant_Type == "refresh_token")
            {
                if (string.IsNullOrWhiteSpace(loginForm.Refresh_Token))
                {
                    return(Unauthorized(new { error = "Missing refresh token." }));
                }
                try
                {
                    var _refresh_token = _refreshTokenManager.Get(loginForm.Refresh_Token);
                    if (_refresh_token == null)
                    {
                        return(Unauthorized(new { error = "Invalid refresh token." }));
                    }
                    var now = DateTime.Now;
                    //if refresh token expired
                    if (_refresh_token.ExpiresAt < now)
                    {
                        return(Unauthorized(new { error = "Expired refresh token." }));
                    }
                    //generate access token, remove old and generate new refresh token
                    _refreshTokenManager.Remove(_refresh_token);
                    var claims = new[]
                    {
                        new Claim("Username", _refresh_token.Username)
                    };
                    var secretBytes = Encoding.UTF8.GetBytes(Constants.Secret);
                    var key         = new SymmetricSecurityKey(secretBytes);
                    var algorithm   = SecurityAlgorithms.HmacSha256;

                    var signingCredentials = new SigningCredentials(key, algorithm);
                    var token = new JwtSecurityToken(
                        Constants.Issuer,
                        Constants.Audiance,
                        claims,
                        notBefore: now,
                        expires: now.AddMinutes(5),
                        signingCredentials);

                    var access_token  = new JwtSecurityTokenHandler().WriteToken(token);
                    var refresh_token = GenerateRefreshTokenString();
                    _refreshTokenManager.Add(new RefreshToken(_refresh_token.Username, refresh_token, now.AddHours(1)));
                    return(Ok(new { current_time = now, access_token, access_token_expires = now.AddMinutes(5), refresh_token, refresh_token_expires = now.AddHours(1) }));
                }
                catch (SecurityTokenException e)
                {
                    return(Unauthorized(new { error = e.Message }));
                }
            }
            return(Unauthorized($"Invalid 'grant_type':'{loginForm.Grant_Type}'"));
        }