I have an Angular 7 application interfacing with a .Net Core 2.2 API back-end. This is interfacing with Azure Active Directory.
On the Angular 7 side, it is authenticating properly with AAD and I am getting a valid JWT back as verified on jwt.io.
On the .Net Core API side I created a simple test API that has [Authorize] on it.
When I call this method from Angular, after adding the Bearer token, I am getting (as seen in Chrome Debug Tools, Network tab, "Headers"):
WWW-Authenticate: Bearer error="invalid_token", error_description="The
signature key was not found"
With a HTTP/1.1 401 Unauthorized.
The simplistic test API is:
[Route("Secure")]
[Authorize]
public IActionResult Secure() => Ok("Secure works");
The Angular calling code is also as simple as I can get it:
let params : any = {
responseType: 'text',
headers: new HttpHeaders({
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
})
}
this.http
.get("https://localhost:5001/api/azureauth/secure", params)
.subscribe(
data => { },
error => { console.error(error); }
);
If I remove the [Authorize] attribute and just call this as a standard GET request from Angular it works fine.
My Startup.cs contains:
services
.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureADBearer(options => this.Configuration.Bind("AzureAd", options));
The options are all properly set (such as ClientId, TenantId, etc) in the appsettings.json and options here is populating as expected.
I was facing the same issue. i was missing the authority..make sure authority and api name is correct now this code in configure services in startup file works for me:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication( x =>
{
x.Authority = "http://localhost:5000"; //idp address
x.RequireHttpsMetadata = false;
x.ApiName = "api2"; //api name
});
I had a unique scenario, hopefully this will help someone.
I was building an API which has Windows Negotiate authentication enabled (.NET Core 5.0, running from IIS) and unit testing the API using the CustomWebApplicationFactory (see documentation for CustomWebApplicationFactory) through XUnit which does not support Negotiate authentication.
For the purposes of unit testing, I told CustomWebApplicationFactory to use a "UnitTest" environment (ASPNETCORE_ENVIRONMENT variable) and specifically coded logic into my application Startup.cs file to only add JWT authentication for the "UnitTest" environment.
I came across this error because my Startup.cs configuration did not have the signing key I used to create the token (IssuerSigningKey below).
if (_env.IsEnvironment("UnitTest"))
{
// for unit testing, use a mocked up JWT auth, so claims can be overridden
// for testing specific authentication scenarios
services.AddAuthentication()
.AddJwtBearer("UnitTestAuth", opt =>
{
opt.Audience = "api://local-unit-test";
opt.RequireHttpsMetadata = false;
opt.TokenValidationParameters = new TokenValidationParameters()
{
ClockSkew = TokenValidationParameters.DefaultClockSkew,
ValidateAudience = true,
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
ValidAudience = "api://local-unit-test",
ValidIssuer = "unit-test",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abcdefghijklmnopqrstuvwxyz123456"))
};
});
} else {
// Negotiate configuration here...
}
Regardless of the ValidateIssuerSigningKey being true or false, I still received the "invalid_token" 401 response, same as the OP. I even tried specifying a custom IssuerSigningKeyValidator delegate to always override the result, but did not have luck with that either.
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature key was not found"
When I added IssuerSigningKey to the TokenValidationParameters object (of course matching the key I used when generating the token in my unit test), everything worked as expected.
There could be two reason:
You might have missed registering service :
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
Or
2. You might have missed assigning value to key "IssuerSigningKey" as shown below
validate.TokenValidationParameters = new TokenValidationParameters()
{
ValidateAudience = true,
ValidAudience = "Audience",
ValidateIssuer = true,
ValidIssuer = "http://localhost:5000",
RequireExpirationTime = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("abcdefghi12345"))
});
This resolved my problem
My problem was that I needed to set the ValidIssuer option in the AddJwtBearer TokenValidationParameters, in addition to the authority
For example:
services.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
options.Audience = "My Audience";
options.Authority = "My issuer";
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidateIssuer = true,
ValidIssuer = "Also My Issuer", //Missing line here
ValidateAudience = true
};
});
Verify the values that you send for request the jwt token (eg: grant_type, client_secret, scope, client_id, etc)
Ensuere that you are using the appropiate token. That's all!
Here is my mistake:
I was using Postman, and request a token and set it to a varibale "Var_Token1":
pm.environment.set("Var_Token1", pm.response.json().access_token);
But when I need to use the token for my final request, I selected and use the wrong token (Var_Token2):
Authorization: Bearer {{Var_Token2}}
For me, this error was coming because the URL in appsettings.json was incorrect. I fixed it and it's working fine now.
This can also happen if you are using a different SignedOutCallbackPath/SignUpSignInPolicyId policy id than which is being passed in the token as tfp/acr.
My Core API uses different services configuration (and it works :)):
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
Configuration.Bind("JwtBearer", options);
}
Are you sure you are passing an access token and not an id_token? Is the aud claim present in the token exactly the same as the clientid your API is configured with? You may want to add some events to your options to see what you are receiving and where the validation fails.
I had this issue, and it was caused by jwtOptions.Authority not being set in config.
If you are using:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,
And jwtOptions.Authority is set to null or "" you can get this error message.
Related
I have a Web API written in .net core 5.0 and I am using Angular 10 for the front end. For now I have kept all the APIs open, however, to move this application in production I need to validate each API call and check if a logged in user is sending these requests.
I have modified the API controller like this :
[Authorize]
[HttpGet]
public List<ReportDataValues> GetReportingData()
{
var ReportData = _context.ReportDataValues.ToList();
return ReportData;
}
Here is my relevant code for the startup.cs file which configures the JWT authentication :
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = false;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(LoginKey),
ValidateIssuer = true,
ValidateLifetime = true,
ValidIssuer = "https://localhost:5001",
ValidAudience = "https://localhost:5001",
ValidateAudience = true,
};
});
}
I am using the #auth0/angular-jwt library to include authorization token in each http request. In my app.module.ts file I have declared a function :
export function tokenGetter(){
return localStorage.getItem('token');
}
Here, token is the id for the key, where the server is returning the token value for the login request. I have verified that a token gets generated and is getting stored in the localStorage
In the app.module.ts I have also included the configuration to include the tokens in each request :
imports: [
JwtModule.forRoot({
config : {
tokenGetter : tokenGetter,
allowedDomains : ["localhost:44326"],
disallowedRoutes : []
}
}),
BrowserModule,
AutocompleteLibModule,
BrowserAnimationsModule,
Based on my understanding this should be enough to include the auth headers in each http request. Here is the http request I am making for this API controller :
return this.http
.get<any[]>(GlobalConstants.baseURL + 'ReportingData')
However, I get an error saying that this request is unauthorized and I see the Network tab in the dev tools has the Bearer token inside it and it is the same token that can be seen in the Application tab in dev tools:
The console logs this error as below :
Can someone please tell me if I need to make any other configuration changes to enable this request to be authorized?
Working on a ASP.Net Core 3.1 API I am having trouble with JWT (bearer) token validation in production.
Given this code:
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.Authority = config["JwtOptions:Authority"];
x.Audience = config["JwtOptions:Audience"];
}
all works will in my development environment. However, moving to production, the token is found to be invalid. Kestrel returns a WWW-Authenticate header that says:
Bearer error="invalid_token", error_description="The signature is invalid"
I am at loss for the reason for this difference. The only way to get it working in production seems to alter the settings as below, however, this means sacreficing all security that the JWT should provide...
x.TokenValidationParameters = new TokenValidationParameters
{
RequireSignedTokens = false,
ValidateIssuerSigningKey = false,
ValidateIssuer = false,
ValidateAudience = false,
SignatureValidator = delegate(string token, TokenValidationParameters parameters)
{
var jwt = new JwtSecurityToken(token);
return jwt;
},
};
Any ideas are welcome.
EDIT
The problem lies with HTTP. When using HTTPS, things work fine. This would seem to be a bug in Microsoft.AspNetCore.Authentication.JwtBearer, since I'd expect this to work with HTTP as well. Microsoft actually has manual for using a reverse proxy to shield Kestrel from the worlds; using HTTP should be fine in that case.
I'm attempting to set up two different authorization policies called 'portal' and 'api' on our .NET Core 2.1 project hosted on a AWS Lambda environment. The first is the default policy that is used by the front-end site, and the latter is used by developers seeking to use our external API. I want each one to be signed with a different IssuerSigningKey so that users cannot use the bearer token they receive interchangeably with the two different services.
The problem I'm having is that the bearer token generated to access the 'api' policy works sometimes, but not others. I will get five 401s in a row, then followed by several 200s, then back to 401s. Seems very random. The errors I'm getting when the 401s show up are
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Failed to validate the token.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: portal was not authenticated. Failure message: IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey , KeyId:
'.
Exceptions caught:
''.
token: '
{
"alg": "HS512",
"typ": "JWT"
}
.
{
"nameid": "88",
"unique_name": "my#email.com",
"role": "apiAccess",
"nbf": 1596835699,
"exp": 1596839299,
"iat": 1596835699
}
'.
Which implies to me that sometimes it's not attempting to use the 'api' policy to validate the bearer token, but instead it's defaulting to 'portal'.
Here is a sample in Startup.cs where I set this all up.
...
serviceDependencies
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer("portal", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(portalAccessKey),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true
};
})
.AddJwtBearer("api", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(apiAccessKey),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false
};
});
serviceDependencies.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("portal")
.Build();
options.AddPolicy("MeteredAccess", new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("api")
.RequireClaim(ClaimTypes.Role, "apiAccess")
.Build());
});
...
And the MVC endpoint I am applying the policy to is
[Authorize(Policy = "MeteredAccess")]
[HttpPost("api/objects/save")]
public async Task<IActionResult> ApiCreateObject([FromBody] CoreEngineObjectFormData data)
{
if(!(await _authService.UpdateUserApiAuthentications(UserId)))
return StatusCode(429);
var result = await _coreEngineService.CreateCoreEngineObject(data);
return Ok(result);
}
I never have this problem with the default policy, requests made from the front-end work every time.
Also, a big thing to mention is that I don't have this problem at all when I run the project locally under IIS Express, it's only after I deploy the project AWS Lambda that this starts to happen. I suspect that something about the lambda's lifetime may have something to do with this.
I've tried for a couple of days to consume a jwt token in my .net core 2.1 web service. The token is rejected with a SecurityTokenInvalidSignatureException: IDX10503: Signature validation failed.-exception.
My setup is quite simple:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(configureOptions => {
configureOptions.ClaimsIssuer = "http://localhost/";
configureOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String("zeey+h0M8mvWSR9HYKlNns+....")),
ValidateIssuer = true,
ValidIssuer = "http://localhost/",
ValidateAudience = true,
ValidAudience = "efb4f12d020b434c9b531af96263b3fa",
};
});
Putting the token I receive into https://jwt.io/, the signature is found valid:
But my web service still refuses to acknowledge the token.
What am I doing wrong?
I finally found the answer to my problem:
My key was wrong. But even with the correct key, I still got the same error...
When constructing the SymmetricSecurityKey, I had to use Encoding.Unicode.GetBytes(...) instead of Encoding.ASCII or Encoding.UTF8.
I'm still having trouble with jwt.io. I guess this site is no longer a good place for validating tokens.
I am implementing security on an ASP.NET Core 1.0.1 application, which is used as a Web API. I am trying to understand if and how to implement 2 different authentication schemes.
Ideally, I would like to allow authentication via Azure Active Directory or via username/password for specific back-end services that contact the application.
Is it possible to configure ASP.NET Core for such a setup where an endpoint either authenticates through Azure AD or JWT token?
I tried with something like this, but upon calling the generate token endpoint, I get a 500 with absolutely no information. Removing the Azure AD configuration makes the endpoint work perfectly:
services.AddAuthorization(configuration =>
{
configuration.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
configuration.AddPolicy("OpenIdConnect", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(OpenIdConnectDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = Configuration["Authentication:AzureAD:ClientId"],
Authority
= Configuration["Authentication:AzureAd:AADInstance"]
+ Configuration["Authentication:AzureAd:TenantId"],
ResponseType = OpenIdConnectResponseType.IdToken,
SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme
});
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.FromMinutes(1),
IssuerSigningKey = TokenAuthenticationOptions.Credentials.Key,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = TokenAuthenticationOptions.Audience,
ValidIssuer = TokenAuthenticationOptions.Issuer
}
});
Use the OpenIdConnectDefaults.AuthenticationScheme constant when you add the authorization policy and when you add the authentication middleware.
Here you are using OpenIdConnectDefaults. Good. Keep that line.
services.AddAuthorization(configuration =>
{
...
configuration.AddPolicy("OpenIdConnect", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(OpenIdConnectDefaults.AuthenticationScheme) // keep
.RequireAuthenticatedUser().Build());
});
Here you are using CookieAuthenticationDefaults. Delete that line.
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
...
SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme // delete
});
Why?
When your OpenIdConnect authorization policy runs, it will look for an authentication scheme named OpenIdConnectDefaults.AuthenticationScheme. It will not find one, because the registered OpenIdConnect middleware is named CookieAuthenticationDefaults.AuthenticationScheme. If you delete that errant line, then the code will automatically use the appropriate default.
Edit: Commentary on the sample
A second reasonable solution
The linked sample application from the comments calls services.AddAuthentication and sets SignInScheme to "Cookies". That changes the default sign in scheme for all of the authentication middleware. Result: the call to app.UseOpenIdConnectAuthentication is now equivalent to this:
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme
}
That is exactly what Camilo had in the first place. So why did my answer work?
My answer worked because it does not matter what SignInScheme name we choose; what matters is that those names are consistent. If we set our OpenIdConnect authentication sign in scheme to "Cookies", then when adding an authorization policy, we need to ask for that scheme by name like this:
services.AddAuthorization(configuration =>
{
...
configuration.AddPolicy("OpenIdConnect", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme) <----
.RequireAuthenticatedUser().Build());
});
A third reasonable solution
To emphasize the importance of consistency, here is a third reasonable solution that uses an arbitrary sign in scheme name.
services.AddAuthorization(configuration =>
{
configuration.AddPolicy("OpenIdConnect", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Foobar")
.RequireAuthenticatedUser().Build());
});
Here you are using CookieAuthenticationDefaults. Delete that line.
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
SignInScheme = "Foobar"
});