I'm trying to authenticate my web api using Azure AD.
I'm following this tutorial and I successfully authenticated using my Angular App.
The problem is, when I put the Authorize
attribute in my controller, it gives me 401 Unauthorized
error in my angular console and even my post man.
As I view my web api log, it shows like this:
Here's my Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// removed because this doesn't work either
// services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
// .AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));
services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
// This is a Microsoft identity platform web API.
options.Authority += "/v2.0";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
}
}
In my appsettings.json
:
"AzureActiveDirectory": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "myorg.onmicrosoft.com",
"TenantId": "241234-12ad-1234-1234-123412341234", // sample only
"ClientId": "8786687-12ad-1234-1234-2341432341" // sample only client id from the webapi in the ad
},
In my App Client, here's my app.module.ts
// MSAL Imports
import {
MsalModule,
MsalInterceptor,
MSAL_CONFIG,
MSAL_CONFIG_ANGULAR,
MsalService,
MsalAngularConfiguration
} from '@azure/msal-angular';
import { Configuration } from 'msal';
// MSAL Configs
export const protectedResourceMap:[string, string[]][]=[['https://localhost:5000/', ['api://WEB-API-CLIENTID/api-access']] ];
const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1;
function MSALAngularConfigFactory(): MsalAngularConfiguration {
return {
popUp: !isIE,
consentScopes: [
"user.read",
"openid",
"profile",
"api://WEBAPI-CLIENT-ID/api-access"
],
unprotectedResources: ["https://www.microsoft.com/en-us/"],
protectedResourceMap,
extraQueryParameters: {}
};
}
function MSALConfigFactory(): Configuration {
return {
auth: {
clientId: 'ANGULAR-CLIENT-ID',
authority: "https://login.microsoftonline.com/TENANT-ID", /// with tenant id
validateAuthority: true,
redirectUri: "http://localhost:4200/",
postLogoutRedirectUri: "http://localhost:4200/",
navigateToLoginRequestUrl: true,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: isIE, // set to true for IE 11
},
};
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
RouterModule.forRoot(appRoutes),
NgHttpLoaderModule.forRoot(),
FormsModule,
// msal angular
MsalModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
{
provide: MSAL_CONFIG,
useFactory: MSALConfigFactory
},
{
provide: MSAL_CONFIG_ANGULAR,
useFactory: MSALAngularConfigFactory
},
MsalService
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Other info: I already saw this thread but it doesn't help fix my issue.
I look forward for someone's help.
BearerAuthenticationScheme
The default scheme for Azure Active Directory B2C Bearer. If you are using, AddAzureADB2CBearer(AuthenticationBuilder, Action<AzureADB2COptions>)
then use JwtBearerAuthenticationScheme
otherwise, use the default bearer scheme.
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));
Please double check your clientId
if it's assigned properly to your app. It's only normal to throw a 401 unauthorized
if it's doesn't meet its security requirements.
If you can get the accessToken
, try if it's a valid access token. Visit this jwt.ms . It should work using Postman if it is valid. make sure you use Authorization
Bearer your_accessToken_here
.
You should expect a 200 Ok
in postman. Now, try it on your angular app.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.