Search code examples
c#asp.net-mvcangularidentityserver4

Serving angular with razor to achieve cookie based authentication


I'm starting a new project with Angular 7, Asp.net core 2, Asp.net Identity, IdentityServer4.

Briefly, my project architecture is like the following:

  • A web API project (resource server)
  • Data access layer project (c# project library)
  • Identity server 4 using Asp identity
  • And one Angular 7 client, this project is generated using two cli commands : "dotnet new angular", to generate the backend. And "ng new" to generate the front end code.

So, since angular project has a back-end, I have chosen the hybrid flow for security reasons.

My goal is to authenticate an angular client user with cookies, using angular client back-end. I have easily made this work using an MVC client but I still couldn't figure out how to achieve the same thing with an angular client.

My current idea is to serve angular using two actions, one that renders a razor cshtml page for anonymous users, and another one for "authorized" users, but I'm still not sure if this is achievable or not.

Is it a good approach or is there a better way?


Solution

  • I've started a similar project recently and contemplated how to approach authentication/authorization.

    Ended up treating the Angular front end the AspNetCore back end as two similar projects (even though they were under the same project). You can use some oidc library for angular (like this for example) and your angular part would basically be a js client using Hybrid flow (preferably). You can use Angular router and route guarding in conjunction with one of the oidc libraries to automatically redirect user to the identity provider should they try to access protected resource and handle the token callback and do the cookie auth.

    Your backend part in AspNetCore would then become simply an ApiResource that your Angular client would have to be allowed to access (in the AllowedScopes) and would only be concerned with serving data to your Angular client (minus the fact that the AspNetCore razor engine serves the initial Angular AppComponent). It would not be concerned at all about guardian any routes and would only be concerned about validating bearer tokens that your Angular client would inject into Http calls to this backend Api.