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

OrcusZ
  • 3,555
  • 2
  • 31
  • 48

2 Answers2

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();
Jules
  • 1,677
  • 1
  • 19
  • 25
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.

CodeFuller
  • 30,317
  • 3
  • 63
  • 79
  • Hm, then I can't reproduce your problem. I've copy/pasted your code and authentication works fine if `app.UseAuthentication()` is called. – CodeFuller Feb 12 '18 at 09:04
  • 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 – OrcusZ Feb 12 '18 at 09:10
  • Do you have a chance to launch it on Windows? It will help a lot to narrow the possible root causes. – CodeFuller Feb 12 '18 at 09:21
  • Yes. I will did it and back when I have tested it correctly in a windows system :) – OrcusZ Feb 12 '18 at 09:22
  • @OrcusZ Anychance you every find the issue? I'm in the exact same situation right now. – hjavaher Apr 13 '18 at 08:42
  • @hjavaher it was an configuration mistake for me. Post a new issue I will have a look – OrcusZ Apr 13 '18 at 10:40