Developing token authentication using ASP.NET Core

Samuele Resca on January 12, 2017

Originally posted on https://samueleresca.net Developing token authentication using ASP.NET Core Introduction The following article shows ho... [Read Full]
markdown guide
 

Very Nice. Thank you!!

The implementation since ok however when trying to access the api using the acquired token I get:

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET localhost:2709/api/values

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: (null).
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Warning: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware:Information: AuthenticationScheme: Cookie was challenged.

Seems that some part of the puzzle is missing.

Anyone have an idea why?

 

Also ran the api/token with the username and password all worked well I got the toekn in return which I appened to a HTTP get call to the server but the authorization fails

 

Errata corrige:

You need to pass the token in the HEADER of the request:

Authorization:Bearer <TOKEN>
 

When i pass the Authorization Bearer in header, it gives me this error:
The header name format is invalid.

This is how i'm passing it:

client.DefaultRequestHeaders.Add("Authorization:Bearer", json.accessToken);

where client is a HttpClient variable and json.accessToken is the value of the token.

Another approach..
If you download the tool Postman you can easily check how this works.
After you revieced your token, you just have to put into Header:
Key: Authorization
Value: Bearer YOUR_TOKEN
including the whitespace between Baerer and your token!

I get nothing but 401s using this very approach in Postman.

Try This

client.DefaultRequestHeaders.Add("Authorization",string.Concat("Bearer ", json.accessToken));

 

I am not able to install any packages for dotnet core, including the ones here.
Package Microsoft.AspNetCore.Identity 2.0.0 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package Microsoft.AspNetCore.Identity 2.0.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)
One or more packages are incompatible with .NETCoreApp,Version=v1.1.
Package restore failed. Rolling back package changes for

this is the error I get when installing Microsoft.AspNetCore.Identity. Same for Microsoft.AspNetCore.Authentication.JwtBearer or any AspNetCore package. I have made sure that the project type is correct.

 

Thank you for the article, it helped me a lot understanding Token generation/validation as I am new to all this asp.net/asp.net core universe.
I have a question though related with the middleware necessity. As you provided a route for the token generation (/api/token), I ask myself if another approach wouldn't be the implementation of the TokenProviderOption class as a Configuration/Option object as explained in this Microsoft doc (docs.microsoft.com/en-us/aspnet/co...) letting the TokenController manage token generation instead of creating a Middleware, apparently, just to hold the customized options for the token generation process.
I would be grateful for any insights on this matter!

 

"In each http call you need to pass the access_token parmeter:
hostname/controller/route?access_t..."
Can i pass the token in the headers section (like, a cookie, for example)? or i need to pass the token in the url?

Edit: Nevermind, didn't saw your "Errata corrige:"

Great article! \o

 

When a request arrives with a valid token in the header, how should the end point determine which user the token is associated with?

 

The token contains all the necessary informations. For example, you can see token infos here: (jwt.io/)[https://jwt.io/]

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJURVNUIiwianRpIjoiZTI2NGQ3NzktZTg2Ni00NGVlLThjOTUtZmI5YTA3NjNhM2ViIiwiaWF0IjoxNTI0NTIzNjY2LCJuYmYiOjE1MjQ1MjM2NjYsImV4cCI6MTUyNDUyMzk2NiwiaXNzIjoiRGVtb0lzc3VlciIsImF1ZCI6IkRlbW9BdWRpZW5jZSJ9.SORiDZO7kohrJ-Ew_hsTtJ5r9Zqn1RN9sjSTJni7MDo

 

First of all let me say this is an excellent post.

I have one question though.

I have implemented this with an WEB API project. If the user is not authorized (e.g. token expired) a 404 Not found is returned.

How can you return an unauthorized status instead of "404 Not found"

With cookies I had implemented it as such

 services.AddIdentity<ApplicationUser, IdentityRole>(identityOptions =>
            {
                identityOptions.Cookies.ApplicationCookie.Events =
                    new CookieAuthenticationEvents
                    {
                        OnRedirectToLogin = context =>
                        {
                            if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == (int)HttpStatusCode.OK)
                                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            else
                                context.Response.Redirect(context.RedirectUri);

                            return Task.CompletedTask;
                        }
                    };                


            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders(); 

Thanks
Shaheem

 

First of all, I thank you for this tutorial.. very useful..
I have a couple of questions (I'm new to JWT).

Let's say that I have a login page.
From this page I get the token.

I wonder to know how to pass it to the next controller (I use a redirect action when the credentials are correct) and globally how to add the famous header (Authorization:Bearer myToken) to all the controllers I use

My second question is how to manage the token refresh?

Thanks once again

 

Thanks for a great article! my question is how to refresh the token when it expires? or what's the mechanism I should adapt in order not to prompt my user for credentials when they're in the middle of doing something considering my token lifetime would only be 10 minutes.

 

I get the following error when trying to build: 'TokenProviderOptions' does not contain a definition for 'NonceGenerator' and no extension method 'NonceGenerator' accepting a first argument of type 'TokenProviderOptions' could be found (are you missing a using directive or an assembly reference?)

I see in your TokenProviderOptions you do not have a property for NonceGenerator()?

 

Couldn't find it either, so I googled Blog.TokenAuthGettingStarted and navigated to the same file, for some reason I could find it in there.


/// <summary>
/// Generates a random value (nonce) for each generated token.
/// </summary>
/// <remarks>The default nonce is a random GUID.</remarks>
public Func<Task<string>> NonceGenerator { get; set; }
= () => Task.FromResult(Guid.NewGuid().ToString());

 

When I try to implement with a .Net Core 2.0 project I get the following error in the Startup.Auth.cs file:
"JwtBearBearerAppBuilderExtensions.UseJwtBearerAuthentication(IapplicationBuilder,JwtBearerOptions) is obsolete"

Any idea how to resolve?

 
 
 

Hey Samuele Is it possible to use token based authentication in simple asp.net project ,mean (without MVC ,wihtout Asp.net core) please tell me ,If yes then How ?

 

Hi. The excelent example worked for me.

But , how to bring back the username on a Controller ?

 

Token based authentication is great... until you need to revoke a token.

 

Amazing article, helped me a lot since I'm a beginner in token based auth. thank you!

 

Nice article. Do you know how to validate/refresh token after database changed, eg: user change password... Thank you.

 

Is it possible to use this set up and point the Token IdentityResolver to a controller? If so, how?

code of conduct - report abuse