Skip to content

03 netcore使用jwt authentication

Jinxin Chen edited this page Mar 12, 2020 · 1 revision

本文介绍如何在.net core中启用jwt authentication及生成token

jwt简介

JSON Web Token(缩写 JWT),一种跨域认证解决方案,它本身包含了认证信息,所以server无需再保存session,做到无状态和方便横向扩展。

JWT 的三个部分依次如下:

  • Header(头部):JSON 对象,类似{"alg": "HS256","typ": "JWT"},描述类型和算法
  • Payload(负载):JSON 对象,存放实际需要传递的数据,官方包含(也可以自定义数据):
    • iss (issuer):签发人
    • exp (expiration time):过期时间
    • sub (subject):主题
    • aud (audience):受众
    • nbf (Not Before):生效时间
    • iat (Issued At):签发时间
    • jti (JWT ID):编号
  • Signature(签名):对前两部分的签名,防止数据篡改。
    • HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

.net core 使用jwt authentication

  1. 提供生成jwt的方法
public Token GetAccessToken(string appID, string appSecret)
{
    var key = System.Text.Encoding.ASCII.GetBytes("[secret]");
    var handler = new JwtSecurityTokenHandler();
    var descriptor = new SecurityTokenDescriptor()
    {
        Subject = new System.Security.Claims.ClaimsIdentity(
            new Claim[]{
                new Claim(ClaimTypes.Name, appID)
            }
        ),
        Expires = DateTime.UtcNow.AddSeconds(_setting.Expired),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
    };
    var token = handler.CreateToken(descriptor);
    var access_token = handler.WriteToken(token);
  1. 在ConfigureServices方法中,加入jwt认证
public void ConfigureServices(IServiceCollection services)
{
    var keyBytes = System.Text.Encoding.ASCII.GetBytes("[secret]");
    // services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme;
    })
    .AddCookie(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme)
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
        {
            IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
            ValidateIssuerSigningKey = true,
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });
  1. 测试认证请求
[Microsoft.AspNetCore.Authorization.Authorize]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    [HttpPost("[action]")]
    public object GetUsers([FromBody] GetUsersModel searchModel)
    {

    }
}

将jwt放在post请求的header中:

Authorization: Bearer [jwt]

请求如上action,验证是否可以正常获取资料

参考

Clone this wiki locally