zoukankan      html  css  js  c++  java
  • netcore使用jwt-authentication

    本文介绍如何在.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,验证是否可以正常获取资料

    参考

  • 相关阅读:
    PC端圣诞树下载
    win7开机一直在正在启动windows界面怎么办?
    EFI、UEFI、MBR、GPT的区别
    进入BIOS中,设置U盘启动
    CSS3摆动动画效果
    比特币钱包搭建与使用
    自动校时工具
    windows7蓝屏0x000000c4
    如何使用webpack打包你的项目
    开源货币/比特币Multiminer、bitrade、bitcoinjs-lib、python-bitcoinrpc介绍
  • 原文地址:https://www.cnblogs.com/windchen/p/12484432.html
Copyright © 2011-2022 走看看