NETCORE - JWT认证与授权

NETCORE - JWT认证与授权

 1. 安装NuGet包:JwtBearer

 

 

 

 

 2. 配置 签名参数

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "TokenParameter": {
    "Issuer": "颁发者", //颁发者
    "Audience": "接收者", //接收者
    "Secret": "123456732409ldjfsd8", //签名秘钥
    "AccessExpiration": 30 //AccessToken过期时间(分钟)"
  },
  "AllowedHosts": "*"
}

 

 

新建配置类

    public class TokenParameter
    {
        public string Issuer { get; set; }//颁发者
        public string Audience { get; set; }//接收者
        public string Secret { get; set; }//签名秘钥
        public int AccessExpiration { get; set; }//AccessToken过期时间(分钟)
    }

 

 

在Startup中 注入config配置

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //注入config配置
            services.Configure<TokenParameter>(Configuration.GetSection("TokenParameter"));
        }

 

 

3. 定义一个获取token的控制器

    [Route("api/[controller]")]
    [ApiController]
    public class OAuthController : ControllerBase
    {
        private TokenParameter Config_TokenParameter;

        public OAuthController(IOptions<TokenParameter> option)
        {
            Config_TokenParameter = option.Value;
        }


        [HttpGet]
        [Route("token")]
        public ActionResult GetAccessToken(string username, string password)
        {
            if (username != "admin" || password != "admin")
            {
                return BadRequest("Invalid Request");
            }

            var claims = new[]
            {
                new Claim (ClaimTypes.Name,username),
                new Claim(ClaimTypes.Role,"")
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Config_TokenParameter.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(Config_TokenParameter.Issuer, Config_TokenParameter.Audience, claims, expires: DateTime.UtcNow.AddMinutes(Config_TokenParameter.AccessExpiration), signingCredentials: credentials);
            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return Ok(token);
        }
    }

 

 

4. 添加token身份认证到容器(startup)

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //注入config配置
            services.Configure<TokenParameter>(Configuration.GetSection("TokenParameter"));

            //获取ServiceProvider
            var serviceProvider = services.BuildServiceProvider();
            //取出放入静态变量
            var Config_TokenParameter = serviceProvider.GetService<IOptions<TokenParameter>>();

            //添加token身份认证到容器
            services.AddAuthentication(x =>
            {

                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
                {
                    x.RequireHttpsMetadata = false;
                    x.SaveToken = true;
                    x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        ValidateIssuerSigningKey = true,//是否调用对签名securityToken的SecurityKey进行验证
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Config_TokenParameter.Value.Secret)),//签名秘钥
                        ValidateIssuer = true,//是否验证颁发者
                        ValidIssuer = Config_TokenParameter.Value.Issuer,//颁发者
                        ValidateAudience = true,//是否验证接收者
                        ValidAudience = Config_TokenParameter.Value.Audience,//接收者
                        ValidateLifetime = true,//是否验证失效时间
                    };
                });
        }

 

 

添加身份认证到中间件

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();//必须在app.UseAuthorization();之前

            app.UseAuthorization();

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

 

 

 

添加测试控制器

需要授权的方法 需加上 [Authorize],给方法或者控制器标记均可

如标记[AllowAnonymous],则此方法不需要身份验证(比如登录接口)

    [Route("api/[controller]")]
    [ApiController]
    public class textController : ControllerBase
    {
        [HttpGet]
        [Route("GetTodo")]
        [Authorize]
        public ActionResult GetTodo()
        {
            return Ok("request ok !");
        }
    }

 

 

postman测试

1. 直接调用GetTodo,失败,返回401 

 https://localhost:5001/api/text/GetTodo 

 

 

 

 

 

 

 

2. 获取token,直接访问 

https://localhost:5001/api/oauth/token?username=admin&password=admin

 

 

 

3.添加 token 再访问 GetTodo,访问成功。

 https://localhost:5001/api/text/GetTodo 

 

 

 

 

 

项目:NETCORE.JWT
附代码:https://gitee.com/wuxincaicai/NETCORE.git

引用:https://segmentfault.com/a/1190000037433091

 

posted @ 2020-11-04 14:29  无心々菜  阅读(389)  评论(0编辑  收藏  举报