JWT

JSON WEB Token(JWT),是一种基于JSON的、用于在网络上声明某种主张的令牌(token)。JWT通常由三部分组成:头信息(header),消息体(payload)和签名(signature)。

.Net Core 中使用 JWT:

一、appsettings.json中增加相应配置

{
"JwtSettings": {

    "Issuer": "https://localhost:44329",
    "Audience": "https://localhost:44329",
    "SecretKey": "1234567891qwerfdsawe"
  }}

二、创建一个对应的类:

    public class JwtSettings
    {
        public string Issuer { get; set; }
        public string Audience { get; set; }
        public string SecretKey { get; set; }
    }

三、Startup类中配置

    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        //1.ConfigureServices中添加服务
        public void ConfigureServices(IServiceCollection services)
        {
             services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
            var jwt = new JwtSettings();
            Configuration.Bind("JwtSettings", jwt);//读取配置文件到C#实例
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                //options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

            })  //默认授权机制名称   
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = JwtClaimTypes.Name,
                        RoleClaimType = JwtClaimTypes.Role,
                        ValidateIssuer = true,//是否在令牌期间验证签发者
                        ValidateAudience = true,//是否验证接收者
                        ValidateLifetime = true,//是否验证失效时间
                        ValidateIssuerSigningKey = true,//是否验证签名
                        ValidAudience = jwt.Audience,//接收者
                        ValidIssuer = jwt.Issuer,//签发者,签发的Token的人
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SecretKey))//拿到SHA256加密后的key
                    };
                });
        }
        //2、Configure 中添加中间件
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseRouting();

            app.UseAuthentication();//JWT中间件

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

四、添加一个JWT认证的控制器AuthorizeController

using System;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Options;
using System.Text;
using System.IdentityModel.Tokens.Jwt;

namespace WebApiTest.Controllers
{
    [Route("api/jwt")]
    public class AuthorizeController : Controller
    {
        private JwtSettings _jwtSettings;

        public AuthorizeController(IOptions<JwtSettings> _jwtSettingsAccesser)
        {
            _jwtSettings = _jwtSettingsAccesser.Value;
        }

        [HttpGet]
        [Route("gettoken")]
        public IActionResult Token(string username,string pwd)
        {
            if (ModelState.IsValid)//判断是否合法
            {
                //登录验证,这里只是做了简单演示,具体还是要按自己的业务逻辑来判断
                if (username != "Lucy" && pwd != "123456")//判断账号密码是否正确
                {
                    return BadRequest();
                }

                //验证通过后,生成token
                var claim = new Claim[]{
                    new Claim(ClaimTypes.Name,"Lucy"),
                    new Claim(ClaimTypes.Role,"admin")
                };

                //对称秘钥
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
                //签名证书(秘钥,加密算法)
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                //生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包,并引用System.IdentityModel.Tokens.Jwt命名空间
                var token = new JwtSecurityToken(_jwtSettings.Issuer, _jwtSettings.Audience, claim, DateTime.Now, DateTime.Now.AddMinutes(30), creds);

                return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });

            }

            return BadRequest();
        }
    }
}

postman 测试得到token

五、控制器中使用jwt

在Controller /action 上打上特性 [Authorize]就可以了,不需要检查授权认证的话打上特性: [AllowAnonymous]

    [Route("api/user")]
    [ApiController]
    [Authorize]//添加认证
    public class UserController : Controller
    {
        [Route("Details")]
        [HttpPost]
        [AllowAnonymous]//不需要认证
        public ActionResult<string> Details()
        {
        }
    }
posted @ 2021-01-26 17:20  清和时光  阅读(107)  评论(0编辑  收藏  举报