这是自定义身份验证的类,但它不会打印错误令牌密钥的消息(令牌密钥是每个用户的唯一字符串)=>AuthenticateResult.Fail("Invalid Token Used for Authorisation") 它只是在邮递员中显示未经授权的 401 状态代码。
var valtoken = auth.getTokenDetails(token); 如果具有指定令牌的用户有权访问控制器的 get 方法,则该方法返回用户详细信息,否则返回 null。因此,对于空结果,我想返回未经授权的 401 状态代码以及获取 api 调用的自定义消息
namespace CustomAuthDemo
{
/*public class AuthenticationSchemeConstants
{
public const string BasicAuthScheme = "Basic";
}*/
public class BasicAuthSchemeOptions:AuthenticationSchemeOptions
{
}
public class CustAuthHandler : AuthenticationHandler<BasicAuthSchemeOptions>
{
private readonly ICustomAuthService auth;
public CustAuthHandler(IOptionsMonitor<BasicAuthSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
ICustomAuthService auth):base(options,logger,encoder,clock)
{
this.auth = auth;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
return AuthenticateResult.Fail("Unauthorised");
string authheader = Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authheader))
return AuthenticateResult.Fail("Unauthorised");
if(!authheader.StartsWith("bearer",StringComparison.OrdinalIgnoreCase))
return AuthenticateResult.Fail("Unauthorised");
string token = authheader.Substring("bearer".Length).Trim();
try
{
return ValidateToken(token);
}
catch(Exception ex)
{
Logger.LogInformation(ex.Message);
return AuthenticateResult.Fail("Unauthorised");
}
}
private AuthenticateResult ValidateToken(string token)
{
if (string.IsNullOrEmpty(token))
return AuthenticateResult.Fail("Unauthorised");
var valtoken = auth.getTokenDetails(token);
if (valtoken == null)
return AuthenticateResult.Fail("Invalid Token Used for Authorisation");
var claims = new List<Claim>
{ new Claim(ClaimTypes.Name,valtoken.username)};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new GenericPrincipal(identity, null);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}