'Get claim from request body

I'm trying to add an own AuthN scheme to ASP.NET Core app (.NET6). Let's say some application has its own secret key. I need to generate JWT only for authenticated applications.

So, an app makes the request:

Headers
   Authorization XDNJADJSSLlkso87D==

POST /application/token
{
   "applicationId": "some app id"
}

The backend first need to validate the secret key, if ok then add the value of applicationId to the Claims.

public class InitialSecretAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.ContainsKey(HeaderNames.Authorization)
            || string.IsNullOrEmpty(Request.Headers[HeaderNames.Authorization]))
        {
            return Task.FromResult(AuthenticateResult.Fail("Authorization header is not found or empty"));
        }

        if (Request.Headers[HeaderNames.Authorization] != secretKey)
        {
            return Task.FromResult(AuthenticateResult.Fail("Authorization header is not valid"));
        }

        AuthenticationTicket ticket = GetAuthenticationTicket();
        return Task.FromResult(AuthenticateResult.Success(ticket));
    }

    private AuthenticationTicket GetAuthenticationTicket()
    {
        Claim[] claims = { "applicationId", // GET ApplicationId from the request body };

        var identity = new ClaimsIdentity(claims, Scheme.Name);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);

        return ticket;
    }
}

Should I use StreamReader to read the request body or it is not efficient way (because it was done here and later before deserealization by framework)? Or maybe I'm completely wrong with the implementation? Could you please advice



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source