.Net Core WebApi 使用JWT完成鉴权和授权

1.引用程序集:System.IdentityModel.Tokens.Jwt

2.新建一个控制器(AuthoizeController),用于完成授权功能

示例代码:

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MyBlog.IService;
using MyBlog.JWT.Utility.ApiResult;
using MyBlog.JWT.Utility.MD5Util;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyBlog.JWT.Controllers
{
    /// <summary>
    /// JWT授权
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("any")] //设置跨域处理的 代理
    public class AuthoizeController : ControllerBase
    {
        private readonly IWriterInfoService _iWriterInfoService;

        public AuthoizeController(IWriterInfoService writerInfoService)
        {
            this._iWriterInfoService = writerInfoService;
        }

        [HttpPost("Login")]
        public async Task<ApiResult> Login(string username, string pwd)
        {
            string miwen = MD5Helper.MD5Encrypt(pwd);

            //数据校验(去数据库查询用户名和密码是否正确)
            var writerInfo = await _iWriterInfoService.FindAsync(c => c.UserName == username && c.UserPwd == miwen);
            if (writerInfo != null)
            {
                //登录成功
                var claims = new Claim[] {
                    new Claim(ClaimTypes.Name,writerInfo.Name), //可以通过this.User.Identity.Name访问到第二个参数的值
                    new Claim("Id",writerInfo.Id.ToString()),
                    new Claim("UserName",writerInfo.UserName)
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));//密钥
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:6060/",//颁发Token的web应用程序地址(当前程序)
                    audience: "http://localhost:5000/",//token接收程序的地址(WebApi)
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken);
            }
            else
            {
                return ApiResultHelper.Error("用户名或密码错误");
            }

        }

    }
}

上面代码不能完全照搬,需要根据项目实际情况进行改动。示例中是新建了一个webapi项目,专门用于授权操作。也可以不新建项目,直接在原有的webapi项目中添加一个新的控制器。

issuer:颁发Token的web应用程序地址(当前程序)

audience:token接收程序的地址(WebApi)

上面这两个地址需要根据实际情况配置,具体查看方法是去项目的Properties文件夹,找到launchSettings.json文件。

3.在服务中进行注册

引用程序集:Microsoft.AspNetCore.Authentication.JwtBearer

在Startup.cs中添加方法AddCustomJWT

        /// <summary>
        /// JWT鉴权
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddCustomJWT(this IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(option =>
                    {
                        option.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF")),
                            ValidateIssuer = true,
                            ValidIssuer = "http://localhost:6060/",
                            ValidateAudience = true,
                            ValidAudience = "http://localhost:5000/",
                            ValidateLifetime = true,
                            ClockSkew = TimeSpan.FromMinutes(60)
                        };
                    });
            return services;
        }

在ConfigureServices中调用AddCustomJWT完成服务的注册。

 

在Configure方法中启用鉴权和授权功能:

 

4.在控制器和action中使用鉴权功能

在控制器中使用: 

如果控制器中有单个方法不需要鉴权,则可以添加匿名访问特性(AllowAnonymous),跳过鉴权,直接访问该方法。

 

在action中使用:

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用.NET 6 Web API进行JWT授权鉴权的示例代码: 1. 首先,安装所需的NuGet包: ``` dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer dotnet add package System.IdentityModel.Tokens.Jwt ``` 2. 在Program.cs文件中进行配置: ```csharp using Microsoft.IdentityModel.Tokens; var builder = WebApplication.CreateBuilder(args); // 添加JWT认证服务 builder.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")) // 密钥 }; }); // 注册授权策略 builder.Services.AddAuthorization(); builder.Services.AddControllers(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run(); ``` 3. 创建一个控制器来处理认证请求: ```csharp using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.Tokens; [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { [AllowAnonymous] [HttpPost("login")] public IActionResult Login(string username, string password) { // 假设这里是验证用户名和密码的逻辑 // 如果验证通过,创建一个JWT token并返回给客户端 var token = GenerateToken(username); return Ok(new { token }); } [Authorize] [HttpGet("protected")] public IActionResult Protected() { // 受保护的路由,只有经过认证的用户才能访问 return Ok("You have accessed the protected route."); } private string GenerateToken(string username) { var claims = new[] { new Claim(ClaimTypes.Name, username), // 可以添加其他自定义的claims }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "your_issuer", audience: "your_audience", claims: claims, expires: DateTime.Now.AddMinutes(30), // token过期时间 signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); } } ``` 以上示例代码演示了如何使用.NET 6 Web APIJWT进行授权鉴权。请注意替换示例中的"your_issuer"、"your_audience"和"your_secret_key"为适合你的实际情况的值。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值