Falcon.SugarApi/Falcon.SugarApi/JWT/IServiceCollectionExtend.cs

57 lines
2.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Falcon.SugarApi.Encryption;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
namespace Falcon.SugarApi.JWT
{
/// <summary>
/// 服务扩展
/// </summary>
public static class IServiceCollectionExtend
{
/// <summary>
/// 注册Falcon.SqlSugar.JWT
/// </summary>
/// <param name="services">服务集合</param>
/// <returns>服务集合</returns>
public static IServiceCollection AddFalconJWT(this IServiceCollection services)
=> services.AddFalconJWT(null);
/// <summary>
/// 注册Falcon.SqlSugar.JWT.JwtContext并配置相关参数
/// <para>消费端通过JwtContext注入</para>
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="OptionBuilder">参数创建器</param>
/// <returns>服务集合</returns>
public static IServiceCollection AddFalconJWT(this IServiceCollection services, Action<JwtContext>? OptionBuilder) {
services.AddSingleton<JwtContext>(sp => {
var option = new JwtContext();
var jtb = sp.GetService<IJwtTokenBuilder>();
if (jtb == null) {
var aesc = sp.GetService<AESConfig>() ?? new AESConfig();
jtb = new AESTokenbuilder(aesc, option);
}
option.JwtTokenBuilder = jtb;
var ulj = sp.GetService<IUserLogin>();
if (ulj != null) {
option.UserLogin = ulj;
}
OptionBuilder?.Invoke(option);
if (option.UserLogin == null) {
throw new Exception("必须为JwtOptions提供UserLogin属性");
}
if (option.JwtTokenBuilder == null) {
throw new Exception("必须为JwtOptions提供JwtTokenBuilder属性");
}
return option;
});
return services;
}
}
}