首页 > 其他分享 >jwt实现登录 和 接口实现动态权限

jwt实现登录 和 接口实现动态权限

时间:2024-04-03 14:47:51浏览次数:11  
标签:builder 实现 app jwt 接口 new var using public

 [Authorize]   ====   using Microsoft.AspNetCore.Authorization;  

 

登录的 DTO

namespace login;

public class WeatherForecast
{
    public DateOnly Date { get; set; }

    public int TemperatureC { get; set; }

    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

    public string? Summary { get; set; }
}

program.cs 实现 jwt 注册

using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        //取出私钥
        var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            //验证发布者
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["Authentication:Issuer"],
            //验证接收者
            ValidateAudience = true,
            ValidAudience = builder.Configuration["Authentication:Audience"],
            //验证是否过期
            ValidateLifetime = true,
            //验证私钥
            IssuerSigningKey = new SymmetricSecurityKey(secretByte)
        };
    });

var app = builder.Build();
//添加jwt验证
app.UseAuthentication();
app.UseAuthorization();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

csproj 依赖管理

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.17-preview.2.24128.4" />
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.10" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
  </ItemGroup>

</Project>

appsetting.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Authentication": {
    "SecretKey": "nadjhfgkadshgoihfkajhkjdhsfaidkuahfhdksjaghidshyaukfhdjks",
    "Issuer": "www.adsfsadfasdf",
    "Audience": "www.adsfsadfasdf"
  }
}

Controller 控制器:

using Microsoft.AspNetCore.Mvc;
using login.Dtos;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
namespace login.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    public readonly IConfiguration _configuration;
    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }
    [HttpPost("testLogin")]
    public IActionResult Login([FromBody] LoginDto loginDto)
    {
        //1.验证用户账号密码是否正确,暂时忽略,因为我们是模拟登录
        //2.生成JWT
        //Header,选择签名算法
        var signingAlogorithm = SecurityAlgorithms.HmacSha256;
        System.Console.WriteLine("算法");
        System.Console.WriteLine(signingAlogorithm);
        var claims = new[]
          {
                new Claim(JwtRegisteredClaimNames.Sub,"user_id"),
                new Claim(ClaimTypes.Role,"admin")
            };
        //取出私钥并以utf8编码字节输出
        var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
        //使用非对称算法对私钥进行加密
        var signingKey = new SymmetricSecurityKey(secretByte);
        //使用HmacSha256来验证加密后的私钥生成数字签名
        var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
        //生成Token
        var Token = new JwtSecurityToken(
                issuer: _configuration["Authentication:Issuer"],        //发布者
                audience: _configuration["Authentication:Audience"],    //接收者
                claims: claims,                                         //存放的用户信息
                notBefore: DateTime.UtcNow,                        //发布时间
                expires: DateTime.UtcNow.AddDays(1),                      //有效期设置为1天
                signingCredentials                                      //数字签名
            );
        //生成字符串 token
        var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
        return Ok(TokenStr);
    }

/// <summary>
/// [Authorize(Roles = "admin")] 需要验证token  只允许 admin 角色使用
/// </summary>
/// <returns></returns>
    [HttpGet(Name = "GetWeatherForecast")]
    [Authorize(Roles = "admin")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

实现基于jwt登录 

标签:builder,实现,app,jwt,接口,new,var,using,public
From: https://www.cnblogs.com/zhulongxu/p/18112653

相关文章

  • Android SystemUI 通知面板实现
    前言这篇文章给大家分享下AndroidSystemUI中下拉通知面板时所看到的开关面板(即QS面板)的实现原理,包括其整体架构,UI构建流程与事件处理流程,对这块感兴趣的同学可以看看一.QS面板构成元素解析QS面板实际上有多种状态,包括:QuickQuickSettings(QQS):即初级展开......
  • 基于donetcore/CAP实现分布式事务一致性
    官网:https://cap.dotnetcore.xyz相关介绍CAP是一个EventBus,同时也是一个在微服务或者SOA系统中解决分布式事务问题的一个框架。它有助于创建可扩展,可靠并且易于更改的微服务系统。在微软的 eShop 微服务示例项目中,推荐使用CAP作为生产环境可用的EventBus。什么是Event......
  • 用java去实现程序化广告应该有哪些步骤?
    目录1.需求分析和规划2.选择合适的技术栈3.搭建开发环境4.数据库设计5.后端开发6.前端开发7.集成第三方服务8.测试和调试9.部署上线10.持续优化和迭代1.需求分析和规划在这一阶段,我们需要详细分析和理解项目需求,并制定相应的规划和计划。这包括以下几个......
  • uniapp uni.showModal的content实现换行显示
    1.实现方法是:'\r\n'2.\r\n介绍\n软回车:在Windows中表示换行且回到下一行的最开始位置。相当于MacOS里的\r的效果。在Linux、unix中只表示换行,但不会回到下一行的开始位置。\r软空格:在Linux、unix中表示返回到当行的最开始位置。在MacOS中表示换行且返回到下一行的......
  • kettle使用MD5加密增量获取接口数据
    kettle使用MD5加密增量获取接口数据场景介绍:使用JavaScript组件进行MD5加密得到Httpheader,调用API接口增量获取接口数据,使用jsoninput组件解析数据入库案例适用范围:MD5加密可参考、增量过程可参考、调用API接口获取数据可参考、JsonInput组件使用可参考整个job设置......
  • PowerShell和DISM命令的组合用法,用于进行 Windows 映像的管理、部署和维护。通过结合
    PowerShell和DISM(DeploymentImageServicingandManagement)命令可以结合使用来进行Windows映像的部署、安装、更新和配置等操作。以下是一些常见的PowerShell和DISM命令的组合用法:安装和更新Windows功能:使用 Install-WindowsFeature cmdlet安装Windows功能,结合DISM......
  • VUE-axios统一增加请求头并根据接口返回的状态码判断用户登录状态并跳转登录页
    背景:后台接口返回code==501表示用户是未登录状态,需要登录才可访问;main.js中通过http拦截做路由跳转importVuefrom‘vue’importAxiosfrom‘axios’Vue.prototype.$axios=Axiosimport{Loading,Message,MessageBox}from‘element-ui’//超时时间Axios.......
  • 【经典算法】LeetCode 21:合并两个有序链表Java/C/Python3实现含注释说明,Easy)
    合并两个有序链表题目描述思路及实现方式一:迭代(推荐)思路代码实现Java版本C语言版本Python3版本复杂度分析方式二:递归(不推荐)思路代码实现Java版本C语言版本Python3版本复杂度分析总结相似题目标签:字符串处理、前缀判断题目描述将两个升序链表合并为一个新的升......
  • 在微信小程序中实现银行支付接入的技术实践
    在微信支付的大力普及下,手续费率也是大家最大的困扰,交易量比较小还可以忍受,但是一天几十万、几百万甚至几千万的交易金额,手续费就会成为商家的最大困扰。再客户极力的推荐增加银行支付接口,我们经过几个月的对接,终于把招商银行、农业银行、工商银行、建设银行的支付接口接入到小......
  • ENet——实时语义分割的深度神经网络架构与代码实现
    概述在移动设备上执行实时像素级分割任务具有重要意义。现有的基于分割的深度神经网络需要大量的浮点运算,并且通常需要较长时间才能投入使用。本文提出的ENet架构旨在减少潜在的计算负担。ENet在保持或提高分割精度的同时,相比现有的分割网络,速度提升了18倍,参数量减少了79倍......