jwt (token授权方式)

本文介绍了JWT(JSON Web Tokens)作为授权方式的使用。详细步骤包括安装Microsoft.AspNetCore.Authentication.JwtBearer包,在Startup配置中添加UseAuthentication和UseAuthorization中间件,设置appsettings配置,以及实现IAuthenticateService接口用于控制器和登录调用的授权处理。特别指出,登录接口可以使用[AllowAnonymous]特性允许无权限访问。
摘要由CSDN通过智能技术生成

jwt

1.安装包

Microsoft.AspNetCore.Authentication.JwtBearer

2.startup

//JWT
 services.AddScoped<IAuthenticateService, TokenAuthenticationService>();
            services.Configure<TokenManagement>(Configuration.GetSection("tokenConfig"));

            var token = Configuration.GetSection("tokenConfig").Get<TokenManagement>();

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                //Token Validation Parameters
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    //获取或设置要使用的Microsoft.IdentityModel.Tokens.SecurityKey用于签名验证。
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.
                    GetBytes(token.Secret)),
                    //获取或设置一个System.String,它表示将使用的有效发行者检查代币的发行者。
                    ValidIssuer = token.Issuer,
                    //获取或设置一个字符串,该字符串表示将用于检查的有效受众反对令牌的观众。
                    ValidAudience = token.Audience,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                };
            });
            ///分割线
            //jwt授权
            app.UseAuthentication();//这个
            
            app.UseRouting();
            //启用跨域
            app.UseCors("cors");
            //引入wwwroot
            app.UseStaticFiles();
            //jwt
            app.UseAuthorization();//这个

app.UseAuthentication() app.UseAuthorization(); 位置固定

3.appsettings

 "tokenConfig": {
    "secret": "123456789123456789",//自行配置
    "issuer": "test.cn",
    "audience": "test",
    "accessExpiration": 30,
    "refreshExpiration": 60
  },

4.IAuthenticateService类

using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using XYZ_Order.Model;
using XYZ_Order.Services.user;

namespace XYZ_Order.Services
{
    public class LoginRequestDTO
    {
        public int? id { get; set; }
        
        public string Username { get; set; }

        public string Password { get; set; }
    }

    public interface IAuthenticateService
    {
        bool IsAuthenticated(LoginRequestDTO request,string root, out string token);
    }

    public class TokenAuthenticationService : IAuthenticateService
    {
        private readonly IUserService _userService;
        private readonly TokenManagement _tokenManagement;
        public TokenAuthenticationService(IUserService userService, IOptions<TokenManagement> tokenManagement)
        {
            _userService = userService;
            _tokenManagement = tokenManagement.Value;
        }
        public bool IsAuthenticated(LoginRequestDTO request,string root, out string token)
        {
            token = string.Empty;
            //if (!_userService.IsValid(request))
            //    return false;
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,request.Username),
                new Claim(ClaimTypes.Sid,request.id.ToString()),
                new Claim(ClaimTypes.Role,root)
                //new Claim("id",request.id.ToString())
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(_tokenManagement.Issuer, _tokenManagement.Audience, claims,
                expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration),
                signingCredentials: credentials);
            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return true;
        }
        
    }
}

控制器调用

[Authorize]

登录调用

[AllowAnonymous]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值