Asp.net core 2 - 401 error with bearer token

OrcusZ picture OrcusZ · Feb 10, 2018 · Viewed 8.4k times · Source

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

Answer

phantomraa picture phantomraa · Apr 30, 2018

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();