.Net Core Jwt鉴权授权

这篇具有很好参考价值的文章主要介绍了.Net Core Jwt鉴权授权。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录
  • 简介
  • 基于.Net Core 验证方式
  • Jwt获取Token
    • 引入三方包
    • 生成Token
    • UserInfo
    • JwtConfig
    • WebApi测试(获取Token)
      • Program.cs
      • appsetting.json
      • Controller
  • .Net Core 验证(webApi)
    • Progarm.cs
    • Contorller
  • .Net Core 授权
    • 简介
    • Program.cs
    • JwtAuthorization.cs
      • 注意
      • Autofac 注册授权服务
    • Controller
      • 注意
  • jwt触发委托

简介

  • Jwt分为三段 通过远点分割
  1. header => 描述这个token加密方式
  2. PlayLoad => 有效载荷,用户信息+自定义Claims信息Verify
  3. Signature => 签名, (头部信息base64处理,有效载荷base64处理) + 密钥
  • 示例 :
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJFeHRlbmRlZDEiOiLml6Dkv6Hmga8iLCJFeHRlbmRlZDIiOiIiLCJFeHRlbmRlZDMiOiIiLCJFeHRlbmRlZDQiOiIiLCJFeHRlbmRlZDUiOiIiLCIxIjoi57O757uf566h55CG5ZGYIiwiMiI6IueUqOaIt-euoeeQhuWRmCIsImV4cCI6MTY4ODkwMTA2NiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDg4IiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1MDg4In0.7J1J7yWj4ELHJZIwLKnT4RgcMu3rGAX5ACBFfCS0LWM

基于.Net Core 验证方式

  1. 生成jwtToken
  2. 标记[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
  3. 验证 Issuer
  4. 验证 Audience
  5. 验证 SecurityKey
  6. 验证自定义验证
  7. 验证完成可以正常访问接口

验证的那几步顺序可以直接在自定义验证中验证

Jwt获取Token

引入三方包

<ItemGroup>
    <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.31.0" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.31.0" />
</ItemGroup>

生成Token


using Microsoft.IdentityModel.Tokens;
using Programming.DotNetCore.Function.Entity.Jwt;
using Programming.DotNetCore.Function.Interface.PasswordService;
using Programming.DotNetCore.Function.Password.Entity;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Programming.DotNetCore.Function.Password
{
    public class JwtServices : IPassWordService
    {
        public string GetToken(UserInfo user,JwtConfig jwtConfig)
        {
            List<Claim> claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName ?? ""),
                new Claim("Extended1", user.Extended1 ?? ""),
                new Claim("Extended2", user.Extended2 ?? ""),
                new Claim("Extended3", user.Extended3 ?? ""),
                new Claim("Extended4", user.Extended4 ?? ""),
                new Claim("Extended5", user.Extended5 ?? ""),
            };
            if (user.Role is not null)
            {
                foreach (var item in user.Role)
                {
                    claims.Add(new Claim(item.Id.ToString(), item.Role));
                }
            }
            if(jwtConfig.SecurityKey == null)
            {
                throw new Exception("JwtConfig.SecurityKey 不能为空");
            }
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey));
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            JwtSecurityToken token = new JwtSecurityToken(
                issuer:jwtConfig.Issuer,
                audience:jwtConfig.Audience,
                claims:claims,
                expires: DateTime.UtcNow.AddMinutes(jwtConfig.ExpiresMinutes),
                signingCredentials:creds
            );
            string resultToken = new JwtSecurityTokenHandler().WriteToken(token);
            return resultToken;
        }
    }
}

UserInfo

namespace Programming.DotNetCore.Function.Password.Entity
{
    public class UserInfo
    {
        public string? UserName { get; set; }
        public List<RoleInfo>? Role { get; set; }
        public string? Extended1 { get; set; }
        public string? Extended2 { get; set; }
        public string? Extended3 { get; set; }
        public string? Extended4 { get; set; }
        public string? Extended5 { get; set; }
    }
}

JwtConfig

namespace Programming.DotNetCore.Function.Entity.Jwt
{
    public class JwtConfig
    {
        public string? Audience { get; set; }
        public string? Issuer { get; set; }
        public string? SecurityKey { get; set; }
        public int ExpiresMinutes { get; set; }
    }
}

WebApi测试(获取Token)

Program.cs

//读取Jwt配置
builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("JwtTokenOptions"));

appsetting.json

