增加登录过期时间支持

This commit is contained in:
falcon 2023-01-04 16:04:59 +08:00
parent 956e3349fe
commit 785457a5f4
2 changed files with 23 additions and 10 deletions

View File

@ -1,17 +1,19 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Linq;
namespace Falcon.SugarApi.FalconClaim
{
/// <summary>
/// 自定义验证方式
/// </summary>
public class FalconAuthenticationHandler:IAuthenticationHandler
public class FalconAuthenticationHandler : IAuthenticationHandler
{
/// <summary>
/// 构造自定义身份验证方式
@ -35,23 +37,24 @@ namespace Falcon.SugarApi.FalconClaim
/// <inheritdoc />
public Task<AuthenticateResult> AuthenticateAsync() {
if(!this.Context.Request.Headers.TryGetValue(FalconClaimOption.FalconAuthenticationKey,out var val)) {
if (!this.Context.Request.Headers.TryGetValue(FalconClaimOption.FalconAuthenticationKey, out var val)) {
return UnLoginResultTask;
}
var token = val.ToString();
if(token.IsNullOrEmpty()) {
if (token.IsNullOrEmpty()) {
return UnLoginResultTask;
}
if(FalconClaimOption.TokenPrefix.IsNotNullOrEmpty() && !token.StartsWith(FalconClaimOption.TokenPrefix)) {
if (FalconClaimOption.TokenPrefix.IsNotNullOrEmpty() && !token.StartsWith(FalconClaimOption.TokenPrefix)) {
return UnLoginResultTask;
}
try {
var ticket = GetTicket(token);
if(ticket == null) {
if (ticket == null) {
return UnLoginResultTask;
}
return Task.FromResult(AuthenticateResult.Success(ticket));
} catch(Exception) {
}
catch (Exception) {
return UnLoginResultTask;
}
}
@ -69,7 +72,7 @@ namespace Falcon.SugarApi.FalconClaim
}
/// <inheritdoc />
public Task InitializeAsync(AuthenticationScheme scheme,HttpContext context) {
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) {
this.Scheme = scheme; this.Context = context;
return Task.CompletedTask;
}
@ -82,16 +85,22 @@ namespace Falcon.SugarApi.FalconClaim
List<Claim>? claims = null;
try {
claims = this.TokenBuilter.GetClaims(token);
} catch(Exception) {
}
catch (Exception) {
return null;
}
if(claims == null || claims.Count == 0) {
if (claims == null || claims.Count == 0) {
return null;
}
//检测是否设置过期时间
var dtExp = claims.Where(m => m.Type == ClaimTypes.Expiration);
if (dtExp.Any() && !DateTime.TryParse(dtExp.First().Value, out var et) && et > DateTime.Now) {
return null;
}
var cid = new ClaimsIdentity(FalconClaimOption.SchemeName);
cid.AddClaims(claims);
var principal = new ClaimsPrincipal(cid);
return new AuthenticationTicket(principal,this.Scheme.Name);
return new AuthenticationTicket(principal, this.Scheme.Name);
}
/// <summary>

View File

@ -14,5 +14,9 @@
/// 密码
/// </summary>
public string? Password { get; set; }
/// <summary>
/// 过期小时数。0或者空为不限制
/// </summary>
public int? ExpHours { get; set; }
}
}