首页 > 其他分享 >339 Refresh Tokens 01(生成RefreshToken)

339 Refresh Tokens 01(生成RefreshToken)

时间:2024-07-01 21:57:45浏览次数:16  
标签:01 RefreshToken string Refresh secret user key using public

步骤

1、appsettings.json

"Jwt": {
  "Issuer": "http://localhost:7221",
  "Audience": "http://localhost:4200",
  "EXPIRATION_MINUTES": 1,
  "Key": "this is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwtthis is secret key for jwt"
},
"RefreshToken": {
  "EXPIRATION_MINUTES": 60
}

2、AuthenticationResponse.cs添加RefreshToken字段

using System;

namespace CitiesManager.Core.DTO
{
    public class AuthenticationResponse
    {
        public string? PersonName { get; set; } = string.Empty;
        public string? Email { get; set; } = string.Empty;
        public string? Token { get; set; } = string.Empty;
        public DateTime Expiration { get; set; }

        public string? RefreshToken { get; set; } = string.Empty;
        public DateTime RefreshTokenExpirationDateTime { get; set; }
    }
}

3、ApplicationUser.cs添加RefreshToken字段

using Microsoft.AspNetCore.Identity;
namespace CitiesManager.Core.Identity
{
    public class ApplicationUser : IdentityUser<Guid>
    {
        public string? PersonName { get; set; }
        public string? RefreshToken { get; set; }
        public DateTime RefreshTokenExpirationDateTime { get; set; }
    }
}

Add-Migration RefreshToken

4、JwtService中生成RefreshToken

using CitiesManager.Core.DTO;
using CitiesManager.Core.Identity;
using CitiesManager.Core.ServiceContracts;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
namespace CitiesManager.Core.Services
{
    public class JwtService : IJwtService
    {
        private readonly IConfiguration _configuration;
        public JwtService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        /// <summary>
        /// Generates a JWT token using the given user's information and the configuration settings.
        /// </summary>
        /// <param name="user">ApplicationUser object</param>
        /// <returns>AuthenticationResponse that includes token</returns>
        public AuthenticationResponse CreateJwtToken(ApplicationUser user)
        {
            // Create a DateTime object representing the token expiration time by adding the number of minutes specified in the configuration to the current UTC time.
            DateTime expiration = DateTime.UtcNow.AddHours(8).AddMinutes(Convert.ToDouble(_configuration["Jwt:EXPIRATION_MINUTES"]));
            // Create an array of Claim objects representing the user's claims, such as their ID, name, email, etc.
            Claim[] claims = new Claim[] {
                 new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), //Subject (user id)
                 new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //JWT unique ID
                 new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()), //Issued at (date and time of token generation)
                 new Claim(ClaimTypes.NameIdentifier, user.Email), //Unique name identifier of the user (Email)
                 new Claim(ClaimTypes.Name, user.PersonName) //Name of the user
                 };
            // Create a SymmetricSecurityKey object using the key specified in the configuration.
            SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            // Create a SigningCredentials object with the security key and the HMACSHA256 algorithm.
            SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            // Create a JwtSecurityToken object with the given issuer, audience, claims, expiration, and signing credentials.
            JwtSecurityToken tokenGenerator = new JwtSecurityToken(
            _configuration["Jwt:Issuer"],
            _configuration["Jwt:Audience"],
            claims,
            expires: expiration,
            signingCredentials: signingCredentials
            );
            // Create a JwtSecurityTokenHandler object and use it to write the token as a string.
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            string token = tokenHandler.WriteToken(tokenGenerator);
            // Create and return an AuthenticationResponse object containing the token, user email, user name, and token expiration time.
            return new AuthenticationResponse()
            {
                Token = token,
                Email = user.Email,
                PersonName = user.PersonName,
                Expiration = expiration,
                RefreshToken = GenerateRefreshToken(),
                RefreshTokenExpirationDateTime = DateTime.UtcNow.AddHours(8).AddMinutes(Convert.ToInt32(_configuration["RefreshToken:EXPIRATION_MINUTES"]))
            };
        }
        //Creates a refresh token (base 64 string of random numbers)
        private string GenerateRefreshToken()
        {
            byte[] bytes = new byte[64];
            var randomNumberGenerator = RandomNumberGenerator.Create();
            randomNumberGenerator.GetBytes(bytes); 
            return Convert.ToBase64String(bytes);
        }
    }
}

5、AccountController.cs

register和login中如下代码更新

