public async Task <StatusResult <string> > UserLogin(LoginInputDto dto) { var result = await _accountService.LoginAsync(dto); #region 添加登录日志 #endregion if (!result.IsSuccess) { return(new StatusResult <string>(result.Message)); } // 生成 token var accessToken = JWTEncryption.Encrypt(new Dictionary <string, object>() { { ClaimConst.USERID, result.Data.Id }, // 存储Id { ClaimConst.USERNAME, result.Data.UserName }, // 存储用户名 { ClaimConst.USERNICKNAME, result.Data.NickName }, { ClaimConst.QINGSHANUSERISSUPER, result.Data.IsSuper }, }); return(new StatusResult <string>() { Data = "Bearer " + accessToken }); }
/// <summary> /// 重写 Handler 添加自动刷新收取逻辑 /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task HandleAsync(AuthorizationHandlerContext context) { string url = context.GetCurrentHttpContext().Request.GetRefererUrlAddress(); if (url.Contains("xx.com")) //if (url.Contains("localhost")) { var isAuthenticated = context.User.Identity.IsAuthenticated; var pendingRequirements = context.PendingRequirements; foreach (var requirement in pendingRequirements) { // 授权成功 context.Succeed(requirement); } } else { // 自动刷新 token if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext())) { await AuthorizeHandleAsync(context); } else { context.Fail(); // 授权失败 } } }
public LoginOutput Login(LoginInput input) { // 验证用户名和密码 var user = _userRepository.FirstOrDefault(u => u.Account.Equals(input.Account) && u.Password.Equals(input.Password), false) ?? throw Oops.Oh(1000); var output = user.Adapt <LoginOutput>(); // 生成 token var jwtSettings = App.GetOptions <JWTSettingsOptions>(); var datetimeOffset = DateTimeOffset.UtcNow; output.AccessToken = JWTEncryption.Encrypt(jwtSettings.IssuerSigningKey, new Dictionary <string, object>() { { "UserId", user.Id }, // 存储Id { "Account", user.Account }, // 存储用户名 { JwtRegisteredClaimNames.Iat, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Nbf, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddSeconds(jwtSettings.ExpiredTime.Value * 60).ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Iss, jwtSettings.ValidIssuer }, { JwtRegisteredClaimNames.Aud, jwtSettings.ValidAudience } }); // 设置 Swagger 刷新自动授权 _httpContextAccessor.SigninToSwagger(output.AccessToken); return(output); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="authenticationBuilder"></param> /// <param name="tokenValidationParameters">token 验证参数</param> /// <param name="jwtBearerConfigure"></param> /// <param name="enableGlobalAuthorize">启动全局授权</param> /// <returns></returns> public static AuthenticationBuilder AddJwt(this AuthenticationBuilder authenticationBuilder, object tokenValidationParameters = default, Action <JwtBearerOptions> jwtBearerConfigure = null, bool enableGlobalAuthorize = false) { // 获取框架上下文 _ = JWTEncryption.GetFrameworkContext(Assembly.GetCallingAssembly()); // 配置 JWT 选项 ConfigureJWTOptions(authenticationBuilder.Services); // 添加授权 authenticationBuilder.AddJwtBearer(options => { // 反射获取全局配置 var jwtSettings = JWTEncryption.FrameworkApp.GetMethod("GetOptions").MakeGenericMethod(typeof(JWTSettingsOptions)).Invoke(null, new object[] { null }) as JWTSettingsOptions; // 配置 JWT 验证信息 options.TokenValidationParameters = (tokenValidationParameters as TokenValidationParameters) ?? JWTEncryption.CreateTokenValidationParameters(jwtSettings); // 添加自定义配置 jwtBearerConfigure?.Invoke(options); }); //启用全局授权 if (enableGlobalAuthorize) { authenticationBuilder.Services.Configure <MvcOptions>(options => { options.Filters.Add(new AuthorizeFilter()); }); } return(authenticationBuilder); }
public async Task <LoginOutput> LoginAsync([FromServices] IHttpContextAccessor httpContextAccessor, [Required] LoginInput input) { // 获取加密后的密码 var encryptPassword = MD5Encryption.Encrypt(input.Password.Trim()); // 判断用户名或密码是否正确 var user = await _userRepository.FirstOrDefaultAsync(u => u.Account.Equals(input.Account) && u.Password.Equals(encryptPassword)); _ = user ?? throw Oops.Oh(SystemErrorCodes.u1000); // 更新登录时间 user.SigninedTime = DateTimeOffset.Now; // 映射结果 var output = user.Adapt <LoginOutput>(); // 生成 token var accessToken = output.AccessToken = JWTEncryption.Encrypt(new Dictionary <string, object> { { "UserId", user.Id }, { "Account", user.Account } }); // 生成 刷新token var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken); // 设置 Swagger 自动登录 httpContextAccessor.SigninToSwagger(accessToken); // 设置刷新 token httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken; return(output); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="services"></param> private static void ConfigureJWTOptions(IServiceCollection services) { // 配置验证 services.AddOptions <JWTSettingsOptions>() .BindConfiguration("JWTSettings") .ValidateDataAnnotations() .PostConfigure(options => { _ = JWTEncryption.SetDefaultJwtSettings(options); }); }
private JsonWebToken ReadToken() { // 获取 token var accessToken = _httpContextAccessor.GetJwtToken() ?? throw Oops.Oh(1001); // 验证token var(IsValid, Token) = JWTEncryption.Validate(accessToken, _jwtSettings); if (!IsValid) { throw Oops.Oh(1001); } return(Token); }
public async Task <(string, string)> LoginAsync(AdminUserLoginCommand command) { var user = await bus.SendCommand(command); // 生成 token var accessToken = JWTEncryption.Encrypt(new Dictionary <string, object> { { userId, user.Id }, { userName, user.UserName } }); // 生成 刷新token var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken); return(accessToken, refreshToken); }
/// <summary> /// 验证 Jwt 授权 /// </summary> /// <param name="context"></param> /// <param name="httpContext"></param> /// <param name="token"></param> /// <returns></returns> public static bool ValidateJwtBearer(this AuthorizationHandlerContext context, HttpContext httpContext, out JsonWebToken token) { // 获取 token var accessToken = httpContext.GetJwtToken(); if (string.IsNullOrEmpty(accessToken)) { token = null; return(false); } // 验证token var(IsValid, Token) = JWTEncryption.Validate(accessToken, httpContext.RequestServices.GetService <IOptions <JWTSettingsOptions> >().Value); token = IsValid ? Token : null; return(IsValid); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddJWTAuthorization(this IServiceCollection services) { // 注册 JWT 配置 services.AddConfigurableOptions <JWTSettingsOptions>(); // 添加默认授权 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = JWTEncryption.CreateTokenValidationParameters(App.GetOptions <JWTSettingsOptions>()); }); return(services); }
public LoginOutput Login(LoginInput input) { // 验证用户名和密码 var user = _userRepository.FirstOrDefault(u => u.Account.Equals(input.Account) && u.Password.Equals(input.Password), false) ?? throw Oops.Oh(1000); var output = user.Adapt <LoginOutput>(); output.AccessToken = JWTEncryption.Encrypt(new Dictionary <string, object>() { { "UserId", user.Id }, // 存储Id { "Account", user.Account }, // 存储用户名 }); // 设置 Swagger 刷新自动授权 _httpContextAccessor.SigninToSwagger(output.AccessToken); return(output); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="services"></param> private static void ConfigureJWTOptions(IServiceCollection services) { // 获取配置节点 var jwtSettingsConfiguration = services.BuildServiceProvider() .GetService <IConfiguration>() .GetSection("JWTSettings"); // 配置验证 services.AddOptions <JWTSettingsOptions>() .Bind(jwtSettingsConfiguration) .ValidateDataAnnotations(); // 选项后期配置 services.PostConfigure <JWTSettingsOptions>(options => { _ = JWTEncryption.SetDefaultJwtSettings(options); }); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <typeparam name="TAuthorizationHandler"></typeparam> /// <param name="services"></param> /// <param name="authenticationConfigure"></param> /// <param name="tokenValidationParameters"></param> /// <param name="jwtBearerConfigure"></param> /// <param name="enableGlobalAuthorize"></param> /// <returns></returns> public static AuthenticationBuilder AddJwt <TAuthorizationHandler>(this IServiceCollection services, Action <AuthenticationOptions> authenticationConfigure = null, object tokenValidationParameters = default, Action <JwtBearerOptions> jwtBearerConfigure = null, bool enableGlobalAuthorize = false) where TAuthorizationHandler : class, IAuthorizationHandler { // 植入 Furion 框架 var furionAssembly = JWTEncryption.GetFrameworkContext(Assembly.GetCallingAssembly()); // 获取添加授权类型 var authorizationServiceCollectionExtensionsType = furionAssembly.GetType("Microsoft.Extensions.DependencyInjection.AuthorizationServiceCollectionExtensions"); var addAppAuthorizationMethod = authorizationServiceCollectionExtensionsType .GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(u => u.Name == "AddAppAuthorization" && u.IsGenericMethod && u.GetParameters().Length > 0 && u.GetParameters()[0].ParameterType == typeof(IServiceCollection)).First(); // 添加策略授权服务 addAppAuthorizationMethod.MakeGenericMethod(typeof(TAuthorizationHandler)).Invoke(null, new object[] { services, null, enableGlobalAuthorize }); // 添加授权 return(services.AddJwt(authenticationConfigure, tokenValidationParameters, jwtBearerConfigure)); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="services"></param> /// <param name="authenticationConfigure">授权配置</param> /// <param name="tokenValidationParameters">token 验证参数</param> /// <param name="jwtBearerConfigure"></param> /// <returns></returns> public static AuthenticationBuilder AddJwt(this IServiceCollection services, Action <AuthenticationOptions> authenticationConfigure = null, object tokenValidationParameters = default, Action <JwtBearerOptions> jwtBearerConfigure = null) { // 获取框架上下文 _ = JWTEncryption.GetFrameworkContext(Assembly.GetCallingAssembly()); // 添加默认授权 var authenticationBuilder = services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; // 添加自定义配置 authenticationConfigure?.Invoke(options); }); AddJwt(authenticationBuilder, tokenValidationParameters, jwtBearerConfigure); return(authenticationBuilder); }
/// <summary> /// 重写 Handler 添加自动刷新 /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task HandleAsync(AuthorizationHandlerContext context) { // 自动刷新Token if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext(), App.GetOptions <JWTSettingsOptions>().ExpiredTime, App.GetOptions <RefreshTokenSettingOptions>().ExpiredTime)) { await AuthorizeHandleAsync(context); } else { context.Fail(); // 授权失败 DefaultHttpContext currentHttpContext = context.GetCurrentHttpContext(); if (currentHttpContext == null) { return; } currentHttpContext.SignoutToSwagger(); } }
/// <summary> /// 请求管道 /// </summary> /// <param name="context"></param> /// <param name="httpContext"></param> /// <returns></returns> public override bool Pipeline(AuthorizationHandlerContext context, DefaultHttpContext httpContext) { // 获取 token var accessToken = httpContext.GetJWTToken(); if (string.IsNullOrEmpty(accessToken)) { return(false); } // 验证token var(IsValid, _) = JWTEncryption.Validate(accessToken, App.GetOptions <JWTSettingsOptions>()); if (!IsValid) { return(false); } // 检查权限 return(CheckAuthorzie(httpContext)); }
public string GetToken() { var jwtSettings = App.GetOptions <JWTSettingsOptions>(); var datetimeOffset = new DateTimeOffset(DateTime.Now); var token = JWTEncryption.Encrypt(jwtSettings.IssuerSigningKey, new JObject() { { JwtRegisteredClaimNames.UniqueName, 1 }, { JwtRegisteredClaimNames.NameId, "百小僧" }, { JwtRegisteredClaimNames.Iat, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Nbf, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddSeconds(jwtSettings.ExpiredTime.Value * 60)).ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Iss, jwtSettings.ValidIssuer }, { JwtRegisteredClaimNames.Aud, jwtSettings.ValidAudience } }); // 设置 Swagger 刷新自动授权 _httpContextAccessor.HttpContext.Response.Headers["access-token"] = token; return(token); }
public async Task <(string, string)> LoginAsync(AdminUserLoginCommand command, CancellationToken cancellationToken = default) { var user = await adminUserService.LoginAsync(command, cancellationToken); // 生成 token var accessToken = JWTEncryption.Encrypt(new Dictionary <string, object> { { userId, user.Id }, { userName, user.UserName } }); // 生成 刷新token var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken); // 设置 Swagger 自动登录 Web.HttpContext.SigninToSwagger(accessToken); // 设置刷新 token Web.HttpContext.Response.Headers["x-access-token"] = refreshToken; return(accessToken, refreshToken); }
public LoginResponseDto Login([FromServices] IHttpContextAccessor httpContextAccessor, [FromBody] LoginRequestDto dto) { var user = _sysUserSerivce.Login(dto.Account, dto.Password); if (user == null) { throw Oops.Oh("用户名或者密码错误"); } var response = user.Adapt <LoginResponseDto>(); // 生成 token response.AccessToken = JWTEncryption.Encrypt(new Dictionary <string, object> { { "UserId", user.UserId }, { "UserName", user.UserName }, { "Account", user.UserName } }); response.ExipreTime = DateTimeOffset.Now.AddMinutes(20).DateTime; // 设置 Swagger 自动登录 httpContextAccessor.SigninToSwagger(response.AccessToken); return(response); }
public async Task <LoginAdminOutput> PostLogin(LoginAdminInput loginAdminInput) { var admin = await _manageService.LoginAdmin(loginAdminInput.Adapt <AdminDto>()); var output = admin.Adapt <LoginAdminOutput>(); // 生成 token var jwtSettings = App.GetOptions <JWTSettingsOptions>(); var datetimeOffset = new DateTimeOffset(DateTime.Now); if (jwtSettings.ExpiredTime != null) { output.AccessToken = JWTEncryption.Encrypt(jwtSettings.IssuerSigningKey, new Dictionary <string, object>() { { "UserId", admin.Id }, // 存储Id { "IsAdmin", true }, // 管理员登录 { JwtRegisteredClaimNames.Iat, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Nbf, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Exp, new DateTimeOffset( DateTime.Now.AddSeconds( jwtSettings.ExpiredTime.Value * 60 * 60 * 24 * 30)) .ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Iss, jwtSettings.ValidIssuer }, { JwtRegisteredClaimNames.Aud, jwtSettings.ValidAudience } }); } // 设置 Swagger 刷新自动授权 if (_httpContextAccessor.HttpContext != null) { _httpContextAccessor.HttpContext.Response.Headers["access-token"] = output.AccessToken; } return(output); }
public async Task <LoginOutput> PostLogin(LoginInput loginInput) { var student = await _studentService.LoginStudent(loginInput.StudentNo, loginInput.Password); var output = student.Adapt <LoginOutput>(); // 生成 token var jwtSettings = App.GetOptions <JWTSettingsOptions>(); var datetimeOffset = new DateTimeOffset(DateTime.Now); output.AccessToken = JWTEncryption.Encrypt(jwtSettings.IssuerSigningKey, new Dictionary <string, object>() { { "UserId", student.Id }, // 存储Id { JwtRegisteredClaimNames.Iat, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Nbf, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddSeconds(jwtSettings.ExpiredTime.Value * 60 * 60 * 24 * 30)).ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Iss, jwtSettings.ValidIssuer }, { JwtRegisteredClaimNames.Aud, jwtSettings.ValidAudience } }); // 设置 Swagger 刷新自动授权 _httpContextAccessor.HttpContext.Response.Headers["access-token"] = output.AccessToken; return(output); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="authenticationBuilder"></param> /// <param name="tokenValidationParameters">token 验证参数</param> /// <param name="jwtBearerConfigure"></param> /// <param name="enableGlobalAuthorize">启动全局授权</param> /// <returns></returns> public static AuthenticationBuilder AddJwt(this AuthenticationBuilder authenticationBuilder, object tokenValidationParameters = default, Action <JwtBearerOptions> jwtBearerConfigure = null, bool enableGlobalAuthorize = false) { var services = authenticationBuilder.Services; // 配置 JWT 选项 ConfigureJWTOptions(services); // 获取配置选项 var jwtSettings = App.GetDefultOptions <JWTSettingsOptions>(); // 添加授权 authenticationBuilder.AddJwtBearer(options => { options.TokenValidationParameters = (tokenValidationParameters as TokenValidationParameters) ?? JWTEncryption.CreateTokenValidationParameters(jwtSettings); // 添加自定义配置 jwtBearerConfigure?.Invoke(options); }); //启用全局授权 if (enableGlobalAuthorize) { services.Configure <MvcOptions>(options => { options.Filters.Add(new AuthorizeFilter()); }); } return(authenticationBuilder); }
public async Task <(string, string)> LoginAsync(AdminUserLoginCommand request, CancellationToken cancellationToken = default) { var user = default(AdminUserEntity); request.Password = Encrypt.Md5By32(request.Password); var loginWay = ""; if (!Valid.IsMobileNumberSimple(request.Account)) { user = await db.Context.AdminUser.Where(c => c.UserName.Equals(request.Account)).FirstOrDefaultAsync(cancellationToken); if (user == null) { Failure.Error("账号不存在"); } loginWay = "Mobile"; } else { user = await db.Context.AdminUser.Where(c => c.Mobile.Equals(request.Account)).FirstOrDefaultAsync(cancellationToken); if (user == null) { Failure.Error("手机号码不存在"); } loginWay = "UserName"; } if (!user.Password.Equals(request.Password)) { Failure.Error("密码错误"); } if (user.Status != Status.Show) { Failure.Error("您的帐号禁止登录,请与管理员联系!"); } user.LoginCount += 1; user.LoginLastTime = DateTime.Now; user.LoginLastIp = Web.IP; user.LoginRecords.Add(new LoginRecordEntity { AdminId = user.Id, LoginIp = user.LoginLastIp, LoginTime = user.LoginLastTime, LoginWay = loginWay }); db.Update(user); // 生成 token var accessToken = JWTEncryption.Encrypt(new Dictionary <string, object> { { userId, user.Id }, { userName, user.UserName } }); // 生成 刷新token var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken); // 设置 Swagger 自动登录 Web.HttpContext.SigninToSwagger(accessToken); // 设置刷新 token Web.HttpContext.Response.Headers["x-access-token"] = refreshToken; return(accessToken, refreshToken); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="authenticationBuilder"></param> /// <param name="tokenValidationParameters">token 验证参数</param> /// <returns></returns> public static AuthenticationBuilder AddJwt(this AuthenticationBuilder authenticationBuilder, object tokenValidationParameters = default) { var services = authenticationBuilder.Services; // 配置 JWT 选项 ConfigureJWTOptions(services); var jwtSettings = services.BuildServiceProvider().GetService <IOptions <JWTSettingsOptions> >().Value; authenticationBuilder.AddJwtBearer(options => { options.TokenValidationParameters = (tokenValidationParameters as TokenValidationParameters) ?? JWTEncryption.CreateTokenValidationParameters(jwtSettings); }); return(authenticationBuilder); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="authenticationBuilder"></param> /// <param name="tokenValidationParameters">token 验证参数</param> /// <param name="enableGlobalAuthorize">启动全局授权</param> /// <returns></returns> public static AuthenticationBuilder AddJwt(this AuthenticationBuilder authenticationBuilder, object tokenValidationParameters = default, bool enableGlobalAuthorize = false) { var services = authenticationBuilder.Services; // 配置 JWT 选项 ConfigureJWTOptions(services); var jwtSettings = services.BuildServiceProvider().GetService <IOptions <JWTSettingsOptions> >().Value; authenticationBuilder.AddJwtBearer(options => { options.TokenValidationParameters = (tokenValidationParameters as TokenValidationParameters) ?? JWTEncryption.CreateTokenValidationParameters(jwtSettings); }); //启用全局授权 if (enableGlobalAuthorize) { services.Configure <MvcOptions>(options => { options.Filters.Add(new AuthorizeFilter()); }); } return(authenticationBuilder); }
/// <summary> /// 添加 JWT 授权 /// </summary> /// <param name="services"></param> /// <param name="configureOptions">授权配置</param> /// <param name="tokenValidationParameters">token 验证参数</param> /// <returns></returns> public static AuthenticationBuilder AddJwt(this IServiceCollection services, Action <AuthenticationOptions> configureOptions = null, object tokenValidationParameters = default) { // 配置 JWT 选项 ConfigureJWTOptions(services); var jwtSettings = services.BuildServiceProvider().GetService <IOptions <JWTSettingsOptions> >().Value; // 添加默认授权 return(services.AddAuthentication(options => { if (configureOptions == null) { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; } else { configureOptions.Invoke(options); } }).AddJwtBearer(options => { options.TokenValidationParameters = (tokenValidationParameters as TokenValidationParameters) ?? JWTEncryption.CreateTokenValidationParameters(jwtSettings); })); }
public async Task <TData <OperatorInfo> > Login([FromForm] string userName, [FromForm] string password) { var obj = new TData <OperatorInfo>(); var userObj = await _userBLL.CheckLogin(userName, password); if (userObj.Tag == 1) { await _userBLL.UpdateLoginInfo(userObj.Data); await _operatorCache.AddCurrent(userObj.Data.ApiToken); obj.Data = await _operatorCache.Current(userObj.Data.ApiToken); } obj.Message = userObj.Message; var ip = NetHelper.Ip; var browser = NetHelper.Browser; var os = NetHelper.GetOSVersion(); var userAgent = NetHelper.UserAgent; var logLoginEntity = new LogLoginEntity { LogStatus = userObj.Tag == 1 ? OperateStatusEnum.Success.ParseToInt() : OperateStatusEnum.Fail.ParseToInt(), Remark = userObj.Message, IpAddress = ip, IpLocation = IpLocationHelper.GetIpLocation(ip), Browser = browser, OS = os, ExtraRemark = userAgent, CreatorId = userObj.Data == null ? 0 : userObj.Data.Id, CreateTime = DateTime.Now }; await _logLoginBLL.SaveForm(logLoginEntity); if (userObj.Tag == 0) { return(obj); } // 生成前端的token // 生成 token var jwtSettings = App.GetOptions <JWTSettingsOptions>(); var datetimeOffset = DateTimeOffset.UtcNow; var accessToken = JWTEncryption.Encrypt(jwtSettings.IssuerSigningKey, new Dictionary <string, object> { { "UserId", userObj.Data.Id.ToString() }, // 存储Id { "Account", userObj.Data.UserName }, // 存储用户名 { "ApiToken", userObj.Data.ApiToken }, // ApiToken { JwtRegisteredClaimNames.Iat, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Nbf, datetimeOffset.ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddSeconds(jwtSettings.ExpiredTime.Value * 60).ToUnixTimeSeconds() }, { JwtRegisteredClaimNames.Iss, jwtSettings.ValidIssuer }, { JwtRegisteredClaimNames.Aud, jwtSettings.ValidAudience } }); // 覆盖apitoken,因为前端需要的是jwt生成的token,而缓存使用的是数据库的apitoken字段 obj.Data.JwtToken = accessToken; obj.Tag = userObj.Tag; var claims = new List <Claim> { new Claim(ClaimTypes.Name, userObj.Data.UserName), new Claim("ApiToken", userObj.Data.ApiToken), }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties(); await NetHelper.HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return(obj); }