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 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.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());

Jwt创建身份验证 Web API测试验证_第1张图片

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

Jwt创建身份验证 Web API测试验证_第2张图片

在调用 api/Values 方法时会自动检测是否存在token 

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

你可能感兴趣的:(.NET)