-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Produce 403 from custom AuthenticationHandler.HandleAuthenticateAsync
#61323
Unanswered
maxkoshevoi
asked this question in
Q&A
-
I'm writing a custom authentication handler since the token I have is not standard. I've added my token validation logic to HandleAuthenticateAsync and return AuthenticateResult.Fail("[reason]") when some part of validation fails.
The token has Aud claim that stores audience, and I want to fail with 403 if token is valid, but audience isn't.
The only way I was able to do that is like this:
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { // ... var tokenAudience = ticket.Principal.Claims.Single(c => c.Type == "Aud"); if (tokenAudience.Value != oAuthConfig.Value.Audience) { Context.Items[nameof(HttpStatusCode)] = (int)HttpStatusCode.Forbidden; return AuthenticateResult.Fail("Incorrect audience"); } return AuthenticateResult.Success(ticket); } protected override async Task HandleChallengeAsync(AuthenticationProperties properties) { if (!Context.Items.TryGetValue(nameof(HttpStatusCode), out object? statusCode)) { return base.HandleChallengeAsync(properties); } Response.StatusCode = (int)statusCode!; return Task.CompleteTask; }
- Why I cannot pass
AuthenticationProperties? I can specify them inAuthenticateResult.Fail, but they come out empty inHandleChallengeAsync
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { // ... return AuthenticateResult.Fail(failureMessage, new AuthenticationProperties { { nameof(HttpStatusCode), HttpStatusCode.Forbidden } }); } protected override async Task HandleChallengeAsync(AuthenticationProperties properties) {} // properties are empty
- Why it's not possible to generate authorization failure from
HandleAuthenticateAsync? I know the name of the method suggests we should only do authentication there, but we still need to fail it in order to get toHandleChallengeAsyncwhich is also not correct since authentication was successful, it's the authorization that's failed
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment