I am writing a web application using the ASP.NET kernel for the backend / service and Angular2 as an interface, and have authentication / authorization issues.
In the ASP.NET core, I only got one html page and a controller, HomeController with an index that allows anonymous access ([AllowAnonymous]). This single page provides angular2-app to the client.
All other communications use ApiControllers (which in the ASP.NET kernel are just normal controllers, but the actions of these controllers expect and send JSON data. I want to use jwt tokens for authentication / authorization. Users, roles, claims, etc. are stored in IdentityDbContext using the EF core.
Most of the tutorials I found are outdated, incomplete, or related to third-party OAuth solutions. I'm not looking for OAuth, I just need a page with username / Passwort and using tokens for logging in, since I use the whole API to get data using the backend. I read a lot of tutorials, tried some useful libraries, but still got confused about how to set up the middleware chain for security on tokens. As far as I understand, I need to add services for identification, since I want to use IdentityDbContext:
public void ConfigureServices(IServiceCollection services) { [...] services.AddIdentity<IdentityUserEntity, IdentityRoleEntity>() .AddEntityFrameworkStores<ApplicationDbContext, long>() .AddDefaultTokenProviders(); [...] }
But what middleware do I need to configure in the setup? Do I need app.UseIdentity () or app.UseJwtBearerAuthentication (o) enough? Wouldn't use UseIdentity for authentication before JwtBearer receives a snapshot when checking tokens ??
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { [...] app.UseIdentity(); [...] app.UseJwtBearerAuthentication(jwtOptions); [...] }
I ask because the client automatically authenticated after I made the call to _signInManager.PasswordSignInAsync (...) in my TokenController, although my client never received jwt. So somehow, ASP.NET identity management found another way to authenticate my user after logging in, which, of course, shouldn't be.
So, how do I perform token based authentication and nothing else?
[UPDATE]
I think I need to intercept the Cookie authentication event and reject the principal in order to disable Cookie authentication (see https://stackoverflow.com/a/125278/ ): But for some reason, my event handler is never called.
app.UseCookieAuthentication(new CookieAuthenticationOptions() { Events = new CookieAuthenticationEvents { OnValidatePrincipal = ValidateAsync } }); public static async Task ValidateAsync(CookieValidatePrincipalContext context) { context.RejectPrincipal(); await context.HttpContext.Authentication.SignOutAsync("BsCookie"); }
Better reads about auth, cookies and token:
- http://andrewlock.net/exploring-the-cookieauthenticationmiddleware-in-asp-net-core/
- https://stormpath.com/blog/token-authentication-asp-net-core