Jwt創建身份驗證 Web API測試驗證

1、創建JWT

環境:.Net Framework 4.7.2

通過程序包管理控制檯添加包

install-package Microsoft.Owin.Security.Jwt

添加JWT方法

private string CreateToken()

{

            //發行日期

            DateTime issuedAt = DateTime.UtcNow;

            //設置過期時間

            DateTime expires = DateTime.UtcNow.AddMinutes(30);

            //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token

            var tokenHandler = new JwtSecurityTokenHandler();

            //創建一個標識,並向我們想要登錄的用戶添加聲明

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]

            {

                new Claim("Name", "Joanna"),

                new Claim("Role","Student"),

                new Claim("MobilePhone","159xxxxxxx9"),

                new Claim("Email","[email protected]"),

                new Claim("Sex","girl")

            });

            const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));

            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            //create the jwt

            var token =

                (JwtSecurityToken)

                    tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:50003", audience: "http://localhost:50001",

                        subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);

            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;

 }

2、運用JWT

環境:.Net Framework 4.7.2

通過程序包管理控制檯添加包

install-package Microsoft.Owin.Security.Jwt

install-package System.IdentityModel.Tokens.Jwt

install-package Thinktecture.IdentityModel.Core

創建TokenValidationHandler 類

    internal class TokenValidationHandler : DelegatingHandler

    {

        private static bool TryRetrieveToken(HttpRequestMessage request, out string token)

        {

            token = null;

            IEnumerable<string> authzHeaders;

            if (!request.Headers.TryGetValues("Authorization", out authzHeaders) || authzHeaders.Count() > 1)

            {

                return false;

            }

            var bearerToken = authzHeaders.ElementAt(0);

            token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;

            return true;

        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

        {

            HttpStatusCode statusCode;

            string token;

            //確定jwt是否存在

            if (!TryRetrieveToken(request, out token))

            {

                statusCode = HttpStatusCode.Unauthorized;

                //允許沒有token的請求——可以使用claimsauthorization屬性設置操作方法是否需要身份驗證

                return base.SendAsync(request, cancellationToken);

            }

            try

            {

                //祕密隨機密鑰 secret random key

                const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

                var now = DateTime.UtcNow;

                var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));

                SecurityToken securityToken;

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

                TokenValidationParameters validationParameters = new TokenValidationParameters()

                {

                    ValidAudience = "http://localhost:50003",

                    ValidIssuer = "http://localhost:50001",

                    ValidateLifetime = true,

                    ValidateIssuerSigningKey = true,

                    LifetimeValidator = this.LifetimeValidator,

                    IssuerSigningKey = securityKey

                };

                //提取並分配jwt的用戶

                Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken);

                HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken);

 

                return base.SendAsync(request, cancellationToken);

            }

            catch (SecurityTokenValidationException e)

            {

                statusCode = HttpStatusCode.Unauthorized;

                return base.SendAsync(request, cancellationToken);

            }

            catch (Exception ex)

            {

                statusCode = HttpStatusCode.InternalServerError;

            }

            return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode) { });

        }

 

        public bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters)

        {

            if (expires != null)

            {

                if (DateTime.UtcNow < expires) return true;

            }

            return false;

        }

在 WebApiConfig.cs 中添加

config.MessageHandlers.Add(new TokenValidationHandler());

最後在api控制器添加 [Authorize]

在調用 api/Values 方法時會自動檢測是否存在token 

參考文章鏈接:https://developerhandbook.com/entity-framework/create-restful-api-authentication-using-web-api-jwt/?tdsourcetag=s_pcqq_aiomsg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章