ASP.NET Core应用JWT进行用户认证及Token的刷新方案

yizhihongxing

下面是关于“ASP.NET Core应用JWT进行用户认证及Token的刷新方案”的完整攻略,包含两个示例说明。

简介

JWT(JSON Web Token)是一种用于身份验证的开放标准,它可以在客户端和服务器之间安全地传输信息。在ASP.NET Core中,我们可以使用JWT来进行用户认证,并实现Token的刷新。本文将详细讲解如何在ASP.NET Core应用中使用JWT进行用户认证及Token的刷新方案。

用户认证及Token的刷新方案

以下是在ASP.NET Core应用中使用JWT进行用户认证及Token的刷新方案的步骤:

  1. 在ASP.NET Core应用中安装Microsoft.AspNetCore.Authentication.JwtBearer NuGet包:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

在上面的命令中,我们使用dotnet命令来安装Microsoft.AspNetCore.Authentication.JwtBearer NuGet包。

  1. 在appsettings.json文件中添加JWT配置:
{
  "Jwt": {
    "Issuer": "YourIssuer",
    "Audience": "YourAudience",
    "Key": "YourKey",
    "ExpireMinutes": 60,
    "RefreshExpireMinutes": 1440
  }
}

在上面的代码中,我们添加了JWT的配置信息,包括Issuer、Audience、Key、ExpireMinutes和RefreshExpireMinutes等。

  1. 在Startup.cs文件中添加JWT认证服务:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

public void ConfigureServices(IServiceCollection services)
{
    // ...

    var jwtSettings = Configuration.GetSection("Jwt");
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Key"]));

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = jwtSettings["Issuer"],
                ValidAudience = jwtSettings["Audience"],
                IssuerSigningKey = key
            };
        });

    // ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseAuthentication();
    app.UseAuthorization();

    // ...
}

在上面的代码中,我们添加了JWT认证服务,并配置了TokenValidationParameters。

  1. 在AccountController中添加登录和刷新Token的API接口:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

[ApiController]
[Route("[controller]")]
public class AccountController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public AccountController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [AllowAnonymous]
    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel model)
    {
        if (model == null)
        {
            return BadRequest("Invalid client request");
        }

        if (model.Username == "admin" && model.Password == "admin")
        {
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, model.Username),
                new Claim(ClaimTypes.Role, "Admin")
            };

            var tokenOptions = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(Convert.ToDouble(_configuration["Jwt:ExpireMinutes"])),
                signingCredentials: signingCredentials
            );

            var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
            return Ok(new { Token = tokenString });
        }
        else
        {
            return Unauthorized();
        }
    }

    [AllowAnonymous]
    [HttpPost("refresh")]
    public IActionResult Refresh([FromBody] RefreshTokenModel model)
    {
        if (model == null)
        {
            return BadRequest("Invalid client request");
        }

        var principal = GetPrincipalFromExpiredToken(model.Token);
        var username = principal.Identity.Name; //this is mapped to the Name claim by default

        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
        var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, "Admin")
        };

        var tokenOptions = new JwtSecurityToken(
            issuer: _configuration["Jwt:Issuer"],
            audience: _configuration["Jwt:Audience"],
            claims: claims,
            expires: DateTime.Now.AddMinutes(Convert.ToDouble(_configuration["Jwt:ExpireMinutes"])),
            signingCredentials: signingCredentials
        );

        var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
        return Ok(new { Token = tokenString });
    }

    private ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
    {
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = false,
            ValidateIssuer = false,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])),
            ValidateLifetime = false //here we are saying that we don't care about the token's expiration date
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        SecurityToken securityToken;
        var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);
        var jwtSecurityToken = securityToken as JwtSecurityToken;
        if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
        {
            throw new SecurityTokenException("Invalid token");
        }

        return principal;
    }
}

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class RefreshTokenModel
{
    public string Token { get; set; }
}

在上面的代码中,我们添加了Login和Refresh API接口,用于用户登录和Token的刷新。

  1. 在Startup.cs文件中添加Swagger UI:
using Microsoft.OpenApi.Models;

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });

    // ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    // ...
}

在上面的代码中,我们添加了Swagger UI,用于测试API接口。

  1. 启动应用程序,并使用Postman等工具测试API接口。

示例说明

以下是两个示例说明,演示如何在ASP.NET Core应用中使用JWT进行用户认证及Token的刷新:

