.net core使用jwt token

上一篇转载的文章中解释了jwt的种种,.net core中使用jwt的方式

使用.net core内置方式实现jwt

使用JwtSecurityTokenHandler实现生成jwt

生成 token

这里我随便定义了一个secret叫mysecret12345678,认证的时候也要用到这个。

        public static string GetJwtAccessToken(ClaimsIdentity claimsIdentity)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("mysecret12345678");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claimsIdentity,
                Expires = DateTime.UtcNow.AddHours(10),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

注入认证

        /// <summary>
        /// 注册JWT Bearer认证服务的静态扩展方法
        /// </summary>
        /// <param name="services"></param>
        /// <param name="appSettings">JWT授权的配置项</param>
        public static void AddJwtBearerAuthentication(this IServiceCollection services)
        {
            //使用应用密钥得到一个加密密钥字节数组
            var key = Encoding.ASCII.GetBytes("mysecret12345678");
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddCookie(cfg => cfg.SlidingExpiration = true)
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = true;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
        }

services.AddJwtBearerAuthentication();

添加认证

注入认证及添加认证后,凡是添加Authorize特性的接口都如使用注入的策略进行认证。
app.UseAuthentication();

接口使用认证

添加两个接口,一个生成token,另一个加上Authorize特性使用认证。如果直接访问testtoken接口会报401,用GetToken接口生成的token去请求testtoken接口执行正常。说明token认证已经生效了。一个最简单的示例完成了。

        [HttpGet]
        public string GetToken()
        {
            var token = JwtBearerAuthenticationExtension.GetJwtAccessToken(new ClaimsIdentity(
                new Claim[]{
                    new Claim("userId","1"),
                    new Claim("userName","2"),
                    new Claim("userAccount","3")
                })
                );
            return token;
        }
        [HttpGet("testtoken")]
        [Authorize]
        public string TestToken()
        {
            return "1";
        }

内置方式生成jwt token的困惑

内置方式生成jwt很简单,从生成到认证,简单一些代码即可完成。但是,我想要刷新token呢,抱歉,要自己去实现。我想要在几个微服务中使用一套呢,抱歉,也比较麻烦。有没有其他方式简单解决呢,有!就是我们接下来讲的IdentityServer4。

使用IdentityServer4内置方式实现jwt

IdentityServer4 是为ASP.NET Core 2.系列量身打造的一款基于 OpenID Connect 和 OAuth 2.0 认证框架。具体的可以查看http://www.identityserver.com.cn/
后续我会写一系列IdentityServer4实战来实践统一认证和token刷新。

posted @ 2020-09-26 09:02  清晨时光  阅读(2073)  评论(0编辑  收藏  举报