.Net Mvc with api controller authenticated by owin jwt auth but when calling protected actions in Http current User null

Anonymous
2022-10-03T06:17:57.517+00:00

my web api hosted with mvc. mvc have cookie auth but i need to authenticate the web api with azure ad access token send by my another app so i use the owin jwt auth middleware but when try to access the action with [authorize] it returns authorization denied for the request and httpcontext.current.user is null. i decoded the access token in online decoder it contains user email id and other info but why it denied please help on this.

   `public partial class Startup  
    {  
        public void Configuration(IAppBuilder app)  
        {  
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);  
            ConfigureApiOAuth(app);  
            ConfigureAuth(app);  
        }  
  
        public void ConfigureApiOAuth(IAppBuilder app)  
        {         
            var issuer = "https://sts.windows.net/tenantId/";  
            var audienceId = myappregisterationclientid;  
            var audienceSecret = ASCIIEncoding.UTF8.GetBytes(clientsceret);  
  
            app.UseJwtBearerAuthentication(  
                new JwtBearerAuthenticationOptions  
                {  
                    AuthenticationMode = AuthenticationMode.Active,  
                    AllowedAudiences = new[] { audienceId },  
                    TokenValidationParameters = new TokenValidationParameters  
                    {  
                        ValidAudience = audienceId,  
                        ValidIssuer = issuer,  
                        ValidateLifetime = false  
                    },  
                    IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]  
                    {  
                        new SymmetricKeyIssuerSecurityKeyProvider(issuer, audienceSecret)  
                    }  
                });  
            HttpConfiguration config = new HttpConfiguration();  
            WebApiConfig.Register(config);  
            app.UseWebApi(config);  
        }  
    }  
}`    
  

controller:

[Authorize]  
public Dictionary
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
35,517 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. 2022-10-05T21:59:59.477+00:00

    Hello @Anonymous and thanks for reaching out. Usually 401 is returned when token validation has not been successful. Decode the token and verify iss and aud claims values are the expected ones. E.g. Some times the aud claim will be api://client-id or similar instead of client-id.

    Let us know if you need additional assistance. If the answer was helpful, please accept it and complete the quality survey so that others can find a solution.