3

I have an existing ASP.NET Core MVC application that I want to add a new API method in a controller. I want to touch the authentication/authorization code as little as possible, so I don't want to write a new authentication middleware for this one API.

The method is supposed to return some type of data if the user is anonoymous/unknown. And it should return more specific and potentially personal information if the user is signed in and has a valid user.

Is it safe to skip the [Authorize] attribute, and check only check the HttpContext.User (https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcontext.user?view=netframework-4.8) property for the username?

Can I assume that the signature has been verified by the OpenID Connect middleware?

// No Authorize attribute
public IActionResult MyApi()
{
    string userName = System.Security.Claims.Claim idClaim = this.HttpContext.User?.Claims?.FirstOrDefault(a => a.Type == "sub")?.Value;
    // Can I assume that the User object only is non-null if the OAuth signature is actually verified?
    // Or is fake-cookies possible?
}
1
  • 1
    If you want anonymous users access the the API then just use HttpContext.User.Identity.IsAuthenticated. That mean everybody! But if you need different kinds of authenticated users receive different kind of responses then I think you should use Policies. Aug 8, 2019 at 8:44

2 Answers 2

3

Authorization does not do anything in regards to authentification, it's only a mechanism to check whether the authenticated user has access to the requested resource. It's like a layer on top of authentication.

The presence of HttpContext.User does not necessarily indicate an authenticated user, but HttpContext.User.Identity.IsAuthenticated does. For ClaimsIdentity it basically just checks whether the field AuthenticationType is not empty.

Therefore, it's safe to assume the user is authenticated if it has AuthenticationType field set. It's also safe to assume that if the field Name is not empty as unauthenticated users can't have it set.

0
1

I use a custom extensions method to read the username from the current identity:

public static bool TryGetUserName(this IIdentity identity, out string username)
{
    try
    {
        username = Microsoft.AspNet.Identity.IdentityExtensions.GetUserName(identity);
        return true;
    }
    catch (ArgumentNullException ane)
    {
        username = null;
        return false;
    }
}

And I use this extension in my API method by calling:

bool isAuth = this.User?.Identity?.TryGetUserName(out username) ?? false;
1
  • Thanks for input!I have an extension method for this, but I copied out the code from it for this question to simplify it. Aug 8, 2019 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.