'Cannot validate Azure AD Token and Identity.IsAuthenticated returns false

I registered my app on Azure AD where I got ClientId, TenantId, etc. Since my app is a web api I test to get access token as described here https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow and successfully obtain the access token, I test the token using Postman. Unfortunately, the app cannot validate the token that the User.Identity.IsAuthenticated always returns false. When I check the User property it is empty and contains no claims such as email etc even if I set it in Azure.

var builder = WebApplication.CreateBuilder(args);

var configuration = builder.Configuration;
var services = builder.Services;

services.AddMicrosoftIdentityWebApiAuthentication(configuration);

services.AddControllers();
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();


var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthentication();
app.Use(async (context, next) =>
{
    bool isAuthenticated = context.User?.Identity?.IsAuthenticated == true; //always false even if the authorization bearer token exists
    if (!isAuthenticated)
    {
        //more logics here
    }
    else
    {
        await next();
    }
});

app.MapControllers();

app.Run();


Solution 1:[1]

Please check the references if they can help.

In token authentication , the server will get the token from the request header with the 'Authentication' key, after that it validates.In the Configure method in Startup.cs, enable authentication with a call to app.UseAuthentication();

app.UseSession();
app.Use(async (context, next) =>
     {
         var JWToken = context.Session.GetString("Token");
         if (!string.IsNullOrEmpty(Token))
         {
             context.Request.Headers.Add("Authorization", "Bearer " + Token);
         }
         await next();
     });
 app.UseAuthentication();

 app.UseAuthorization();

or you can check the user in api controller using httpcontext.user. If you expose api scope , it can be used in here.

[Authorize]
    [Route("api/[controller]")]
    public class TodoListController : Controller
    {

        [HttpGet]
        public IEnumerable<TodoItem> Get()
        {
           //here
        }

see Context.User.Identity.IsAuthenticated is always false in jwt token? - Microsoft Q&A

References:

  1. Configure protected web API apps - Microsoft identity platform | Microsoft Docs
  2. Quickstart: Protect a web API with the Microsoft identity platform - Microsoft identity platform | Microsoft Docs
  3. How To Protect Your ASP NET Web API Using JWT Authentication | (rahulpnath.com)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kavyasaraboju-MT