网站上如何设置行间距,安徽省建设工程信息网查询,微信保修网站开发源代码,魔贝课凡seo课程好吗本文以一个完整的示例#xff0c;展示如何在.NET 6.0 Web API项目中实现基于Token的身份验证。这个例子包括了如何创建和验证JWT Token#xff0c;以及如何在控制器中使用这些Token。
步骤 1: 创建Web API项目
首先#xff0c;用Visual Studio 2022创建一个基于.NET6.0的 … 本文以一个完整的示例展示如何在.NET 6.0 Web API项目中实现基于Token的身份验证。这个例子包括了如何创建和验证JWT Token以及如何在控制器中使用这些Token。
步骤 1: 创建Web API项目
首先用Visual Studio 2022创建一个基于.NET6.0的 Web API项目。
步骤 2: 安装必要的NuGet包
安装Microsoft.AspNetCore.Authentication.JwtBearer包。
步骤 3: 配置身份验证服务
在Program.cs中配置身份验证服务
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;var builder WebApplication.CreateBuilder(args);// 添加身份验证服务
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options {options.TokenValidationParameters new TokenValidationParameters{ValidateIssuer true,ValidateAudience true,ValidateLifetime true,ValidateIssuerSigningKey true,ValidIssuer builder.Configuration[Jwt:Issuer],ValidAudience builder.Configuration[Jwt:Audience],IssuerSigningKey new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration[Jwt:Key]))};});// 添加授权服务
builder.Services.AddAuthorization();var app builder.Build();// 使用身份验证和授权中间件
app.UseAuthentication();
app.UseAuthorization();// 其他配置和路由设置app.MapControllers();
app.Run();步骤 4: 配置JWT设置
在appsettings.json中配置JWT的相关设置
{Jwt: {Issuer: YourIssuer,Audience: YourAudience,Key: YourVerySecretKey}
}步骤 5: 创建Token生成控制器
创建一个控制器来生成Token
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;[ApiController]
[Route([controller])]
public class AuthController : ControllerBase
{private readonly IConfiguration _configuration;public AuthController(IConfiguration configuration){_configuration configuration;}[HttpPost(login)]public IActionResult Login([FromBody] LoginModel model){// 假设这里有一个验证逻辑验证用户名和密码if (model.Username test model.Password password){var tokenDescriptor new SecurityTokenDescriptor{Subject new ClaimsIdentity(new Claim[]{new Claim(ClaimTypes.Name, model.Username)}),Expires DateTime.UtcNow.AddMinutes(5),SigningCredentials new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration[Jwt:Key])), SecurityAlgorithms.HmacSha256Signature),Issuer _configuration[Jwt:Issuer],Audience _configuration[Jwt:Audience]};var tokenHandler new JwtSecurityTokenHandler();var token tokenHandler.CreateToken(tokenDescriptor);return Ok(new { token tokenHandler.WriteToken(token) });}else{return Unauthorized();}}
}public class LoginModel
{public string Username { get; set; }public string Password { get; set; }
}步骤 6: 创建受保护的控制器
创建一个控制器只有持有有效Token的用户才能访问
[ApiController]
[Route([controller])]
public class SecretController : ControllerBase
{[Authorize][HttpGet]public IActionResult Get(){return Ok(This is a secret message.);}
}步骤 7: 调用API
要调用API首先需要获取Token。可以使用Postman或类似的工具发送一个POST请求到/Auth/login并提供用户名和密码。然后使用返回的Token在Authorization头部中发送一个GET请求到/Secret。
POST /Auth/login HTTP/1.1
Host: localhost:5000
Content-Type: application/json{Username: test,Password: password
}GET /Secret HTTP/1.1
Host: localhost:5000
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoidGVzdCIsImV4cCI6MTYxODI3MzYwNSwiaXNzIjoiWW91ciJJc3N1ZXIiLCJhdWQiOiJZb3VyQXV0aGVudGljYXRpb24ifQ.6_3QXxZ3VzZvjZ7RnV5NQz-7y_93fY0Y7Y6jV7-XzQ确保在实际应用中实现安全的用户验证逻辑并且不要在代码中硬编码敏感信息。此外根据你的具体需求可能还需要实现用户注册、Token刷新等功能