JWTBearer

  JWTBearer框架是.NET中一种基于JSON Web Token (JWT)实现的身份验证和授权框架。JWT是一种开放标准,用于在不同系统之间安全地传输信息。它使用JSON对象来表示声明,声明包含关于实体(通常是用户)的信息以及与该实体相关的元数据。这些声明可以被签名和/或加密,以确保只有授权用户可以访问它们。

  JWTBearer框架建立在ASP.NET Core中的身份验证和授权机制之上。它使用JWT作为身份验证令牌,当用户成功验证后,它会将该令牌放置在请求标头中。这个标头可以被中间件检索并用于授权请求。

如何实现JWTBearer框架?

要在.NET应用程序中实现JWTBearer框架,需要执行以下步骤:

步骤1:安装必要的包

在.NET应用程序中使用JWTBearer框架需要安装以下两个NuGet包:

  • Microsoft.AspNetCore.Authentication.JwtBearer
  • System.IdentityModel.Tokens.Jwt

可以使用Visual Studio的NuGet包管理器或在终端窗口中使用以下命令来安装这些包:

Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Install-Package System.IdentityModel.Tokens.Jwt

步骤2:配置身份验证服务

在.NET应用程序的Startup.cs文件中,需要添加身份验证服务的配置。这可以通过调用AddAuthentication方法并传递一个AuthenticationScheme对象来完成。在JWTBearer框架中,可以使用JwtBearerDefaults.AuthenticationScheme来表示此方案。在配置过程中,需要提供JWT的发行者、受众者、密钥等信息。

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "your-issuer",
                ValidAudience = "your-audience",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
            };
        });
}

 

步骤3:配置授权策略

在.NET应用程序中,授权策略用于定义哪些用户可以访问哪些资源。在JWTBearer框架中,可以使用RequireAuthenticatedUser()方法来指定只有授权用户才能访问资源。

using Microsoft.AspNetCore.Authorization;

public void ConfigureServices(IServiceCollection services)
{
    // 配置身份验证服务
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            // 省略配置代码
        });

    // 配置授权策略
    services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
    });
}

 

步骤4:启用身份验证和授权

在.NET应用程序中,需要调用UseAuthentication()方法来启用身份验证中间件,调用UseAuthorization()方法来启用授权中间件。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 省略其他配置代码

    // 启用身份验证和授权中间件
    app.UseAuthentication();
    app.UseAuthorization();
}

 

JWTBearer框架的使用示例

在.NET应用程序中使用JWTBearer框架的基本步骤已经介绍完毕。接下来,我们将使用一个具体的示例来演示如何实现身份验证和授权。

假设我们正在开发一个API,用于管理用户的订单。我们希望只有授权用户才能访问该API。我们将使用JWTBearer框架来实现此功能。

步骤1:创建API

首先,我们需要创建一个API,用于管理用户的订单。我们可以使用ASP.NET Core Web API模板来创建此API。在Visual Studio中,选择"ASP.NET Core Web应用程序"项目模板,选择"API"模板,并输入项目名称和位置。

步骤2:添加身份验证和授权支持

接下来,我们需要添加身份验证和授权支持。在我们的API项目的Startup.cs文件中,我们将添加以下代码:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;

public void ConfigureServices(IServiceCollection services)
{
    // 配置身份验证服务
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "your-issuer",
                ValidAudience = "your-audience",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
            };
        });

    // 配置授权策略
    services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 省略其他配置代码

    // 启用身份验证和授权中间件
    app.UseAuthentication();
    app.UseAuthorization();
}

 

这将添加JWTBearer框架的身份验证和授权支持。我们将使用"your-issuer"、"your-audience"和"your-secret-key"作为示例值,实际应用程序中需要使用自己的值。

步骤3:添加API控制器

接下来,我们需要添加API控制器。在我们的API项目中,我们将添加一个名为"OrdersController"的控制器。此控制器将包含管理订单的API操作。

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
[Authorize]
public class OrdersController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        // 返回所有订单
        return Ok("All Orders");
    }

    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        // 根据订单ID返回订单
        return Ok($"Order {id}");
    }

    [HttpPost]
    public IActionResult Post()
    {
        // 创建新订单
        return Ok("New Order Created");
    }

    [HttpPut("{id}")]
    public IActionResult Put(int id)
    {
        // 更新订单
        return Ok($"Order {id} Updated");
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        // 删除订单
        return Ok($"Order {id} Deleted");
    }
}

 

注意,我们在"OrdersController"类上添加了Authorize属性。这意味着只有授权用户才能访问"OrdersController"中的API操作。

步骤4:生成JWT令牌

现在,我们需要生成一个JWT令牌,并将其用于身份验证。我们将使用Microsoft.IdentityModel.Tokens库中的JwtSecurityToken类来生成JWT令牌。

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

public string GenerateJwtToken(string userId, string username, string secretKey, string issuer, string audience, int expirationMinutes = 60)
{
    // 创建声明
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, userId),
        new Claim(JwtRegisteredClaimNames.UniqueName, username),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };

    // 创建密钥
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

    // 创建凭证
    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    // 创建JWT令牌
    var token = new JwtSecurityToken(
        issuer: issuer,
        audience: audience,
        claims: claims,
        expires: DateTime.UtcNow.AddMinutes(expirationMinutes),
        signingCredentials: credentials);

    // 序列化JWT令牌
    var encodedToken = new JwtSecurityTokenHandler().WriteToken(token);

    return encodedToken;
}

 

在这个方法中,我们需要传递userId、username、secretKey、issuer、audience和expirationMinutes参数。userId和username将包含在JWT令牌的声明中。secretKey将用于签署JWT令牌。issuer和audience将用于验证JWT令牌。expirationMinutes将指定JWT令牌的有效期。

步骤5:使用JWT令牌进行身份验证

现在,我们可以使用上一步中生成的JWT令牌进行身份验证。我们可以使用HTTP客户端发送一个带有Authorization标头的请求,其中包含JWT令牌。

以下是一个使用C# HttpClient类进行身份验证的示例:

using System;
using System.Net.Http;
using System.Threading.Tasks;

public async Task<string> CallApi(string token)
{
    using (var client = new HttpClient())
    {
        // 添加Authorization标头
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

        // 发送请求
        var response = await client.GetAsync("https://your-api.com/orders");

        // 检查响应状态码
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            return content;
        }
        else
        {
            return null;
        }
    }
}

 

在这个方法中,我们需要传递一个JWT令牌作为参数。我们将在Authorization标头中包含此JWT令牌,并使用HttpClient类发送请求。

如果JWT令牌有效且包含正确的声明,我们的API将返回请求的资源。否则,API将返回401未经授权的响应。

posted @ 2024-03-20 22:15  一事冇诚  阅读(160)  评论(0编辑  收藏  举报