Aninda Sen
Aninda Sen

Reputation: 63

Multiple authentication mechanisms in the same webapi controller

We have vendors (and in house consumers) some of who do basic authentication with us and some do jwt token auth when consuming our API. We have our controller annotated with either basic auth filter or token auth filter. Is there a way to combine both these authentication methods in the same controller depending on which method is being called? We can ofcourse annotate each method with basic or token auth filters instead of anotating the class but I was wondering whether there was a better way of doing it?

Upvotes: 2

Views: 4058

Answers (1)

Wokuo
Wokuo

Reputation: 206

This can be done with Owin. In Startup.cs file you can add something like that:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        var oAuthOptions = new OAuthBearerAuthenticationOptions
        {
            // your jwt settings
        };

        app.UseOAuthBearerAuthentication(oAuthOptions);

        app.Use(typeof(BasicAuthenticationMiddleWare)); // basic auth middleware           
    }
}

Unluckily Owin doesn't support basic auth by default, you have to write your own middleware for that:

public class BasicAuthenticationMiddleWare : OwinMiddleware
{
    public BasicAuthenticationMiddleWare(OwinMiddleware next) : base(next) { }

    public override Task Invoke(IOwinContext context)
    {
        throw new NotImplementedException();
    }
}

For information about basic middleware you will find here: https://lbadri.wordpress.com/2013/07/13/basic-authentication-with-asp-net-web-api-using-owin-middleware/

About how to configure jwt for owin you will find more details in google. Without details about your jwt vendor I cannot help you with configuration.

When you configure jwt and basic auth you simply add [Authorize] attribute to your controllers or methods:

[Authorize]
public class AccountController : ApiController
{

}

Owin will do the rest of work to define which auth method was used to authorize request.

If you are not using jwt as bearer tokens please use UseOAuthAuthorizationServer instead of UseOAuthBearerAuthentication.

Also using Owin you can add other vendors like Google, Microsoft, Facebook and others.

Upvotes: 2

Related Questions