.net core Jwt 添加

2018-06-17 19:14:49来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

    Jwt 已经成为跨平台身份验证通用方案,如不了解请关注:https://jwt.io/。   

    为了和微软其他验证模块有个比较好的衔接,项目中采用了微软开发的jwt组件: System.IdentityModel.Tokens.Jwt。首先安装:Install-Package System.IdentityModel.Tokens.Jwt。

   在config方法中添加

    

1  if (!HostingEnvironment.IsEnvironment("test"))
2             {
3                 app.UseJwtBearerAuthentication(Jwt.GetJwtOptions());
4             }

 实现一个jwt工具类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IdentityModel.Tokens.Jwt;
 4 using System.Security.Claims;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using AutoMapper;
 8 using Microsoft.AspNet.Hosting;
 9 using Microsoft.AspNetCore.Authentication.JwtBearer;
10 using Microsoft.AspNetCore.Builder;
11 using Microsoft.AspNetCore.Hosting;
12 using Microsoft.AspNetCore.Http;
13 using Microsoft.AspNetCore.Http.Extensions;
14 using Microsoft.Extensions.Configuration;
15 using Microsoft.IdentityModel.Tokens;
16 using NDaisy.Core.ServiceLocator;
17 using WebApiCore.Core.Utility.Extension;
18 using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
19 
20 namespace WebApiCore.Utility
21 {
22     public class Jwt
23     {
24         private static SecurityKey _signKey;
25         private static IConfigurationSection _config;
26         private const string Issue = "webcore";
27         static Jwt()
28         {
29             _config= ServiceLocator.Current.GetInstance<IConfigurationRoot>().GetSection("Jwt");
30             var keyAsBytes = Encoding.ASCII.GetBytes(_config.GetValue<string>("Salt"));
31             _signKey = new SymmetricSecurityKey(keyAsBytes);
32               
33         }
34 
35         public static JwtBearerOptions GetJwtOptions()
36         {
37             return new JwtBearerOptions
38             {
39                 TokenValidationParameters =
40                 {
41                     ValidIssuer = Issue,
42                     IssuerSigningKey = _signKey,
43                     ValidateLifetime = true,
44                     ValidateIssuer = true,
45                     ValidateAudience = false
46                 },
47                   Events = new JwtBearerEvents()
48                   {
49                       OnAuthenticationFailed = c =>
50                       {
51                           
52                           return Task.Run(() =>
53                           {
54                               if (ServiceLocator.Current.GetInstance<IHostingEnvironment>().IsDevelopment())
55                               {
56                                   c.Request.GetDisplayUrl().LogInfo();
57                                   c.Exception.LogError();
58                               }
59 
60                           } );
61                       }
62                    
63                   }
64             };
65         }
66 
67         public static string SignToken(IList<Claim> claims)
68         {
69             var seconds= _config.GetValue<int>("SlideTime");
70              
71             JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(issuer: Issue, claims: claims, expires: DateTime.UtcNow.AddSeconds(seconds), signingCredentials: new SigningCredentials(_signKey, SecurityAlgorithms.HmacSha256));
72              
73             return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
74         }
75     }
76 
77 }
View Code

添加一个获取token的入口,实际项目中,放在登录授权里面:

1  app.Map("/auth/test", appbuilder =>
2             {
3                 appbuilder.Run(d =>
4                 {
5                     var token= Jwt.SignToken(new List<Claim>() {new Claim("name", "ryan")});
6                    
7                     return d.Response.WriteAsync(token);
8                 });
9             });

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:ASP.net 内置对象

下一篇:WebForm aspx页面传值---7种方式