![](/img/trans.png)
[英]How to make ASP.Net Core Web API Identity return a 401 on unauthorized
[英]"Authorization failed. AuthenticationScheme: AzureADJwtBearer was challenged" in ASP.NET Core 3.1 Web API - 401 Unauthorized
我正在尝试使用 Azure AD 对我的 Web api 进行身份验证。
我正在学习本教程,并且使用我的 Angular 应用程序成功进行了身份验证。
问题是,当我将Authorize
属性放在我的控制器中时,它在我的角度控制台甚至我的401 Unauthorized
给了我401 Unauthorized
错误。
当我查看我的 web api 日志时,它显示如下:
这是我的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();
}
}
在我的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
},
在我的 App Client 中,这是我的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 { }
其他信息:我已经看过这个帖子,但它无助于解决我的问题。
我期待着有人的帮助。
BearerAuthenticationScheme
Azure Active Directory B2C Bearer 的默认方案。 如果您使用AddAzureADB2CBearer(AuthenticationBuilder, Action<AzureADB2COptions>)
然后使用JwtBearerAuthenticationScheme
否则,使用默认承载方案。
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));
请仔细检查您的clientId
是否已正确分配给您的应用。 如果不符合其安全要求,则抛出401 unauthorized
的401 unauthorized
是正常的。
如果您可以获得accessToken
,请尝试它是否是有效的访问令牌。 访问此jwt.ms 。 如果有效,它应该可以使用 Postman。 确保您使用Authorization
Bearer your_accessToken_here
。
你应该期待邮递员的200 Ok
。 现在,在您的 angular 应用程序上尝试一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.