示例1:用户登录

使用Postman向"http://localhost:5000/account/login"发送POST请求,请求体中包含用户名和密码,即可获取Token。

示例2:Token刷新

使用Postman向"http://localhost:5000/account/refresh"发送POST请求,请求体中包含过期的Token,即可获取新的Token。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:ASP.NET Core应用JWT进行用户认证及Token的刷新方案 - Python技术站

(0)
上一篇 2023年5月16日
下一篇 2023年5月16日

相关文章

  • python数据分析之员工个人信息可视化

    对于“python数据分析之员工个人信息可视化”的完整攻略,我可以给出如下的示例过程: 1. 安装必要的依赖库 对于本次分析项目,我们需要安装一些必要的依赖库,比如pandas、matplotlib、seaborn等。我们可以通过在命令行输入以下内容来完成依赖库的安装: pip install pandas matplotlib seaborn 2. 读取员…

    云计算 2023年5月18日
    00
  • Task提高异步执行效率技巧

    Task提高异步执行效率技巧 在JavaScript中,异步编程是非常常见的。Task是一种异步编程模式,可以提高异步执行效率。本文将提供一个完整的攻略,包括Task的概念、Task的使用方法、Task的优化技巧以及两个示例说明。 Task的概念 Task是一种异步编程模式,可以将多个异步操作组合成一个任务,以提高异步执行效率。Task通常由多个步骤组成,每…

    云计算 2023年5月16日
    00
  • 2019年Java,php,运维工程师转型大数据前景展望,看看你属于哪一类

    2019年Java,php,运维工程师转型大数据前景展望,看看你属于哪一类 随着大数据技术的不断发展,越来越多的企业开始重视大数据的应用和开发。在这个背景下,Java、PHP、运维等工程师转型大数据成为了一个热门话题。下面是一份关于2019年Java、PHP、运维工程师转型大数据前景展望的完整攻略,包括背景介绍、转型过程、示例说明等。 1. 背景介绍 Jav…

    云计算 2023年5月16日
    00
  • EC2(elastic compute cloud,弹性计算云,又称EC2实例)

    (一)定义:EC2和实例EC2(elastic compute cloud,弹性计算云),即云中的虚拟服务器。 是用于在云中创建和运行虚拟机的 Amazon Web 服务。简言之,EC2就是一部具有无限采集能力的虚拟计算机,用户能够用来执行一些处理任务。EC2是一种可选择的虚拟集群的服务模型。EC2实例:用户创建好AMI后,实际运行的系统称为一个实例(ins…

    2023年4月11日
    00
  • 【云计算】OpenStack qcow2镜像如何转化为Docker镜像?

    Import qcow2 image to docker hub                   参考资料: https://forums.docker.com/t/import-qcow2-image-to-docker-hub/6164 https://github.com/docker/docker/issues/1617 http://stack…

    云计算 2023年4月15日
    00
  • C#使用有道ip地址查询接口方法实例详解

    C#使用有道ip地址查询接口方法实例详解 本文将介绍如何在C#中使用有道ip地址查询接口进行IP地址查询。我们将会学习: 如何发送HTTP请求调用有道API 如何将API返回的JSON数据解析成C#对象 发送HTTP请求调用有道API 有道IP地址查询API是通过GET方法访问,请求URL为: http://apis.youdao.com/iplocatio…

    云计算 2023年5月17日
    00
  • 推荐8项提高 ASP.NET Web API 性能的技术

    推荐8项提高 ASP.NET Web API 性能的技术: 使用消息压缩 在 Web API 中使用消息压缩是一种提高性能的好方法。常用的消息压缩方式有 GZip 和 Deflate。您可以使用 Microsoft.AspNet.WebApi.MessageHandlers.Compression 包来实现消息压缩。 示例: config.MessageHa…

    云计算 2023年5月17日
    00
  • C#获取应用程序路径或Web页面目录路径

    C#获取应用程序路径或Web页面目录路径可以通过.NET Framework的System.IO和System.Web命名空间来实现。下面分别给出Windows应用程序和Web应用程序两个场景的示例说明。 获取Windows应用程序路径 方案一:使用Application.StartupPath 可以使用System.Windows.Forms命名空间的Ap…

    云计算 2023年5月17日
    00
合作推广
合作推广
分享本页
返回顶部