Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net core 2 - 401 error with bearer token

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

like image 949
OrcusZ Avatar asked Feb 10 '18 12:02

OrcusZ


2 Answers

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();
like image 132
phantomraa Avatar answered Oct 06 '22 00:10

phantomraa


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.

like image 37
CodeFuller Avatar answered Oct 06 '22 00:10

CodeFuller