首页 > 其他分享 >.NetCore 3.1 JWT AccessToken And RefreshToken

.NetCore 3.1 JWT AccessToken And RefreshToken

时间:2023-03-06 17:59:50浏览次数:76  
标签:RefreshToken AppSettings JWT response 3.1 var new public

Controller

    [HttpGet]
    public Response<JwtDto> Login(string account, string password)
    {
        var response = new Response<JwtDto>();

        var user = students.SingleOrDefault(t => t.Account == account);

        if (user != null)
        {
            if (user.Password.Equals(password))
            {
                response.Msg = "登录成功";

                var token = new JwtDto()
                {
                    AccessToken = Jwt.CreateToken(user, TokenType.AccessToken),
                    RefreshToken = Jwt.CreateToken(user, TokenType.RefreshToken)
                };

                response.Data = token;
            }
            else
            {
                response.Status = 400;
                response.Msg = "用户密码不正确!";
            }
        }
        else
        {
            response.Status = 400;
            response.Msg = "用户名不存在!";
        }

        return response;
    }

    [HttpGet]
    public Response<string> RefreshToken(string refreshToken)
    {
        Student student;
        var response = new Response<string>();

        if (Jwt.ValidateRefreshToken(refreshToken.ToStringX().Replace("Bearer ", ""), out student))
        {
            response.Data = Jwt.CreateToken(student, TokenType.AccessToken);
        }
        else
        {
            response.Status = 401;
            response.Msg = "Unauthorized";
        }

        return response;
    }

JWT

   public class Jwt
    {
        public static string CreateToken(Student student, TokenType type)
        {
            var audience = type == TokenType.AccessToken ? AppSettings.JWT.AccessTokenAudience : AppSettings.JWT.RefreshTokenAudience;

            var expires = type == TokenType.AccessToken ? AppSettings.JWT.AccessTokenExpires : AppSettings.JWT.RefreshTokenExpires;

            var claims = new Claim[] {
                    new Claim(ClaimTypes.Name, student.Account),
                    new Claim(JwtRegisteredClaimNames.Iss,AppSettings.JWT.Issuer),
                    new Claim(JwtRegisteredClaimNames.Aud,audience),
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                    new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(expires)).ToUnixTimeSeconds()}")
                };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JWT.SecurityKey));
            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var securityToken = new JwtSecurityToken(
                    issuer: AppSettings.JWT.Issuer,
                    audience: audience,
                    claims: claims,
                    expires: DateTime.Now.AddSeconds(expires),
                    signingCredentials: signingCredentials);

            return "Bearer " + new JwtSecurityTokenHandler().WriteToken(securityToken);
        }

        public static bool ValidateRefreshToken(string refreshToken, out Student student)
        {
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = AppSettings.JWT.Issuer,
                ValidateAudience = true,
                ValidAudience = AppSettings.JWT.RefreshTokenAudience,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.FromSeconds(0),
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JWT.SecurityKey))
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            SecurityToken securityToken;

            try
            {
                tokenHandler.ValidateToken(refreshToken, tokenValidationParameters, out securityToken);
                student = SerializeToken(securityToken);

                return true;
            }
            catch (Exception)
            {
                student = null;
                return false;
            }
        }

        public static Student SerializeToken(SecurityToken securityToken)
        {
            Student student = new Student();

            object account;

            (securityToken as JwtSecurityToken).Payload.TryGetValue(ClaimTypes.Name, out account);

            student.Account = account.ToString();

            return student;
        }
    }

    public enum TokenType
    {
        AccessToken,
        RefreshToken
    }

    public class JwtDto
    {
        public string AccessToken { get; set; }
        public string RefreshToken { get; set; }
    }

AppSettings

   public class AppSettings
   {
        private static readonly IConfigurationRoot configuration;

        static AppSettings()
        {
            configuration = new ConfigurationBuilder()
                               .SetBasePath(Directory.GetCurrentDirectory())
                               .AddJsonFile("appsettings.json", false, true)
                               .Build();
        }

        public static class JWT
        {
            public static string Issuer => configuration["JWT:Issuer"];
            public static string AccessTokenAudience => configuration["JWT:AccessTokenAudience"];
            public static int AccessTokenExpires => Convert.ToInt32(configuration["JWT:AccessTokenExpires"]);
            public static string RefreshTokenAudience => configuration["JWT:RefreshTokenAudience"];
            public static int RefreshTokenExpires => Convert.ToInt32(configuration["JWT:RefreshTokenExpires"]);
            public static string SecurityKey => configuration["JWT:SecurityKey"];
        }
    }

