Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add token authentication for webApi controller to existing asp.net MVC 5 application

I currently have a Web API controller added to an existing MVC 5 project (not using .net core) and I was able to successfully create and get data from the controller that I have set up. The purpose of the API is to pass data between it and a mobile application that uses the same data source that the MVC project uses (I will also be calling existing methods in the project from the API so I would prefer the API exist in the MVC project). I am now looking for a way to add token authentication to the API, as I only want logged in users in the mobile application to be allowed to access the API. How can I achieve this?

like image 896
Christian Chavez Avatar asked Jul 02 '18 19:07

Christian Chavez


1 Answers

The simplest solution should be to use the Token Validation Middleware from the IdentityServer 3 suite.
Just add the nuget package and configure your application following the doc:

public class Startup
{
  public void Configuration(IAppBuilder app)
  {
    // turn off any default mapping on the JWT handler
    JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

    app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = "https://localhost:44333/core",
            RequiredScopes = new[] { "api1" }
        });

    app.UseWebApi(WebApiConfig.Register());
  }
}

It's ok to set
app.UseIdentityServerBearerTokenAuthentication() only
prior to
app.UseCookieAuthentication() and app.UseOpenIdConnectAuthentication()
and call
GlobalConfiguration.Configure(WebApiConfig.Register) in Global.asax
Such approach allows to combine token and cookie-based auth in one MVC application.
The only problem for today is that IdentityServer 3 family tools are frozen and support System.IdentityModel 4 and OWIN 3 only, so

update: The preferred solution for ASP.NET 4.6+ becomes IdentityServer3.Contrib.AccessTokenValidation -- a fork, refactored according to the recent framework changes.

like image 96
d_f Avatar answered Sep 22 '22 13:09

d_f