I'm trying to implement Bearer token (only) authentication in a .NET Core 3.1 API, using Azure AD.
I'm able to retrieve a token from Azure AD after verifying the authorization_code
and the browser posts back to my redirect URL with the following:
{"token_type":"Bearer","scope":"User.Read","expires_in":3600,"ext_expires_in":3600,"access_token":"EwBwA8l6...SzT3qoxGbSMg=="}
(shortened)
Once I have this token, should I be able to use the [Authorize]
attribute directly on my APIs and request using a Bearer token in the header? When I do, I get a 401 response.
I have this in my ConfigureServices()
:
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Audience = "<guid>";
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = false,
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abc123")),
TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abc123"))
};
});
services.AddControllers();
And in Configure()
I have:
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
In my error log, the message I'm seeing is:
"Bearer" was not authenticated. Failure message: "No SecurityTokenValidator available for token
I've tried many, many combinations of settings in Startup.cs, and no matter what I can only seem to get a 401 when calling my API from Postman. I'm able to get Cookie authentication working with code samples I've found online, but I don't want that.
Is the issue that the token is encrypted? Am I trying to use the wrong token? Or is there some other issue? Do I need to have identity set up in my app with database tables for AspNetUser, etc.?
In short, I'm just trying to generate a Bearer token using Azure AD as the auth provider, and make calls to my APIs by passing in a Bearer token header.