Stack Undefined
Stack Undefined

Reputation: 1330

Authorization using JWT token in .net framework 4.7 app

I'm working with a .net framework 4.7 app hosted in IIS. The api needs to be secured with JWT token. Identity is provided by another server and clients will send the JWT as bearer token in the header. I like to use OWIN pipeline for authorization. Currently the app uses Global.asax for startup and I like to keep it as is. I just want OWIN for authorization using JWT. I will use the [Authorize] attribute on the controllers needing jwt authorization. IIS doesn't do any authorization at the moment.

I have this in the Startup.cs for Owin.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidAudience = ConfigHelper.GetAudience(),
                    ValidIssuer = ConfigHelper.GetIssuer(),
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true
                }
            });
    }
}
    

How do I call the Startup.Configure() from Global.asax so Owin pipeline handles the authorization for incoming requests.

Thanks

Upvotes: 0

Views: 5365

Answers (1)

Stack Undefined
Stack Undefined

Reputation: 1330

You can have both global.asax and OWIN startup in the same project. ASP.NET will first call the global.asax and hand the control over to OWIN's startup. Make sure you have the Microsoft.Owin.Host.SystemWeb package installed in the project. And you have a class with the name Startup and a method Configuration(IAppBuilder app). There are other ways to let OWIN know where it should start.

You should also be aware of the fact that in .NET framework, there is a manual process to retrieve the signing keys from the authority that issued the JWT token. Otherwise, you will get the mismatched key error. Once you get the keys, you will assign them to ValidSigningKeys property in TokenValidationParameters. Search SO for examples.

public class Startup
{
   public void Configuration(IAppBuilder app)
   {
      app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidAudience = ConfigHelper.GetAudience(),
                ValidIssuer = ConfigHelper.GetIssuer(),
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true
            }
        });
}

Upvotes: 1

Related Questions