【发布时间】:2021-03-22 13:43:25
【问题描述】:
您好,我正在为我的客户端 SPA 应用程序和 .Net 核心后端 API 应用程序实施身份验证和授权。我在 azure ad 中为 SPA 和 API 应用程序注册了两个应用程序。我可以使用 Postman 获取令牌,如下所示。
我可以获得带有所需详细信息的令牌。现在我在前端反应应用程序中尝试同样的事情。我正在使用 react adal 库。
我有下面的代码来获取令牌
/* istanbul ignore file */
import { adalGetToken, AuthenticationContext, UserInfo } from 'react-adal';
import { UserProfile } from '../common/models/userProfile';
class AdalContext {
private authContext: AuthenticationContext | any;
private appId: string = '';
private endpoints: any;
public initializeAdal(adalConfig: any) {
debugger;
this.authContext = new AuthenticationContext(adalConfig);
this.appId = adalConfig.clientId;
this.endpoints = adalConfig.endpoints.api;
}
get AuthContext() {
return this.authContext;
}
public getToken(): Promise<string | void | null> {
debugger;
return adalGetToken(this.authContext, this.appId, this.endpoints).catch((error: any) => {
if (error.msg === 'login_required' || error.msg === 'interaction_required') {
this.authContext.login();
}
});
}
public acquireToken(callback: Function) {
let user = this.AuthContext.getCachedUser();
if (user) {
this.authContext.config.extraQueryParameter = 'login_hint=' + (user.profile.upn || user.userName);
}
adalGetToken(this.authContext, this.appId, this.endpoints).then(
(token) => {
callback(token);
},
(error) => {
if (error) {
if (error.msg === 'login_required') this.authContext.login();
else {
console.log(error);
alert(error);
}
}
}
);
}
public getCachedToken(): string {
return this.authContext.getCachedToken(this.authContext.config.clientId);
}
public getCachedUser(): UserInfo {
return this.authContext.getCachedUser();
}
public getUserProfileData(): UserProfile {
const user = this.authContext.getCachedUser();
const userProfileData = new UserProfile();
if (user) {
userProfileData.name = user.profile.name;
userProfileData.firstName = user.profile.given_name;
userProfileData.surname = user.profile.family_name;
userProfileData.emailAddress = user.userName;
userProfileData.userProfileName = user.profile.name || user.userName;
}
return userProfileData;
}
public logOut() {
this.authContext.logOut();
}
}
const adalContext: AdalContext = new AdalContext();
export default adalContext;
export const getToken = () => adalContext.getToken();
我能够生成令牌,但这里的问题是在 Aud 字段中,我正在获取 SPA 的客户端 ID,但我的意图是获取后端的客户端 ID,因为我正在为我的后端应用程序生成令牌。所以我正在努力在反应 adal 代码中设置范围。 在邮递员中,我正在进入范围,但在这里不确定如何通过应对。端点在这里是否意味着范围?同样在邮递员中,我正在传递 SPA 应用程序的客户端机密,但在这里我看不到任何传递客户端机密的选项。有人可以帮助我在这里做错了什么,还是我以错误的方式理解事情。任何帮助,将不胜感激。谢谢
【问题讨论】:
-
我已经在您的案例中发布了我的想法,顺便说一下,api 是由您自己维护的,即使您提供带有 SPA 客户端 ID 的 Aud 的访问令牌,您也可以将其视为正确的验证码中的Aud。也就是说,如何检查token是否有效,就看你自己了。
-
实际上,我期望 aud 值作为后端客户端 ID,因为稍后在令牌的帮助下,我想代表我的第三个应用程序流实现。代表我的后端应用程序的令牌和客户端 ID 中的流 Aud 值应该相同
-
先生有进展吗?很高兴收到您的回复。
标签: reactjs asp.net-core azure-active-directory adal