if (result.Succeeded)
{
    //sign-in
    await _signInManager.SignInAsync(user, isPersistent: false);
    var authenticationResponse = _jwtService.CreateJwtToken(user);
    user.RefreshToken = authenticationResponse.RefreshToken;
    user.RefreshTokenExpirationDateTime = authenticationResponse.RefreshTokenExpirationDateTime;
               
    await _userManager.UpdateAsync(user);
    return Ok(authenticationResponse);
}

6、register.component.ts/login.component.ts

添加如下代码

localStorage["refreshToken"] = response.refreshToken;

结果

登录以后成功生成refreshToken

Gitee获取源码:

https://gitee.com/huang_jianhua0101/asp.-net-core-8.git

标签:01,RefreshToken,string,Refresh,secret,user,key,using,public
From: https://blog.csdn.net/KevinHuang2088/article/details/140111053

相关文章

  • CF950Div3 G. Yasya and the Mysterious Tree(01Trie)
    Problem题目地址Solution设\(s[u]\)是根到\(u\)路径上的异或和,树上任意两点\(u,v\)的路径异或和可表示为\(s[u]\opluss[v]\)。考虑查询操作?vx即求\(\max\{s[v]\opluss[u]\oplusx|\\1\leu\len,u\not=v\}\),若把\(s[v]\oplusx\)看作一个整体......
  • 20240701总结(网络流)
    A-FlowProblemHDU3549FlowProblem题解:网络流版题,甚至今天早上我还只会EK(辛亏卡EK的没那么多,但是还是被迫学习dinic)B-WarHDU-3599War题意:求1到n最短路径(无向边)的最大条数(一条边不能重复经过)题解:题面就让人难懂,好像出题人在考生活实际和理解能力。看懂题就简单了,先跑......
  • Windows Server 2016 搭建VPN服务
    ......
  • WEB01MySQL安装和数据库
    第一天、WEB课程web课程主要讲三部分内容数据库数据库介绍什么是数据库数据存储的仓库,其本质也是一个文件系统数据库会按照特定的格式对数据进行存储,用户可以对数据库中的数据进行增加,修改,删除及查询操作。数据库管理系统层次数据库管理系统(DataBaseManage......
  • 打卡信奥刷题(208)用Scratch图形化工具信奥P8605 [普及组][蓝桥杯 2013 国 AC] 网络寻路
    [蓝桥杯2013国AC]网络寻路题目描述XXX国的一个网络使用若干条线路连接若干个节点。节点间的通信是双向的。某重要数据包,为了安全起见,必须恰好被转发两次到达目的地......
  • [刷题笔记] Luogu P1612 [yLOI2018] 树上的链
    ProblemDescriptionDescription给定一棵有\(n\)个节点的树。每个节点有一个点权和一个参数。节点\(i\)的权值为\(w_i\),参数为\(c_i\)。\(1\)是这棵树的根。现在,对每个节点\(u\)(\(1\lequ\leqn\)),请在树上你找到最长的一条链\(v_1,v_2,\dotsv_m\),满足如下条件:......
  • k8s-01-介绍
    K8S介绍单体应用:由很多个组件组成,这些组件紧密的耦合在一起,由于他们在同一个操作系统进程中运行,所以在开发、部署、管理都必须在同一个实体进行。即使市某个组件中小的更改,都需要重新部署整个应用。组件间缺乏严格的边界定义,相互依赖,日积月累导致系统复杂度提升。微服务:将......
  • 01.Redis常用的一些命令
    简介:Redis是一款开源的使用ANSIC语言编写、遵守BSD协议、支持网络、可基于内存也可持久化的日志型、Key-Value高性能数据库。Redis与其他Key-Value缓存产品相比有以下三个特点:支持数据持久化,可以将内存中的数据保存在磁盘中,重启可再次加载使用支持简单的Key-Value类型的......
  • LeetCode 1013. Partition Array Into Three Parts With Equal Sum
    原题链接在这里:https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/description/题目:Givenanarrayofintegers arr,return true ifwecanpartitionthearrayintothree non-empty partswithequalsums.Formally,wecanpartition......
  • 【在线评论】不同视角下在线评论对客户满意度和推荐度的影响—推文分析—2024-07-01
    今天的推文主题是【在线评论】,重点关注可以关注第四篇,很全面地分析了在线评论的信息多维性。第一篇从客户的在线评论入手,将客户消费的动机为功利、享受、社会满足;第二篇是关于在线评论对消费者再次选择同一家酒店的机制探索。变量:信息质量、信息来源可信度、信息有用性与......