Token Authentication in ASP.NET Core 2.0 - A Complete Guide

Gayan Gunarathna

Very helpful article. could you please help me to figure out one problem… I am new to ASP.Net Core and Angular development…

I have used,
ASP.Net Core 2.0 Identity
Angular 6
for my development.

following some articles I configured the JWT middleware as follows.

in Startup.cs → ConfigureServices()

services.AddAuthentication()
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;

cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration[“JwtSecurityToken:Issuer”],
ValidAudience = Configuration[“JwtSecurityToken:Audience”],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[“JwtSecurityToken:Key”]))
};

});
and in Startup.cs → Configure()
app.UseAuthentication();

then in one of my controllers I applied like this.
[Authorize(Roles = “Agent”)]
[Route(“artists”)]
public IActionResult Artists()
{
// some logic
}

Problem:
in my Login method, I don’t issue any token. So when the logged in user(with Agent role) tries to call this controller,
surprisingly even without having a token in the client request, the authorization works. Again when I try to call this controller by logged in with different role it throws unauthorized access error which is as the expected. I don’t have any idea on how the authorization process works without creating and exchanging the tokens. Have I missed something here…

Nagaraju

I am getting WWW- AUthenticate Bearer error=“invalid token” erorr_description = “token not valid yet” some times though I have valid JWT after login… Can someone help me fix this issue. I am getting this in Angular 2 UI and ASP.Net core application.

Manjunath Somasekhar

Thank you for this document.

Rohan

Great document. Thanks:)

MichaelFreidgeim

In the previous version of this article https://stormpath.com/blog/…
“For web applications, we recommend using HttpOnly cookies instead of HTML5 storage/headers, for better security against XSS attacks”. In this article you don’t mention cookies. Does it mean , that now using bearer header is preferred than using HttpOnly cookies?

Ramesh Janjyam

very helpful. thank you. I have a question regarding consuming OAuth secured apis instead of using that as an authentication mechanism. for example - azure ad would be my app’s primary auth mechanism. I also want to allow user to connect to his github account so that I can display his repos in the app. can you let me know how I can achieve this?

Nate Barbettini

In that scenario, your application acts as a client to the GitHub API. You can think of this as being totally separate from how users authenticate to your application (Azure AD). Your app needs to implement the Github OAuth protocol documented here: https://developer.github.co…

Ramesh Janjyam

thank you for looking into it. I was trying to implement the same but had questions around good practices for storing tokens, using refresh token to get a new token when it expires, etc. thought it is a scenario that might have already been solved by others or may be a library out there which does this oauth dance and automatically refreshes tokens when it expires etc. but couldnt find any references online.

Dave Black

Thanks for the article. Just one problem/callout/suggestion…

With respect to your code when creating a symmetric key,

var sharedKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(“mysupers3cr3tsharedkey!”));


It is bad practice to use the System.Text.Encoding class for cryptography because of possible data loss. See here - https://haacked.com/archive/2012/01/30/hazards-of-converting-binary-data-to-a-string.aspx/

Nate Barbettini

Thanks Dave! I agree that handling the key in that way isn’t a best practice. In the code above it truly is ASCII text so I don’t think the issue in Haack’s blog applies, but it’s a contrived example. I definitely don’t recommend hardcoding the key in your code either. :slight_smile:
A production app should definitely use a KMS or at least store it in private environment variables.

Goomba

This article helps me a LOT!

khandokar sabbir

Hi Nate Barbettini

This is a great article.I need to clear the following things
How do i know which Key is valid for me among multiples keys in jwks_uri so that i can set to in IssuerSigningKey in "Specify Token Validation Parameter"
Where can i keep the method ValidateandDecode in asp.net core project and each request get called
Where can i write OpenIdConnectConfigurationRetriever code and make signingKeys available in configureService Method in startup

Cloudi5 Tech

Very interesting and it caught my attention. I do want a website that is easy to manage. Bookmarking your article which will probably be my guide. Thank you very much.
Cloudi5 https://www.cloudi5.com/web…

Vussan

Can somebody explain, how does token expiration work here?

Prachi More

This blog is useful for web developers, as it discusses the alternative options of ASP Net Core, which is the most reliable authentication used for application development. I was really confused to know about them before, though there are some differences in the functionality or features of these software solutions.

Abhi Mediratta

Thanks so much for the detailed explanation. I just have one question:
Does the middleware handle key rotation automatically? I’ll be using AWS Cognito’s auth server for document discovery.

Azizjan Ayupov

Thank you!

Good article @oktadev-blog. I like to use below mechanism to get SigningKeys from WellKnownEndPoint
var signingKeys = discoveryDocument.SigningKeys;

This code is in my Startup.cs file.

What will happen when SigningKeys change? Will my Token Validation all fail and will I have to restart my API in Production? That will be undesirable. Is the solution then to disable the SigningKeys completely?