ASP.NET Core 项目实战(JWT使用)

1.项目服务层(Service) 创建CustomJWTService.cs类

image.png
using Interface;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Model.Dto.User;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebModel.Other;

namespace Service
{
    public class CustomJWTService: ICustomJWTService
    {
        private readonly JwtTokenOptions _JWTTokenOptions;
        public CustomJWTService(IOptionsMonitor jwtTokenOptions)
        {
            _JWTTokenOptions = jwtTokenOptions.CurrentValue;
        }

        /// 
        /// 获取token
        /// 
        /// 
        /// 
        /// 
        public string GerToken(UserRes user)
        {
            #region 有效载荷,大家可以自己写,爱写多少写多少;尽量避免敏感信息
            var claims = new[]
            {
                    new Claim("Id",user.Id.ToString()),
                    new Claim("NickName",user.NickName),
                    new Claim("Name",user.Name),
                    new Claim("UserType",user.UserType.ToString()),
                };

            //需要加密:需要加密key:
            //Nuget引入:Microsoft.IdentityModel.Tokens
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));

            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //Nuget引入:System.IdentityModel.Tokens.Jwt
            JwtSecurityToken token = new JwtSecurityToken(
             issuer: _JWTTokenOptions.Issuer,
             audience: _JWTTokenOptions.Audience,
             claims: claims,
             expires: DateTime.Now.AddMinutes(10),//10分钟有效期
             signingCredentials: creds);

            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
            #endregion
        }
    }
}

2.注册服务 => HostBuilderExtend.cs

using Autofac;
using Autofac.Extensions.DependencyInjection;
using SqlSugar;
using System.Runtime.CompilerServices;
using WebModel.Other;

namespace WebApi.Config
{
    /// 
    /// 注册类-扩展
    /// 
    public static class HostBuilderExtend
    {
        public static void Register(this WebApplicationBuilder app)
        {
            // 1. nuGet 安装 autofac
            app.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            app.Host.ConfigureContainer(builder =>
            {
                #region 注册 sqlsugar
                builder.Register(context =>
                {
                    SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        //数据库配置地址
                        ConnectionString = "Server=;Database=zxAdminDb;Uid=sa;Pwd=root",
                        DbType = DbType.SqlServer,
                        IsAutoCloseConnection = true
                    });
                    //支持SQL 语句的输出,方便排查问题
                    db.Aop.OnLogExecuted = (sql, par) =>
                    {
                        Console.WriteLine("\r\n");
                        Console.WriteLine($"{DateTime.Now.ToString("yyyyMMdd HH:mm:ss")},Sql语句:{sql}");
                        Console.WriteLine("===================================================");
                    };
                    return db; 
                });
                #endregion

                // 注册接口和实现层
                builder.RegisterModule(new AutofacModuleRegister());
            });
            //Automapper映射
            app.Services.AddAutoMapper(typeof(AutoMapperConfigs));

            // 注册JWT
            app.Services.Configure(app.Configuration.GetSection("JwtTokenOptions"));
        }

    }
}

你可能感兴趣的:(ASP.NET Core 项目实战(JWT使用))