Supporting JWT and Cookie based Auth scheme in one .Net Core Web API

Nitesh Singhal
2 min readSep 10, 2021

--

When I have introduced OpenIDConnect and OAuth for securing swagger UI(read more), I had to use default scheme as cookie and because of this, API access also was changed to cookie authentication but I want to use JWT bearer authentication scheme to access the API’s, so I need to support both JWT based authentication scheme and cookie based authentication scheme in my webapi project.

In this tutorial, I am going to show how can we achieve both authentication in same webapi project.

Let’s start by making changes in Startup.cs’s ConfigureServices method.

look at the below code.

I am creating a custom policy and forwarding the required scheme based on path.

Now at controller we have to specify the authentication scheme used. in this case it is JwtBearer.

Let’s run the application.

For IdentityProvider, I am using keycloak as mentioned in previous article.

For accessing the swagger UI it is redirected to keycloak for authentication, once we authenticated successfully it is redirected back to swagger UI.

Now we can see swagger UI and try to access the API.

Swagger UI
Access API via swagger

We see 401 unauthorized status,

Now we try to get JWT token using postman and use that token with swagger UI.

Postman
Success API call with Swagger UI

Summary

Implementing multiple authentication scheme is easy and can be useful in the scenario where it is required to support different authentication scheme.

Hope it is helpful.

Thanks for reading..!

If you liked this article please share the energy and press the clap button And follow me for more interesting articles like this one.

--

--

Nitesh Singhal

Software architect, Exploring ASP.Net core and containerization technologies