我有一个客户端 Typescript React Web 应用程序需要与 .net 核心 api 进行通信。在客户端集成了 msal.js。我能够登录 AAD,获取用户帐户和访问 token 并将其作为 Bearer 传递给 api 调用。但是 api 级别的身份验证失败。
在客户端:
config: Msal.Configuration = buildConfiguration({ auth: {
clientId: 'clientId',
authority: 'authority',
validateAuthority: true,
navigateToLoginRequestUrl: false
} });
request = {
scopes: ["user.read"]
};
userAgentApp : Msal.UserAgentApplication = new Msal.UserAgentApplication(this.config);
private _accessToken: string = '';
public async GetAccessToken(): Promise<string>{
if(this._accessToken == '')
{
await this.userAgentApp.acquireTokenSilent(this.request)
.then((tokenResponse) => this._accessToken = tokenResponse.accessToken)
.catch((error) => console.log(error))
}
return this._accessToken;
}
public login() {
console.log("before login");
this.userAgentApp.handleRedirectCallback((error, response) =>
{
console.error(error)
});
this.userAgentApp.loginRedirect(this.request);
console.log("after login")
}
// Calling the api
axios.defaults.headers.common = {'Authorization': `Bearer ${accessToken}`}
const travelExpensesResponse = await axios.get("https://localhost:44350/api/reisekostenantrag")
在 API 上
// Start.cs ConfigureServices
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Audience = "clientId";
options.Authority = "authority";
});
我遇到了 SecurityTokenInvalidSignatureException:IDX10511:签名验证失败。
- 问题出在哪里?
- 是否有任何示例可以说明如何从客户端应用程序向 .net core api 传递 token ?
最佳答案
问题是 token 被赋予了这个范围user.read
,这是一个 Graph API 范围。
所以解决方案是在 azure 中注册服务器应用程序并创建一个 custom scope .
然后在客户端应用上:
request = {
scopes: ["api://clientid/access_as_user"]
};
关于c# - OAuth2 身份验证失败.net 核心 api 调用在 React-Typescript Web 应用程序上使用 Msal.js 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56935160/