I’m building out the LoECDA.com website and decided to rewrite the app using .net core 2.0 with some vue.js instead of angular. LoECD.com is a place where you can see the profiles of all the League members, as well as their speaking schedules. It’s also my personal playground for playing with new technologies.
I knew I needed some type authentication because there is a private admin section where League members can go in and update their profiles and speaking schedules. So… easy enough, fired up Visual Sudio 2017, File > New > Proj, selected an ASP.NET Core Web Application which brought me to the New ASP.NET Core Web Application dialog. From here, I picked Web Application (Model-View-Controller), made sure I was creating a .net core 2.0 project and changed Authentication to use Individual User Accounts
Visual Studio scaffolded out my asp.net core 2.0 web project, turned on cookies based authentication with user info saved to a database using EF. If we look at the Startup.cs file
The two red boxes got added to my ConfigureService(IServiceCollection services) method. This turned on my cookies based authentication and uses EF so if I wanted to secure my AdminController where only people that have logged in can access the actions, all I would need to do is add the attribute [Authorize]
First, I needed to a way to generate the JWT’s so I wrote a TokenController that given a username and password, generates a valid token
Next, I configured asp.net core to use token authentication. So in the Startup.cs, I added the following to ConfigureServices(IServiceCollection services)
Made sure app.UseAuthentication() was called in Configure(IApplicationBuilder app, IHostingEnvironment evn)
Created an api controller for my apis and slapped the [Authorize] attribute on it.
Aaaaaaaaand… guess what, it didn’t work. I started debugging using postman and I noticed something really curious. Even though I was passing the token in the header correctly, it was still trying to reroute me to the login page.
Apparently, when I used the [Authorize] attribute, it bound to the first authentication system by default (cookies). So I needed to specify which auth to use. To do that, i added the attribute [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
And bam! Everything started working.
If you want to use both tokens and cookies in your .net core 2.0 project, it defaults to cookie based. If you want to use tokens, make sure you specify which method of authorization to check. You can do it with the attribute
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]