.net core 授权验证学习


 

1、Cookies 授权验证方式

  Startup.cs 文件

 

  // 注册Cookie认证服务

  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
  {
  o.ExpireTimeSpan = TimeSpan.FromDays(1);

  ….
  });

  

  //身份认证中间件

  app.UseAuthentication();

  //授权中间件
  app.UseAuthorization();

 

  Cookies 的写入

//用户信息
var claims = new List<Claim>();
claims.Add(new Claim("id", "Id 值"));
claims.Add(new Claim("name", "Name 值"));
claims.Add(new Claim("role", "角色值"));
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(claimsIdentity);

//写入Cookies
await this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,principal);

  

  在需要授权的地api 方法上增加Cookies 验证特性

  [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

 

  //设置支持多种请认方式,以下为 Token 和 cookies 两种认证方式

  [Authorize(AuthenticationSchemes = “Cookies,Bearer”)]

 

2、Jwt Token 授权方式

  

//配置 Jwt 认证服务
services
.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<TokenOptions>>((options, tokenOptions) =>
{
    var opt = tokenOptions.Value;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = opt.Issuer != null,
        ValidateAudience = opt.Audience != null,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,

        ClockSkew = TimeSpan.FromMinutes(30),
        ValidIssuer = opt.Issuer,
        ValidAudience = opt.Audience,
        IssuerSigningKey = opt.ToSecurityKey()
    };
});

//注册 Jwt 认证服务
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();

  

.net core 授权验证学习

 1 /// <summary>
 2     /// 表示token选项
 3     /// </summary>
 4     public class TokenOptions
 5     {
 6         /// <summary>
 7         /// 证书路径
 8         /// </summary>
 9         public string Pfx { get; set; } = "certs/jwt/jwt.pfx";
10 
11         /// <summary>
12         /// 安全算法
13         /// </summary>
14         public string SecurityAlgorithm { get; set; } = SecurityAlgorithms.RsaSha256;
15 
16         /// <summary>
17         /// Issuer字段
18         /// </summary>
19         public string? Issuer { get; set; } = "http://medical.com";
20 
21         /// <summary>
22         /// Audience字段
23         /// </summary>
24         public string? Audience { get; set; }
25 
26         /// <summary>
27         /// 过期时间
28         /// </summary>
29         public TimeSpan Expire { get; set; } = TimeSpan.FromDays(365);
30 
31         /// <summary>
32         /// 转换为安全键
33         /// </summary>
34         /// <returns></returns>
35         public SecurityKey ToSecurityKey()
36         {
37             var path = Path.Combine(AppContext.BaseDirectory, this.Pfx);
38             var certificate = new X509Certificate2(path);
39             return new X509SecurityKey(certificate);
40         }
41 
42         /// <summary>
43         /// 创建jwt
44         /// </summary> 
45         /// <param name="claims"></param>
46         /// <param name="expire"></param> 
47         /// <returns></returns>
48         public TokenResult CreateToken(IEnumerable<Claim> claims, TimeSpan? expire = null)
49         {
50             var securityKey = this.ToSecurityKey();
51             var signingCredentials = new SigningCredentials(securityKey, this.SecurityAlgorithm);
52             var jwtHandler = new JwtSecurityTokenHandler();
53 
54             var expireValue = expire == null ? this.Expire : expire.Value;
55             var jwt = jwtHandler.CreateJwtSecurityToken(
56                 issuer: this.Issuer,
57                 audience: this.Audience,
58                 expires: DateTime.Now.Add(expireValue),
59                 signingCredentials: signingCredentials,
60                 subject: new ClaimsIdentity(claims)
61             );
62             var token = jwtHandler.WriteToken(jwt);
63             return new TokenResult
64             {
65                 Access_token = token,
66                 Expires_in = (long)expireValue.TotalSeconds,
67                 Refresh_token = null,
68                 Token_type = "bearer"
69             };
70         }
71     }

TokenOptions
.net core 授权验证学习

/// <summary>
    /// 表示token描述
    /// </summary>
    public class TokenResult
    {
        /// <summary>
        /// token值
        /// </summary>
        public string Access_token { get; set; } = string.Empty;

        /// <summary>
        /// 过期时间戳(秒)
        /// </summary>
        public long Expires_in { get; set; }

        /// <summary>
        /// token类型
        /// </summary>
        public string Token_type { get; set; } = "bearer";

        /// <summary>
        /// 刷新token
        /// </summary>
        public string? Refresh_token { get; set; }
    }

TokenResult.cs

 

 

备注:程序运行时经常出现以下异常:

Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager

解决办法

  1、服务注册,重定义新的目录;

    services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, “DataProtection”)));

  2、删除 C:/Users/******/AppData/Local/ASP.NET/DataProtection-Keys 下的所有文件

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/278716.html

(0)
上一篇 2022年8月3日
下一篇 2022年8月3日

相关推荐

发表回复

登录后才能评论