zoukankan      html  css  js  c++  java
  • Token使用

    1.NeGet添加包

    IdentityModel和System.IdentityModel.Tokens.Jwt和Microsoft.AspNetCore.Authorization

    2.Startup.cs注册

        services.AddAuthentication(x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                   .AddJwtBearer(o =>
                   {
                       o.TokenValidationParameters = new TokenValidationParameters
                       {
                           NameClaimType = JwtClaimTypes.Name,
                           RoleClaimType = JwtClaimTypes.Role,
    
                           ValidIssuer = "http://localhost:54427",//这里和方法里面的要一样啊
                           ValidAudience = "api",
                           IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("this is a security key"))
    
                           /***********************************TokenValidationParameters的参数默认值***********************************/
                           // RequireSignedTokens = true,
                           // SaveSigninToken = false,
                           // ValidateActor = false,
                           // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                           // ValidateAudience = true,
                           // ValidateIssuer = true, 
                           // ValidateIssuerSigningKey = false,
                           // 是否要求Token的Claims中必须包含Expires
                           // RequireExpirationTime = true,
                           // 允许的服务器时间偏移量
                           // ClockSkew = TimeSpan.FromSeconds(300),
                           // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                           // ValidateLifetime = true
                       };
                   });

    3.添加中间件

     app.UseAuthentication();

    4.写入Token

      public class UserModel
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string PassWord { get; set; }
            public string Email { get; set; }
    
        }
    
        [Route("api/[controller]/[action]"), ApiController]
        public class TokenController : ControllerBase
        {
            [HttpPost]
            public async Task<IActionResult> GenToken(UserModel model)
            {
                //get username and pwd from this model ,then get data from db 
                //var user = _context.Users.FirstOrDefault(l => l.Name == model.Name && l.Pwd == model.PassWord);
                //If there is data in the database
                var user = new UserModel() { ID = 1, Email = "example@live.com", Name = "tester", PassWord = "123456" };
                //if user null ,return
                if (user == null) return Unauthorized();
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes("this is a security key");
                var authTime = DateTime.UtcNow;
                var expiresAt = authTime.AddDays(7);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(JwtClaimTypes.Audience,"api"),
                        new Claim(JwtClaimTypes.Issuer,"http://localhost:54427"),//这里要和启动项一样啊
                        new Claim(JwtClaimTypes.Id, user.ID.ToString()),
                        new Claim(JwtClaimTypes.Name, user.Name)
                    }),
                    Expires = expiresAt,
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);
                return Ok(new
                {
                    access_token = tokenString,
                    token_type = "Bearer",
                    profile = new
                    {
                        sid = user.ID,
                        name = user.Name,
                        auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                        expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                    }
                });
            }
        }

    5.添加特性自动检测是否有Token

    [Authorize] (检测是否请求头是否有Token,可以添加在控制器和Action上)

    以下是为全局添加特性注册

    services.AddMvc(options=>
                {
                    options.Filters.Add(new AuthorizeFilter());
                }
                )

    特性 [AllowAnonymous] 忽略所有特性检查

    6.使用  Postman  模拟调用和验证

    验证:

  • 相关阅读:
    什么是聚集索引,什么是非聚集索引,什么又是主键?
    给.net添加MultiPage、TabStrip、Toolbar、treeView,treeview等控件
    一个洗牌程序算法,随机交换位置【经典】
    overload和override都叫重载,都在什么情况下用阿?
    补间形状和补间动画
    电子时钟
    绘图板
    查询XML数据
    纯代码生成按钮
    小球滚动,方块上移
  • 原文地址:https://www.cnblogs.com/Blog-JJ/p/11340325.html
Copyright © 2011-2022 走看看