Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core WebAPI Cookie + JWT Authentication

we have a SPA (Angular) with API backend (ASP.NET Core WebAPI):

SPA is listens on app.mydomain.com, API on app.mydomain.com/API

We use JWT for Authentication with built-in Microsoft.AspNetCore.Authentication.JwtBearer; I have a controller app.mydomain.com/API/auth/jwt/login which creates tokens. SPA saves them into local storage. All works perfect. After a security audit, we have been told to switch local storage for cookies.

The problem is, that API on app.mydomain.com/API is used by SPA but also by a mobile app and several customers server-2-server solutions.

So, we have to keep JWT as is, but add Cookies. I found several articles which combines Cookies and JWT on different controllers, but I need them work side-by-side on each controller.

If client sends cookies, authenticate via cookies. If client sends JWT bearer, authenticate via JWT.

Is this achievable via built-in ASP.NET authentication or DIY middleware?

Thanks!

like image 779
Luke1988 Avatar asked Mar 23 '18 18:03

Luke1988


People also ask

Can I use JWT with cookies?

On every request to server, the JWT will be read from Cookies and added in the Authorization header using Bearer scheme. The server can then verify the JWT in the request header (as opposed to reading it from the cookies).

What is JWT authentication in ASP NET core?

JWT authentication is a standard way for protecting APIs - it's adept at verifying the data that's transmitted over the wire between APIs and the clients that consume the APIs. You can even safely pass claims between the communicating parties as well.


1 Answers

Okay, I have been trying achieving this for a while and i solved same issue of using jwt Authentication Tokens and Cookie Authentication with the following code.

API Service Provider UserController.cs

This Provide Different Services to the User with Both (Cookie and JWT Bearer)Authentication Schemes

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]  [Route("[controller]")] [ApiController] public class UsersController : ControllerBase {      private readonly IUserServices_Api _services;     public UsersController(IUserServices_Api services)     {         this._services = services;     }           [HttpGet]     public IEnumerable<User> Getall()     {         return _services.GetAll();     } } 

My Startup.cs

public void ConfigureServices(IServiceCollection services)     {                    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);                   services.AddAuthentication(options => {             options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;             options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;             options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;             options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;         })             .AddCookie(options =>             {                 options.LoginPath = "/Account/Login";                 options.AccessDeniedPath = "/Home/Error";             })             .AddJwtBearer(options =>             {                 options.SaveToken = true;                 options.RequireHttpsMetadata = false;                 options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()                 {                     ValidateIssuer = true,                     ValidateAudience = true,                     ValidAudience = " you site link blah blah",                     ValidIssuer = "You Site link Blah  blah",                     IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(sysController.GetSecurityKey()))                     ,                     ValidateLifetime = true,                     ClockSkew = TimeSpan.Zero                 };             });      } 

And further if you want custom Authentication for a specific Controller then you have to specify the Authentitcation Type for the Authorization like:

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] public IActionResult Index() {     return View();    // This can only be Access when Cookie Authentication is Authorized. }  [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public IActionResult Index() {     return View();    // And this one will be Access when JWT Bearer is Valid } 
like image 171
Sayed Muhammad Idrees Avatar answered Sep 21 '22 12:09

Sayed Muhammad Idrees