{
  "JwtTokenOptions": {
    "Issuer": "http://localhost:5088",
    "Audience": "http://localhost:5088",
    "SecurityKey": "kq4DY5N1eFJhscOkI7Zp4Nd0WNy9d9AEsN6Yjgdv9OxLyol66tzGBKT_7vwolN7GZ8EDwqJBwccjDJfb81ws5s3sbbP5wUzQ3-PcTSsD-Rueiu2rsOUZwg_NR3RBCwmtouV-832YV2trCjNTawLB1z0LMukWGFNaAJVZ8WdQcrYn6a0ko5oVhZqaHBgsCLEGiqPtoFsiCcrJTz1IvXHk9_cDSr2hwEmSl18GlkOtgCHFH8aidYth3aQHRHuClTi6Y9mYRJtqqK-FNQYq4ZP23DSGZGFejJFTnM9YMpppuTMLklhSGySwX8rfjZ_0L5ac18nHaykTaiC2fvH00W42qQ"
  }
}

Controller

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Programming.DotNetCore.Function.Entity.Jwt;
using Programming.DotNetCore.Function.Interface.PasswordService;
using Programming.DotNetCore.Function.Password.Entity;

namespace Cnpc.Com.Ioc.WebApp.Controllers
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class TestJwtController : ControllerBase
    {
        IPassWordService _passWordService;
        JwtConfig _jwtconfig;

        public TestJwtController(IPassWordService passWordService,IOptions<JwtConfig> jwtconfig) 
        {
            _passWordService = passWordService;
            _jwtconfig = jwtconfig.Value;
        }

        [HttpGet]
        public IActionResult Login(string userName,string passWord)
        {
            string token = _passWordService.GetToken(new()
            {
                UserName = userName,
                Extended1 = "无信息",
                Role = new List<RoleInfo>() 
                { 
                    new RoleInfo() { Id = "1",Role="系统管理员"} ,
                    new RoleInfo() { Id = "2",Role="用户管理员"} ,
                }
            }, new()
            {
                Audience = _jwtconfig.Audience,
                Issuer= _jwtconfig.Issuer,
                SecurityKey= _jwtconfig.SecurityKey,
                ExpiresMinutes = 5,
            });

            return new JsonResult(new { token = token }); 
        }
    }
}

.Net Core 验证(webApi)

Progarm.cs

添加JWT验证

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidIssuer = jwtConfig.Issuer, //发行人
        ValidateAudience = true,
        ValidAudience = jwtConfig.Audience,//订阅人
        ValidateIssuerSigningKey = true,
        //对称加密密钥
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey!)),
        ValidateLifetime = true, //验证失效时间
        ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值
        RequireExpirationTime = true,
        AudienceValidator = (audiences, securityToken, validationParameters) =>
        {
            return true;
        },
        LifetimeValidator = (notBefore,expires,  securityToken, validationParameters) =>
        {
            return true;
        }
    };
});

app.UseAuthentication();

读取配置文件

JwtConfig jwtConfig = new JwtConfig();
builder.Configuration.Bind("JwtTokenOptions", jwtConfig);

添加Swagger支持,api右上角可以写Token

builder.Services.AddSwaggerGen(c =>
{
    //添加Jwt验证设置,添加请求头信息
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Id = "Bearer",
                    Type = ReferenceType.SecurityScheme
                }
            },
            new List<string>()
        }
    });

    //放置接口Auth授权按钮
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "Value Bearer {token}",
        Name = "Authorization",//jwt默认的参数名称
        In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
        Type = SecuritySchemeType.ApiKey
    });
}); ;

Contorller

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Programming.DotNetCore.Function.Entity.Jwt;
using Programming.DotNetCore.Function.Interface.PasswordService;
using Programming.DotNetCore.Function.Password.Entity;

namespace Cnpc.Com.Ioc.WebApp.Controllers
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class TestJwtController : ControllerBase
    {
        [HttpGet]
        [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
        public IActionResult TestApi()
        {
            //获取用户Claim信息
            var user = HttpContext.User.Claims.Select(it => new { it.Type,it.Value});
            return new JsonResult(user);
        }
    }
}

.Net Core 授权

简介

可以在数据库中进一步验证访问接口的权限

Program.cs

//jwt 授权
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("JwtPolicy", policy =>
    {
        //jwt 授权
        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        //这里为自定义授权指定一下类
        .AddRequirements(new UserRoleRequirement(JwtBearerDefaults.AuthenticationScheme)); 
    });
});

app.UseAuthorization();

JwtAuthorization.cs

注意

