0

这是自定义身份验证的类,但它不会打印错误令牌密钥的消息(令牌密钥是每个用户的唯一字符串)=>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);
    }
4

1 回答 1

0

我只是重写了 CustAuthHandler 中的 HandleChallengeAsync 方法,当授权失败时,这个方法称为 Eveytime,所以我写回了一个字符串和 401 状态码到我的 http 请求的响应体,但验证失败了。

protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            
            await base.HandleChallengeAsync(properties);
            Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            string output = "authentification failed you don't have access to this content";
            await Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(output));
        
           
        }
于 2021-03-04T18:49:02.687 回答