NetCore3.1JWT

1.安装Microsoft.AspNetCore.Authentication.JwtBearer包

2.增加用于验证的实体

public class TokenManagement
    {
        [JsonProperty("secret")]
        public string Secret { get; set; }
        [JsonProperty("issuer")]
        public string Issuer { get; set; }
        [JsonProperty("audience")]
        public string Audience { get; set; }
        [JsonProperty("accessExpiration")]
        public int AccessExpiration { get; set; }
        [JsonProperty("refreshExpiration")]
        public int RefreshExpiration { get; set; }
    }

3.配置文件中增加

  "tokenManagement": {
    "secret": "HSTrade.AppletManage.Api",
    "issuer": "HSTrade.AppletManage.Api",
    "audience": "HSTrade.AppletManage.Api",
    "accessExpiration": 30,
    "refreshExpiration": 60
  }

4.StartUp类中注册Authentication

services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();

services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
        ValidIssuer = token.Issuer,
        ValidAudience = token.Audience,
        ValidateIssuer = false,
        ValidateAudience = false
    };
});

5.注册中间件  app.UseAuthentication();  

6.增加用户类

public class LoginRequestDTO
{
    [Required]
    [JsonProperty("username")]
    public string Username { get; set; }
    [Required]
    [JsonProperty("password")]
    public string Password { get; set; }
}

7.增加接口

public interface IAuthenticateService
{
    bool IsAuthenticated(LoginRequestDTO request, out string token);
}

8.实现接口

public class AuthenticateService : IAuthenticateService
{
    private readonly TokenManagement _tokenManagement;

    public AuthenticateService(IOptions<TokenManagement> tokenManagement)
    {
        this._tokenManagement = tokenManagement.Value;
    }
    public bool IsAuthenticated(LoginRequestDTO request, out string token)
    {
     //这里通过request验证账户密码// token
= string.Empty; var claims = new[] { new Claim(ClaimTypes.Name,request.Username), new Claim(ClaimTypes.Name,request.Password) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret)); SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //var jwtToken = new JwtSecurityToken(new JwtHeader(credentials), new JwtPayload(claims)); var jwtToken = new JwtSecurityToken(_tokenManagement.Issuer, _tokenManagement.Audience, claims, expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration), signingCredentials: credentials); token = new JwtSecurityTokenHandler().WriteToken(jwtToken); return true; } }

9.增加Controller

[ApiController]
[Route("api/auth")]
public class AuthenticationController : ControllerBase
{
    private readonly IAuthenticateService _authService;

    public AuthenticationController(IAuthenticateService authService)
    {
        this._authService = authService;
    }
    [AllowAnonymous]
    [HttpPost,Route("requestToken")]
    public ActionResult RequestToken([FromBody] LoginRequestDTO request)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest("Invalid Request");
        }
        string sToken;
        if (_authService.IsAuthenticated(request, out sToken))
        {
            return Ok(sToken);
        }
        return BadRequest("Invalid Request");
    }
}

 

posted @ 2020-04-02 17:01  houzps  阅读(445)  评论(0)    收藏  举报