验证中涉及到 IUserServices 和 JwtAuthorization, 需要在ioc容器中注册一下,我这里使用的是Autofac注册,如果使用系统自带的注册可以这么写:

  • builder.Services.AddTransient<IUserServices, UserServices>();
  • builder.Services.AddTransient<IAuthorizationHandler, JwtAuthorization>();

Autofac 注册授权服务

using Autofac;
using Autofac.Extras.DynamicProxy;
using Castle.DynamicProxy;
using Cnpc.Com.Ioc.Bll;
using Cnpc.Com.Ioc.Dal;
using Cnpc.Com.Ioc.IBll;
using Cnpc.Com.Ioc.IDal;
using Cnpc.Com.Ioc.Tools;
using Cnpc.Com.Ioc.WebApp.Authorization;
using Cnpc.Com.Ioc.WebApp.Filter.ActionFilter;
using Microsoft.AspNetCore.Authorization;
using Programming.DotNetCore.Function.Interface.PasswordService;
using Programming.DotNetCore.Function.Password;

namespace WepApiTest.Autofac
{
    public class AutofacConfig : Module
    {

        protected override void Load(ContainerBuilder builder)
        {
            //ioc
            builder.RegisterType<JwtAuthorization>().As<IAuthorizationHandler>();
            builder.RegisterType<UserServices>().As<IUserServices>();
        }
    }
}
using Cnpc.Com.Ioc.IBll;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

namespace Cnpc.Com.Ioc.WebApp.Authorization
{
    public class UserRoleRequirement : IAuthorizationRequirement
    {
        public string AuthenticateScheme;
        public UserRoleRequirement(string authenticateScheme)
        {
            AuthenticateScheme = authenticateScheme;
        }
    }
    public class JwtAuthorization : AuthorizationHandler<UserRoleRequirement>
    {
        IUserServices userSercices;
        public JwtAuthorization(IUserServices userSercices)
        {
            this.userSercices = userSercices;
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserRoleRequirement requirement)
        {
            string? userName = context.User.FindFirst(it => it.Type == ClaimTypes.Name)?.Value;
            if (userSercices.IsAdmin(userName!))
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
            return Task.CompletedTask;
        }
    }
}

Controller

注意

唯一需要修改的地方就是这里, 指定Policy 为 Program.cs 中设置授权方案名称文章来源地址https://www.toymoban.com/news/detail-538362.html

  • [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme,Policy = "JwtPolicy")]
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Programming.DotNetCore.Function.Entity.Jwt;
using Programming.DotNetCore.Function.Interface.PasswordService;
using Programming.DotNetCore.Function.Password.Entity;

namespace Cnpc.Com.Ioc.WebApp.Controllers
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class TestJwtController : ControllerBase
    {
        [HttpGet]
        [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme,Policy = "JwtPolicy")]
        public IActionResult TestApi()
        {
            var user = HttpContext.User.Claims.Select(it => new { it.Type,it.Value});
            return new JsonResult(user);
        }
    }
}

jwt触发委托

 builder.Services.AddAuthentication(options =>
            {
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidIssuer = jwtConfig.Issuer, //发行人
                    ValidateAudience = true,
                    ValidAudience = jwtConfig.Audience,//订阅人
                    ValidateIssuerSigningKey = true,
                    //对称加密密钥
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey!)),
                    ValidateLifetime = true, //验证失效时间
                    ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值
                    RequireExpirationTime = true,
                    AudienceValidator = (audiences, securityToken, validationParameters) =>
                    {
                        return true;
                    },
                    LifetimeValidator = (notBefore,expires,  securityToken, validationParameters) =>
                    {
                        return true;
                    }
                };

                options.Events = new JwtBearerEvents() 
                {
                    //身份验证失败出发
                    OnAuthenticationFailed = AuthenticationFailedContext =>
                    {
                        return Task.CompletedTask;
                    },
                    //授权失败触发
                    OnForbidden = ForbiddenContext =>
                    {
                        return Task.CompletedTask;
                    },
                    //请求时候触发
                    OnMessageReceived = MessageReceivedContext =>
                    {
                        return Task.CompletedTask;
                    },
                    //Token验证成功触发
                    OnTokenValidated = TokenValidatedContext =>
                    {
                        return Task.CompletedTask;
                    },
                    //没有token,授权Handler处理失败触发
                    OnChallenge = JwtBearerChallengeContext =>
                    {
                        return Task.CompletedTask;
                    }
                };
            });

