Patrick Borkowicz
Patrick Borkowicz

Reputation: 1216

Testing if a request is anonymous or authenticated WebAPI 2 + Identity

I'm using WebAPI 2 + ASP.NET Identity

In one of my ApiController methods, I would like to test if a particular HTTP request is coming from an authenticated client or not (i.e. whether the request contains an authorization header or not).

The following works, but maybe there is a better way?

private AuthContext db = new AuthContext();

// GET api/Orders/
[AllowAnonymous]
public async Task<IHttpActionResult> GetOrder(int id)
{
    // ApplicationUser is an IdentityUser.
    ApplicationUser currentUser = null;

    try
    {
        UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        currentUser = await userManager.FindByNameAsync(User.Identity.GetUserName());
    }
    catch (Exception)
    {
    }

    if ( currentUser == null )
    {
        // Anonymous request.
        // etc...




    } else {
        // Authorized request.
        // etc...
    }
}

I am using the default routing template. Another option would be to route to 2 different methods for authorized requests and anonymous requests (decorated with appropriate data annotations).

Upvotes: 1

Views: 2572

Answers (1)

David Tansey
David Tansey

Reputation: 6023

In the ApiController class in WebApi there is a User property (which you are already making use of in your code: User.Identity.GetUserName()).

This User property is an IPrincipal instance which has a property Identity which is an instance of IIdentity.

Within the code of an ApiController method you can test whether the user for the current request is Authenticated by testing the IsAuthenticated property of User.Identity.

For example:

if ( User.Identity.IsAuthenticated)
{
    // Authenticated user...do something
}
else
{
   // anonymous..do something different
}

Upvotes: 7

Related Questions