当前位置:网站首页>Netcore3.1 JSON web token Middleware

Netcore3.1 JSON web token Middleware

2022-07-04 23:51:00 Genius Wolong

Ten years of Hedong , Ten years in Hexi , Don't deceive young people into being poor

knowledge has no limit , Keep improving

1、 Introduced in the project jwt

2、 establish token The example code of is as follows :

2.1、 Required entity classes

    /// <summary>
    /// POCO class , Used to store, issue, or verify jwt Information used when 
    /// </summary>
    public class TokenOptions
    {
        public static string Secret = "chenwolong_love_woman_2022";// Private key   At least 16 Characters 

        public static string Issuer = "webapi.cn";

        public static string Audience = "WebApi";

        public static int AccessExpiration = 180;// Expiration time 
         
    }

2.2、 establish Token

        public dynamic UserLogin(string uname, string upwd)
        {
            var userinfo = new { uname = " Chen Wolong ", sex = " male ", age = 30, userrole = new List<string>() { "admin", "staff" }, city = " Suzhou ", love = " beauty " };
            var expiresTime = DateTime.Now.AddMinutes(TokenOptions.AccessExpiration); 
            var claims = new[]
           {
                    new Claim(ClaimTypes.Name,uname),
                    new Claim(ClaimTypes.Role,ClaimTypes.Role ), // 
                    new Claim(ClaimTypes.Actor,"wuan"),
                    new Claim(ClaimTypes.Country,"China"),
                    new Claim(ClaimTypes.Expired,"China"),
                    new Claim(ClaimTypes.UserData,JsonConvert.SerializeObject(userinfo))
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TokenOptions.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(TokenOptions.Issuer, TokenOptions.Audience, claims, expires: expiresTime, signingCredentials: credentials);
            
             var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            // add  "Bearer "  It's for compatibility swagger 
            return new { token = "Bearer "+ token, expiresTime = expiresTime.ToString("yyyy-MM-dd HH:mm:ss") };

        }

3、jwt middleware

3.1、 Required entities

    public class CurrentUser
    {
        public string uname { get; set; }
        public string sex { get; set; }
        public int age { get; set; }
        public List<string> userrole { get; set; } = new List<string>();
        public string city { get; set; }
        public string love { get; set; }
    }

Take a closer look at this entity class , And we create token The anonymous variables defined in are consistent

 

 3.2、 Preparation of Middleware

using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wuanModel;

namespace wuanIotApi.Middlewares
{

    public class JwtMiddlewares
    {
        private readonly RequestDelegate _next;

        public JwtMiddlewares(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Request.Headers.TryGetValue("Authorization", out var apiKeyHeaderValues);
            if (apiKeyHeaderValues.Count > 0)
            {
                // This is for compatibility swagger
                var token = apiKeyHeaderValues.FirstOrDefault().Replace("Bearer ","");
                 
                AttachUserToContext(context, token);
            }

             await _next.Invoke(context);
        }

        private void AttachUserToContext(HttpContext context, string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.UTF8.GetBytes(TokenOptions.Secret); // Get used to generate token The encryption key
               
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true, // Whether the validation Key SecurityKey
                    IssuerSigningKey = new SymmetricSecurityKey(key), // Get SecurityKey
                    ValidateIssuer = false, // Whether the validation Issuer
                    ValidateAudience = false, // Whether the validation Audience
                    ValidateLifetime = true, // Whether the validation Token The expiration time of 
                }, out SecurityToken validatedToken); 

                var jwtToken = (JwtSecurityToken)validatedToken;
                // I learned that ,ValidTo The time zone is different from Beijing time 8 Hours , Through this time , Judge Token Is it overdue 
                var ValidTo = jwtToken.ValidTo.AddHours(8);
                if (ValidTo < DateTime.Now)
                { 
                    return; 
                }
                var userdata  = jwtToken.Claims.Where(A => A.Type.Contains("userdata")).ToList().FirstOrDefault().Value; 
                // Write authentication information , Convenient for business use 
                var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim("userdata", userdata) });
                Thread.CurrentPrincipal = new ClaimsPrincipal(claimsIdentity);

                // take Token The user information parsed in is stored in the current request 
                context.Items["userdata"] = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentUser>(userdata);
            }
            catch (Exception ex)
            {
                context.Items["userdata"] = null;
            }
        }
    }
}


context.Items["userdata"] Use

4、 Create the base controller

4.1, Basic controller

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using wuanCommon;
using wuanModel;

namespace wuanIotApi.Controllers
{
    [Authorize]
    [Route("api/V1/[controller]")]
    [ApiExplorerSettings(GroupName = "V1")]
    public class BaseController : Controller
    {
        public CurrentUser user = new CurrentUser();
        public BaseController() { }
        /// <summary>
        ///  The first 2 Step to execute the base class constructor 
        ///  The first 3 Step   Execute asynchronous methods of the parent class    Asynchronous methods    Seems to be able to communicate with OnActionExecuting At the same time 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            return base.OnActionExecutionAsync(context, next);
        }

        /// <summary>
        ///  The first 4 Step   perform OnActionExecuting Method 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!Request.Headers.TryGetValue("Authorization", out var apiKeyHeaderValues))
            {
                user =null;
            }
            else
            {
                user = (CurrentUser)this.HttpContext.Items["userdata"];
            }
        }

        /// <summary>
        ///  Step 5: execute the base class Action
        ///  The first 6 Step  Aciton After execution   perform  OnActionExecuted
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
        }

        
    }
}

4.2 , Others inherited from the base controller webapi controller

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using wuanInterface;

namespace wuanIotApi.Controllers
{
    public class UserController : BaseController
    {
        private readonly IUserService service;
        public UserController(IUserService _service)
        {
            this.service = _service;
        }
        /// <summary>
        ///  The user login 
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("UserLogin")]
        public IActionResult UserLogin()
        { 
            var result = service.UserLogin("", "");
            return Ok(result);
        }

        [HttpPost]
        [Route("TokenTest")]
        public IActionResult TokenTest()
        { 
            return Ok(user);
        }
    }
}

Dangdai Token When asked , among TokenTest The basic information of the current requester will be printed , That is to say : Chen Wolong   In Suzhou Like beautiful women   these

@ Genius Wolong's blog

原网站

版权声明
本文为[Genius Wolong]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041845133754.html