到了这里,关于.Net Core Jwt鉴权授权的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • ASP.NET Core 鉴权授权三(添加自定义授权策略)

    此处鉴权给的值是6,授权用的1,尝试访问 基于策略的授权中有一个很重要的概念是Requirements,每一个Requirement都代表一个授权条件。 Requirement需要继承接口IAuthorizationRequirement。 已经内置了一些常用的实现: AssertionRequirement :使用最原始的断言形式来声明授权策略。 DenyAn

    2024年02月03日
    浏览(25)
  • ASP.NET Core 鉴权授权一(简单的Cookie)

    简单的理解:鉴权衡量你能不能进一道门,授权是你进门了可以干什么

    2024年02月03日
    浏览(19)
  • ASP.NET Core 鉴权授权二(自定义token)

    首先自定义一个类TokenAuthenticationHandler,然后需要继承IAuthenticationHandler接口 具体代码: 后续需要鉴权的接口,在请求上都需要加上Authorization参数 Claim:相当于一个身份单元,存储着键值信息 ClaimsIdentity:身份证,身份单元的集合(可以理解为身份证上有多个身份单元) Clai

    2024年02月03日
    浏览(23)
  • ASP.NET Core MVC 从入门到精通之鉴权授权基础

    随着技术的发展,ASP.NET Core MVC也推出了好长时间,经过不断的版本更新迭代,已经越来越完善,本系列文章主要讲解ASP.NET Core MVC开发B/S系统过程中所涉及到的相关内容,适用于初学者,在校毕业生,或其他想从事ASP.NET Core MVC 系统开发的人员。 经过前几篇文章的讲解,初步

    2024年02月08日
    浏览(28)
  • 如何在.net6webapi中配置Jwt实现鉴权验证

    jwt是一种用于身份验证的开放标准,他可以在网络之间传递信息,jwt由三部分组成:头部,载荷,签名。头部包含了令牌的类型和加密算法,载荷包含了用户的信息,签名则是对头部和载荷的加密结果。 jwt鉴权验证是指在用户登录成功后,服务器生成一个jwt令牌并返回给客户

    2024年02月07日
    浏览(35)
  • ASP.NET Core高级之认证与授权(二)--JWT认证前后端完整实现

    了解JWT身份认证的流程 了解基于JWT身份认证和Session身份认证的区别 学习如何在ASP.NET Core WebAPI项目中封装JWT认证功能 在上文ASP.NET Core高级之认证与授权(一)–JWT入门-颁发、验证令牌中演示了JWT认证的一个入门案例,本文是一个基于JWT认证的完整的前后端实现代码案例。 JWT身

    2024年02月01日
    浏览(36)
  • ASP.NET Core使用JWT+标识框架(identity)实现登录验证

    最近阅读了《ASP.NET Core 技术内幕与项目实战——基于DDD与前后端分离》(作者杨中科)的第八章,对于Core入门的我来说体会颇深,整理相关笔记。 JWT:全称“JSON web toke”,目前流行的跨域身份验证解决方案; 标识框架(identity):由ASP.NET Core提供的框架,它采用RBAC(role

    2024年02月11日
    浏览(33)
  • .NET CORE开源 DDD微服务 支持 多租户 单点登录 多级缓存、自动任务、分布式、日志、授权和鉴权 、网关 、注册与发现 系统架构 docker部署

    源代码地址https://github.com/junkai-li/NetCoreKevin 基于NET6搭建跨平台DDD思想WebApi架构、IDS4单点登录、多缓存、自动任务、分布式、多租户、日志、授权和鉴权、CAP、SignalR、 docker部署  如需简约项目可直接去除项目引用 解耦设计都可以单独引用 架构默认全部引用并启动 项目启动时

    2023年04月24日
    浏览(35)
  • AspNetCore 成长杂记(一):JWT授权鉴权之生成JWT(其一)

    最近不知怎么的,自从学了WebAPI(为什么是这个,而不是MVC,还不是因为MVC的Razor语法比较难学,生态不如现有的Vue等框架,webapi很好的结合了前端生态)以后,使用别人的组件一帆风顺,但是不知其意,突然很想自己实现一个基于的JWT认证服务,来好好了解一下这个内容。 自

    2023年04月19日
    浏览(25)
  • AspNetCore 成长杂记(一):JWT授权鉴权之生成JWT(其二)

    前面说了用第三方类库生成JWT的故事,给我带来了很大的方便,并且我也承诺要写一篇用常规方法生成JWT的文章( 一般都是用微软官方的类库 ),因此才有了这篇文章。 另外,在前面的文章中,我要纠正一下一些错误JWT的整个结构决定了JWT只能作为临时的授权认证解决方案,

    2023年04月26日
    浏览(24)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包