user240141
user240141

Reputation:

ASP.Net WebApi responding unauthorized acess

I am having ASP.Net webapi which is hosted on Azure. Actually I am having two different subscription

  1. For Azure Active Directory - say its demo.onmicrosoft.com
  2. For hosting webapi. - say its hosted on abc.azurewebsites.net

My api which is hosted on abc.azurewebsites.net is registered on demo.onmicrosoft.com. My client app is a service app which is authenticating against a user that resides in demo.onmicrosoft.com. Authentication is basic authentication by passing user credentials and recieveing AccessToken from Azure Active Directory. After recieving token from demo.onmicrosoft.com I am calling api from abc.azurewebsites.net. Like this:

https://abc.azurewebsites.net/api/some/queryapi

Now, In my controller if I use

[Authorize]
public class SomeController:ApiController
{
  //my code
}

I am getting uauthorized access. and if I remove that attribute from controller it works fine. Can you help me out.Even after app registration & authentication why I am getting so. Is that because of two different subscription or something else.

Update

I am sending token to my webapi this way

using (var client = new HttpClient())
{
  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
}

IMO, since my token is from azure ad of some other subscription so its not getting recognized by my webapi.

More Update - Startup.cs

  public void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                    TokenValidationParameters = new TokenValidationParameters {
                         ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                    },
                });
        }

Web.config

  <add key="ida:Tenant" value="demo.onmicrosoft.com" />
  <add key="ida:Audience" value="https://demo.onmicrosoft.com/4e4xxxx5-5xx1-4355-8xxc-705xxxx163" />
  <add key="ida:ClientID" value="d0xxxxa-2xxx6-4xx-9e58-07xxxxxxxx1" />

Upvotes: 1

Views: 1058

Answers (2)

bram_sharp
bram_sharp

Reputation: 36

1). Make sure Azure Authentication setting off.

2). In StartupAuth.cs

        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // Note: Remove the following line before you deploy to production:
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);

follow this article: https://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

Upvotes: 0

Fei Xue
Fei Xue

Reputation: 14649

It is relative to how you protect the web API instead of Azure subscription. For example, here is a piece of code which used to protect web API using Azure AD in the .net core:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
        // Add the console logger.
        loggerFactory.AddConsole(LogLevel.Debug);

        // Configure the app to use Jwt Bearer Authentication
        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAD:Tenant"]),
            Audience = Configuration["AzureAd:Audience"],
            Events = new JwtBearerEvents
            {
                OnTokenValidated = tokenValidated ,
                OnAuthenticationFailed= AuthenticationFailed
            }
        });
}

This web API will verify the signature of the token to ensure the token is issued from Azure AD. Then it will check the aud claim in the access token. If the aud claim also matched as we config in above code the we can call the web API successfully.

Upvotes: 2

Related Questions