appsettings.json

   "JWT": {
    "Issuer": ".Net Core Api",
    "AccessTokenAudience": "AccessToken Client",
    "AccessTokenExpires": 1200,
    "RefreshTokenAudience": "RefreshToken Client",
    "RefreshTokenExpires": 86400,
    "SecurityKey": "5bGx5LicLea1juWugS3msbbkuIrljr8t5ZCR5L+u6aOe"
  }

ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "Core",
            });

            var security = new OpenApiSecurityScheme
            {
                Description = "JWT授权,请输入 Bearer {Token} 进行身份验证",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            };
            options.AddSecurityDefinition("oauth2", security);
            options.AddSecurityRequirement(new OpenApiSecurityRequirement { { security, new List<string>() } });
            options.OperationFilter<AddResponseHeadersFilter>();
            options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
            options.OperationFilter<SecurityRequirementsOperationFilter>();
        });

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true,
                            ValidIssuer = AppSettings.JWT.Issuer,
                            ValidateAudience = true,
                            ValidAudience = AppSettings.JWT.AccessTokenAudience,
                            ValidateLifetime = true,
                            ClockSkew = TimeSpan.FromSeconds(0),
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JWT.SecurityKey))
                        };

                        options.Events = new JwtBearerEvents
                        {
                            OnChallenge = async context =>
                            {
                                context.HandleResponse();
                                context.Response.ContentType = "application/json;charset=utf-8";
                                context.Response.StatusCode = StatusCodes.Status200OK;

                                var result = new Response<string>()
                                {
                                    Status = 401,
                                    Msg = "Unauthorized"
                                };

                                await context.Response.WriteAsync(result.ToJson());
                            }
                        };
                    });
    }

Configure

    app.UseAuthentication();

相关资料

  1. demo

转 https://www.cnblogs.com/xiangxiufei/p/13341712.html

标签:RefreshToken,AppSettings,JWT,response,3.1,var,new,public
From: https://www.cnblogs.com/wl-blog/p/17184781.html

相关文章

  • 学习ASP.NET Core Blazor编程系列二十七——JWT登录(2)
    学习ASP.NETCoreBlazor编程系列文章之目录学习ASP.NETCoreBlazor编程系列一——综述学习ASP.NETCoreBlazor编程系列二——第一个Blazor应用程序(上)学习A......
  • Spring Security + JWT + Swagger2 登录验证一套流程小结
    SpringSecurity+JWT+Swagger2登录验证一套流程主要是三个框架的集成配置,以及各个独立的配置(主要是JWT+Security的登录验证)。流程:构建SpringBoot基本项目,......
  • Step-by-step guide on how to use JWT
    JWT(JSONWebToken)isastandardforsecurelytransmittinginformationbetweenpartiesasaJSONobject.Here'sastep-by-stepguideonhowtouseJWT:......
  • 算法基础1.3.1高精度加法
    前言该文章探讨的高精度代指C++中极大整数的计算,不是浮点数(y总说那个少见,不讲)。这个问题只在C++中存在,Java有大整数类来解决,python本身特性就已经解决了。高精度整数分......
  • docker-compose up -d 运行报错: ERROR: https://dl-cdn.alpinelinux.org/alpine/v3.1
    docker部署python时执行到RUNapkupdate....命令出现错误:ERROR:https://dl-cdn.alpinelinux.org/alpine/v3.17/community:BADsignature一般是软件包源地址请求......
  • python 安装最新版3.11.2 for centos
    目录Python安装前的准备参考官方文档openssl下载地址openssl安装python的安装遇到的一些坑Python安装前的准备sudoyumupdate&&sudoyuminstall-yopenssl-deve......
  • php jwt
    <?phpnamespaceapp\api\library;/***PHP实现jwt*/classJwt{//头部privatestatic$header=array('alg'=>'HS256',//生成signature的算法......
  • No.3.1
    JavaScript是什么?JavaScript是一种运行在客户端(浏览器)的编程语言,实现人机交互效果。作用:网页特效(监听用户的一些行为让网页作出对应的反馈)  表单验证(针对表单数......
  • NetCore JWT token
    在netcore中jwt使用场景很多,网上有很多的资料,这里不再累述,之后有机会会单独介绍,今天主要以实战为主。1、createjwttoken1publicinterfaceIJwtTokenService2......
  • .net core 3.1 上传大文件报错413 Payload Too Large
    IIS配置如下https://www.cnblogs.com/hallejuayahaha/p/12884347.html  代码里面新增services.Configure<FormOptions>(options=>{options.Mul......