.Net Core使用JWT

.Net Core使用JWT

1.新建WebApi项目JwtDemo

.Net Core使用JWT_第1张图片

2.通过nuget安装JWT.Net 根据你的版本自行选择合适的版本

.Net Core使用JWT_第2张图片

3.分别建立三个实体类LoginDto,PlayloadDto,TokenDto

    public class LoginDto {
        public string UserId { get; set; }
        public string Password { get; set; }
    }
    public class PlayloadDto {
        public string UserId { get; set; }
        public List Roles { get; set; }
        public DateTime? ExpiryDateTime { get; set; }
    }
    public class TokenDto {
        public bool Success { get; set; }
        public string Token { get; set; }
        public string Message { get; set; }
    }

4.新建TokenController用于验证用户信息获取Token信息

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JwtDemo.Dto;
using Microsoft.AspNetCore.Mvc;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System.Text;

namespace JwtDemo.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TokenController : Controller {
        private const string secretKey = "sfdkjskdlfnnierljewlkjsffd";

        [HttpPost]
        public TokenDto GetToken(LoginDto loginDto) {
            TokenDto tokenInfo = new TokenDto();
            if (loginDto.UserId=="1646" && loginDto.Password == "123456") {
                
                PlayloadDto playloadDto = new PlayloadDto() { UserId = loginDto.UserId, Roles = new List {"1001"}, ExpiryDateTime = DateTime.Now.AddMinutes(30) };
                try {
                    byte[] key = Encoding.UTF8.GetBytes(secretKey);
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
                    IJsonSerializer serializer = new JsonNetSerializer();//序列化
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
                    IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
                    var token = encoder.Encode(playloadDto, key);//生成令牌

                    
                    tokenInfo.Success = true;
                    tokenInfo.Token = token;
                    tokenInfo.Message = "ok";
                }
                catch(Exception e) {
                    tokenInfo.Success = false;
                    tokenInfo.Message = e.InnerException.ToString();
                }
            }
            return tokenInfo;
        }


    }
}

得到相应的token信息 

.Net Core使用JWT_第3张图片 

5.新建过滤器ApiAuthorityAttribute 用于验证token信息的正确性

using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JWT;
using JWT.Serializers;
using JwtDemo.Dto;
using JwtDemo.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using JWT.Algorithms;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace JwtDemo.Filter {
    public class ApiAuthorityAttribute : Attribute, IAuthorizationFilter {
        private const string secretKey = "sfdkjskdlfnnierljewlkjsffd";
        public void OnAuthorization(AuthorizationFilterContext context) {
            var controller = context.RouteData.Values["controller"].ToString();
            var action = context.RouteData.Values["action"].ToString();

            var httpcontext = ServiceGetter.ServiceProvider.GetRequiredService().HttpContext;
            //取得header中的auth的token信息
            var authHeader = from t in httpcontext.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();
            if (authHeader != null) {
                try {
                    string token = authHeader.FirstOrDefault();
                    byte[] key = Encoding.UTF8.GetBytes(secretKey);
                    IJsonSerializer serializer = new JsonNetSerializer();//序列化
                    IDateTimeProvider provider = new UtcDateTimeProvider();
                    IJwtValidator validator = new JwtValidator(serializer, provider);
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
                    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                    //解密
                    var json = decoder.DecodeToObject(token, key, verify: true);
                    if(json != null) {
                        if (json.ExpiryDateTime < DateTime.Now) {
                            httpcontext.Response.WriteAsync("0你的Token验证不通过");
                            context.Result = new EmptyResult();//加入此句代码就不会继续执行action 
                            return;
                        }
                    }
                }
                catch(Exception e) {
                    context.Result = new EmptyResult();//加入此句代码就不会继续执行action 
                    return;
                }
            }
        }
    }
}

6.将此过滤器应用到api接口上,将获取到的token信息放到header中键值为auth项中,然后发送请求,就可以通过此过滤器验证了

.Net Core使用JWT_第4张图片

你可能感兴趣的:(WebApi,.Net,Core,JWT)