分享

NET CORE API权限控制之JWT的创建和引用

 丹枫无迹 2021-03-16

在我们的接口调用中,都需要配置权限控制,下面介绍下在ASP NET CORE下使用JWT的步骤:

1.创建鉴权项目

由于鉴权并不需要每次调用都鉴权,所以我们可以自己创建一个项目工程作为鉴权中心,用户拿到鉴权后用对应信息去访问对应API;

2.引用对应DLL

引用System.IdentityModel.Tokens.Jwt.dll

3.编写JWT创建Token的代码

鉴权代码单独写在一个类里,为了应用也封装成接口,服务继承接口,一些信息写在了配置类里:首先贴出代码,如下:

接口信息:

    public interface IJWTService
    {string GetToken(string UserName);
    }

实现信息:

public class JWTService : IJWTService
    {private readonly IConfiguration _configuration;public JWTService(IConfiguration configuration)
        {
            _configuration = configuration;
        }public string GetToken(string UserName)
        {
            Claim[] claims = new[]
            {               new Claim(ClaimTypes.Name, UserName),               new Claim("NickName","Richard"),               new Claim("Role","Administrator")//传递其他信息              };
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);/**
             *  Claims (Payload)
                Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段:

                iss: The issuer of the token,token 是给谁的
                sub: The subject of the token,token 主题
                exp: Expiration Time。 token 过期时间,Unix 时间戳格式
                iat: Issued At。 token 创建时间, Unix 时间戳格式
                jti: JWT ID。针对当前 token 的唯一标识
                除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
             * */var token = new JwtSecurityToken(
                issuer: _configuration["issuer"],
                audience: _configuration["audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(10),//10分钟有效期                signingCredentials: creds);string returnToken = new JwtSecurityTokenHandler().WriteToken(token);return returnToken;
        }
    }

 appsettings.json配置文件,红色部分是配置信息,如下:供上面代码获取配置信息

{  "Logging": {"LogLevel": {      "Default": "Information",      "Microsoft": "Warning",      "Microsoft.Hosting.Lifetime": "Information"}
  },  "AllowedHosts": "*",  "audience": "http://localhost:5000",
  "issuer": "http://localhost:5000",
  "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"}

4.在鉴权项目工程Startup.cs文件里依赖注入JWT的服务类

编写获取Token的接口编码,如下:

    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    { 
        #region 构造函数
        private ILogger<AuthenticationController> _logger = null;
        private IJWTService _iJWTService = null;
        private readonly IConfiguration _iConfiguration;
        public AuthenticationController(ILogger<AuthenticationController> logger,
            IConfiguration configuration
            , IJWTService service)
        {
            this._logger = logger;
            this._iConfiguration = configuration;
            this._iJWTService = service;
        }
        #endregion[Route("Login")]
        [HttpGet]
        public string Login(string name, string password)
        {
            ///这里应该是需要去连接数据库做数据校验,为了方便所有用户名和密码写死了
            if ("sxwcorejwt".Equals(name) && "123456".Equals(password))//应该数据库            {
                string token = this._iJWTService.GetToken(name);
                return JsonConvert.SerializeObject(new{
                    result = true,
                    token
                });
            }
            else{
                return JsonConvert.SerializeObject(new{
                    result = false,
                    token = ""});
            }
        }
    }

启动鉴权项目服务,调用Login方法就可以获取到鉴权的Token,如下图;

5.API工程引用对应DLL

 引用Microsoft.AspNetCore.Authentication.JwtBearer.dll

6.在API工程Startup.cs文件下添加配置代码,

代码配置几乎都是一样,有响应的备注,大家应该可以看懂,就不多说了,如下图:

 Startup.cs全部代码如下:

public class Startup
    {public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();#region JWT鉴权授权//services.AddAuthentication();//禁用  var ValidAudience = this.Configuration["audience"];var ValidIssuer = this.Configuration["issuer"];var SecurityKey = this.Configuration["SecurityKey"];
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)  //默认授权机制名称;                                       .AddJwtBearer(options => {
                         options.TokenValidationParameters = new TokenValidationParameters
                         {
                             ValidateIssuer = true,//是否验证Issuer ValidateAudience = true,//是否验证Audience ValidateLifetime = true,//是否验证失效时间 ValidateIssuerSigningKey = true,//是否验证SecurityKey ValidAudience = ValidAudience,//Audience ValidIssuer = ValidIssuer,//Issuer,这两项和前面签发jwt的设置一致  表示谁签发的Token IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey))//拿到SecurityKey                         };
                     });#endregion}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }#region 通过中间件来支持鉴权授权app.UseAuthentication();#endregionapp.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>{
                endpoints.MapControllers();
            });
        }
    }
View Code

 注意:appsettings.json配置文件,也要添加红色部分是配置信息,这里面的配置要和鉴权项目里的配置要一样如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"}
  },
  "AllowedHosts": "*",  "audience": "http://localhost:5000",
  "issuer": "http://localhost:5000",
  "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"}

7.在对应方法或者对应控制器上添加鉴权机制

如果是某一个方法需要鉴权只需要在对应方法上添加属性:[Authorize],如下图

如果是针对整个控制器上所有的方法都需要鉴权只需要在对控制器上添加属性:[Authorize],方法就不需要添加了,如下图

 

在控制器上添加属性:[Authorize],会使所有此控制器的方法需要鉴权,但是如果此控制器个别方法不需要鉴权,可以在对应方法上添加:[AllowAnonymous],如下图

8.测试鉴权

用postman测试如下:

没有鉴权,报错401,无鉴权,如下图:

用步骤4获取的Token有鉴权调用,如下图:

 至此NET CORE API权限控制之JWT的创建和引用已经完成,希望对你有帮助。 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多