jwt (token授权方式)

jwt

1.安装包

Microsoft.AspNetCore.Authentication.JwtBearer

2.startup

//JWT
 services.AddScoped();
            services.Configure(Configuration.GetSection("tokenConfig"));

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

            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)
        {
            _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]

你可能感兴趣的:(.net,core,jwt)