15

I'm not able to access protected method with Authorized with a token generated by Asp.net Core.

The configuration :

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.Audience = Configuration["Tokens:Issuer"]; cfg.ClaimsIssuer = Configuration["Tokens:Issuer"]; cfg.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Tokens:Issuer"], ValidAudience = Configuration["Tokens:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])) }; 

The token generated :

var claims = new[] { new Claim (JwtRegisteredClaimNames.Sub, model.Email), new Claim (JwtRegisteredClaimNames.Jti, Guid.NewGuid ().ToString()), }; //_config var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expiration = DateTime.UtcNow.AddDays(7); var token = new JwtSecurityToken(_config["Tokens:Issuer"], _config["Tokens:Issuer"], claims, expires: expiration, signingCredentials: creds); return new TokenModel() { Token = new JwtSecurityTokenHandler().WriteToken(token), Expiration = expiration, UserFirstName = model.FirstName, UserLastName = model.LastName }; 

After the generation I get this kind of token :

{ "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZWl4ZWlyYXBlcnNvQGdtYWlsLmNvbSIsImp0aSI6IjVmNTk3OGVkLWRlZjAtNDM3Yi1hOThhLTg3ZWU4YTQ3MmZlNCIsImV4cCI6MTUxODg2ODYxOCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIn0.1fHXr8jtuZ8PTJmJPBKQIqiOk_c-bCQ6KRyFLLJkU5s", "expiration": "2018-02-17T11:56:58.683076Z", "userFirstName": null, "userLastName": null } 

I can add or not the autorization in my HTTP headers in Postman, I receive an "Unauthorized Exception - 401"

I already check some other Stack post and GitHub Post, It seems my configuration it's ok.

If needed I can add the configuration file.

Thanks.

Edit 1 :

Here the screen of the header in postman :

enter image description here

8
  • how is your authorization header looking? Commented Feb 10, 2018 at 12:05
  • @DotNetDev picture added :) Commented Feb 10, 2018 at 12:09
  • 1
    Are you sure the same security algorithm (HMACSHA256) is being used to validate the token? You don't specify it in your .AddJwtBearer options so it will use the default which may not be the same algorithm. Commented Feb 10, 2018 at 22:15
  • 1
    Ok So i remove some extra configuration and it's works.... thnks guys Commented Feb 12, 2018 at 20:04
  • 2
    @OrcusZ Nevermind, I got it :) Just removed all the options and kept the absolute min which is the issuersigningkey, validissuer and validaudience. Commented Apr 13, 2018 at 18:45

2 Answers 2

42

I'm unsure if you're facing the same issue, but I'm running an ASP.NET Core project with code looking similar to yours.

I encountered 401 responses when including a bearer token provided by the API's login, but this was fixed by calling app.UseAuthentication() as the first method in Configure(). My code changed from this...

app.UseMvc(); app.UseAuthentication(); 

To this...

app.UseAuthentication(); app.UseMvc(); 
Sign up to request clarification or add additional context in comments.

3 Comments

You are saver! I just lost couple hours figuring why it doesn't work and it was just order of calls!
If i could give you 10000 points I would. This is exactly my issue.
You are a lifesaver. This small change cost me two days. Kudos!
7

Your code looks OK. The most possible root cause of the problem is that you have not added authentication middleware to your application. AddAuthentication extension call for IServiceCollection just registers all required services, but it does not add authentication middleware to HTTP request pipeline.

To fix the problem add following call in Startup.Configure() method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); // ... } 

I was able to reproduce the problem with your code, and calling app.UseAuthentication() fixes the issue.

6 Comments

Hm, then I can't reproduce your problem. I've copy/pasted your code and authentication works fine if app.UseAuthentication() is called.
humm... I think I did not tell it, but i'm running this code in a macOS system, I don't know if this can be the source of the problem
Do you have a chance to launch it on Windows? It will help a lot to narrow the possible root causes.
Yes. I will did it and back when I have tested it correctly in a windows system :)
@OrcusZ Anychance you every find the issue? I'm in the exact same situation right now.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.