设为首页 加入收藏

TOP

我的第一个netcore2.2 api项目搭建(三)续(一)
2019-09-17 18:23:50 】 浏览:53
Tags:一个 netcore2.2 api 项目 搭建

上一章快速陈述了自定义验证功能添加的过程,我的第一个netcore2.2 api项目搭建(三)

但是并没有真正的去实现,这一章将要实现验证功能的添加。

这一章实现目标三:jwt认证授权添加

在netcore2.2中,只要添加很简单的配置就能添加jwt功能了。至于jwt本身是啥大家自行去了解,这里不做多说了。。

1.1添加JwtHelper类

public class JwtHelper
    {
        public const string Audience = "JH.OPEMR.API";
        public const string Issuer = "all";
        public const string SigningKey = "my first security key";

        public static string CreateJwtToken(string uid, string uName, string sub)
        {
            var dateTime = DateTime.UtcNow;
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SigningKey));

            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
               {
                    new Claim(JwtClaimTypes.Audience,Audience),
                    new Claim(JwtClaimTypes.Issuer,Issuer),
                    new Claim(JwtClaimTypes.Id, uid),
                    new Claim(JwtClaimTypes.Name, uName),
                    new Claim("Role", sub)//高亮,很重要
               }),
                Expires = dateTime.AddHours(0.5),
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            return tokenString;
        }
    }

这个类就一个方法,提供生成加密的jwt串

1.2在Startup做配置:

//注册默认认证方式,这里使用jwt方式
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
               {
                   o.TokenValidationParameters = new TokenValidationParameters
                   {
                       RoleClaimType = JwtClaimTypes.Role,//这个很重要

                       ValidIssuer = JwtHelper.Issuer,
                       ValidAudience = JwtHelper.Audience,
                       IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtHelper.SigningKey))

                       /***********************************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
                   };
               });

可以看出,JwtHelper里的几个变量在Startup中也使用了,这样就保证了配置的参数和生成jwt串的参数保持了一致,这样就能起到防伪作用了,不是千千万万个jwt串在咱系统都能通过,如果都通过了,那不是搞笑么。。。

1.3启用验证

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
        //启用验证
            app.UseAuthentication(); //启用验证中间件
            //app.UseMiddleware<MyAutoMiddleware>();

            //启用Swagger
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

            });

            app.UseMvc();
        }

在前一章中,咱们并没有调用app.UseAuthentication(),是因为上一章咱们自己启用了中间件,并没有启用2.2注入的验证方式。而这一章,咱们注入了jwt,就得调用这句话是执行验证授权了。一旦启用,jwt就会自行进行请求的验证功能,不需要咱们在写代码了。。。

ok,F5运行

可以看到,未验证,调用失败。。

咱们先用postman调用login模拟登录,生成一个jwt串,代码很简单:

/// <summary>
    /// Account 模块
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiCon
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇新增筛选方案 下一篇.NET Core 常用第三方包

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目