ASP.NET Core MVC 项目 创建JWT搭配WebApi和MinimalApi实现输出Token

目录

一:新建WebApi项目

二:添加关键类

三:修改appsettings.json文件

四:修改Program.cs文件

五:添加控制器AuthenticationController

六:结果截图


一:新建WebApi项目【推荐搭配WebApi和MinimalApi使用】

  1. 右键当前解决方案、添加、新建项目。
  2. 点击ASP.NET Core Web API下一步。
  3. 输入项目名称,后缀追加.WebApi。
  4. 勾选使用控制器(取消选中以使用最小Api)。
  5. 取消勾选不使用顶级语句。
  6. 点击创建。
  7. 右键管理NuGet包引入:
  8. Microsoft.IdentityModel.Tokens
  9. Newtonsoft.Json
  10. System.IdentityModel.Tokens.Jwt

二:添加关键类

添加关键类JWTTokenOptions

namespace Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility
{
    public class JWTTokenOptions
    {
        public string Audience { get; set; }
        public string SecurityKey { get;set; }
        public string Issuer { get; set; }
    }
}

添加关键类ICustomJWTService

namespace Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility
{
    public interface ICustomJWTService
    {
        string GetToken(string UserName, string PassWord);
    }
}

添加关键类CustomHSJWTService

using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility
{
    public class CustomHSJWTService : ICustomJWTService
    {
        /// <summary>
        /// 注入构造函数
        /// </summary>
        private readonly JWTTokenOptions _JWTTokenOptions;
        public CustomHSJWTService(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions)
        {
            this._JWTTokenOptions = jwtTokenOptions.CurrentValue;
        }
        /// <summary>
        /// 用户登录成功之后
        /// 用来生成Token方法
        /// </summary>
        /// <param name="UserName">用户账号</param>
        /// <param name="PassWord">用户密码</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string GetToken(string UserName, string PassWord)
        {
            //有效载荷,避免敏感信息
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,UserName),
                new Claim(ClaimTypes.Role,"Administrator"),
                new Claim("NickName",UserName),
                new Claim("Role","Admin"),
                new Claim("ABCD","ABCD"),
                new Claim("Student","酱油")
            };
            //获取加密KEY
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));
            //加密KEY
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //准备生成Token
            JwtSecurityToken token = new JwtSecurityToken(issuer: _JWTTokenOptions.Issuer, audience: _JWTTokenOptions.Audience, claims: claims, expires: DateTime.Now.AddMinutes(5), signingCredentials: creds);
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }
    }
}

三:修改appsettings.json文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "JWTTokenOptions": {
    "Audience": "http://localhost:5200",
    "Issuer": "http://localhost:5200",
    "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
  }
}

四:修改Program.cs文件

using Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility;

//表示整个应用程序,调用CreateBuilder方法创建一个WebApplicationBuilder对象
var builder = WebApplication.CreateBuilder(args);

//向管道容器添加注册中间件
//添加注册Controller中间件
//添加注册Swagger中间件
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//添加注册JWT鉴权授权
builder.Services.Configure<JWTTokenOptions>(builder.Configuration.GetSection("JWTTokenOptions"));
builder.Services.AddTransient<ICustomJWTService, CustomHSJWTService>();

//配置管道容器中间件,构造WebApplication实例
var app = builder.Build();

//配置HTTP请求管道判断开发者模式
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//向管道添加用于将HTTP请求重定向到HTTPS的中间件
app.UseHttpsRedirection();
//向管道添加用于身份鉴权授权中间件
app.UseAuthorization();
//向管道添加用于Controller中间件
app.MapControllers();


//向管道添加启动应用程序中间件
app.Run();

五:添加控制器AuthenticationController

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Study_ASP.NET_Core_MVC.AuthenticationCenter.Utility;

namespace Study_ASP.NET_Core_MVC.AuthenticationCenter.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : Controller
    {
        /// <summary>
        /// 构造函数注入
        /// </summary>
        private ICustomJWTService _iJWTService = null;
        public AuthenticationController(ICustomJWTService customJWTService)
        {
            _iJWTService = customJWTService;
        }
        [Route("Get")]
        [HttpGet]
        public IEnumerable<int> Get()
        {
            return new List<int>() { 1, 2, 3, 4, 6, 7 };
        }

        [Route("Login")]
        [HttpPost]
        public string Login(string UserName, string PassWord)
        {
            //判断用户账号和密码
            if ("VinCente".Equals(UserName) && "123456".Equals(PassWord))
            {
                //生成Token 
                string token = this._iJWTService.GetToken(UserName, PassWord);
                return JsonConvert.SerializeObject(new
                {
                    result = true,
                    token
                });

            }
            else
            {
                return JsonConvert.SerializeObject(new
                {
                    result = false,
                    token = ""
                });
            }
        }
    }
}

六:结果截图

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,针对您的问题,我可以给您一些关于js-cookie设置token过期时间以及ASP.NET Core Web APIJWT刷新Token的实用技巧。 首先,关于js-cookie设置token过期时间,可以通过以下代码实现: ```javascript // 设置cookie过期时间为1天 Cookies.set('token', 'your_token_value', { expires: 1 }); ``` 其中,`expires`属性表示过期时间,单位为天。 其次,关于ASP.NET Core Web APIJWT刷新Token,可以采用以下方法: 在JWT的payload中加入`exp`属性,表示token的过期时间。当token过期后,客户端需要向服务器发送请求,获取新的token。服务器对于过期的token,可以返回一个特定的状态码,比如401 Unauthorized。客户端接收到该状态码后,可以重新向服务器发送请求,获取新的token。 同时,在服务器端需要实现一个刷新token的接口,接口的功能是根据旧的token生成新的token。具体实现可以参考以下代码: ```csharp [HttpPost("refresh-token")] public IActionResult RefreshToken([FromBody] string token) { // 验证旧的token是否有效 var principal = _jwtService.GetPrincipalFromExpiredToken(token); if (principal == null) return BadRequest("Invalid token"); // 生成新的token var newToken = _jwtService.GenerateToken(principal.Claims); return Ok(newToken); } ``` 其中,`_jwtService`表示JWT的服务类,`GetPrincipalFromExpiredToken`方法用于从过期的token中获取`ClaimsPrincipal`对象,`GenerateToken`方法用于生成新的token。 希望以上内容对您有所帮助。如有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vin Cente

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值