我正在尝试使用MSAL Angular库通过Microsoft进行授权。我在MS Azure中配置了环境,编写了一个代码...登录后,我将获得ID_Token,但是我无法在Graph.microsoft.com/v1.0/me上验证它为持有人。我得到了"无效的访问"代码。我搜索了所有堆栈,即使有一些熟悉的线程,我仍然无法弄清楚。我想确保令牌有效,并从响应中获取用户电子邮件。这是我的代码:
@Injectable()
export class MsalService {
B2CTodoAccessTokenKey = 'b2c.access.token';
tenantConfig = {
tenant: 'censored.onmicrosoft.com',
// Replace this with your client id
clientID: 'censored',
signInPolicy: 'B2C_1_signinsignup',
signUpPolicy: 'B2C_1_signin',
redirectUri: 'http://localhost:4200/auth/microsoft',
b2cScopes:
['https://censored.onmicrosoft.com/api/user_impersonation'],
resource: 'https://graph.microsoft.com'
};
/*
* B2C SignIn SignUp Policy Configuration
*/
clientApplication = new Msal.UserAgentApplication(
this.tenantConfig.clientID, this.authority,
function(errorDesc: any, token: any, error: any, tokenType: any) {
},
{
redirectUri: this.tenantConfig.redirectUri,
navigateToLoginRequestUrl: false
}
);
public login(): void {
this.clientApplication.authority =
'https://login.microsoftonline.com/common';
this.authenticate();
}
public authenticate(): void {
var _this = this;
this.clientApplication.loginPopup(this.tenantConfig.b2cScopes)
.then(function(idToken: any) {
_this.clientApplication.acquireTokenSilent(
_this.tenantConfig.b2cScopes)
.then(
function(accessToken: any) {
_this.saveAccessTokenToCache(accessToken);
}, function(error: any) {
_this.clientApplication.acquireTokenPopup(
_this.tenantConfig.b2cScopes).then(
function(accessToken: any) {
_this.saveAccessTokenToCache(accessToken);
}, function(error: any) {
console.log('error: ', error);
});
});
}, function(error: any) {
console.log('error: ', error);
});
}
首先,您似乎缺少wendys_type参数,这是您正在使用的授权代码授予流。
另外,您不能直接使用令牌,而需要将您从响应URL获得的代码交换到令牌中。
public static AuthenticationResult ExchangeCodeForToken(string InTenantName, string InUserObjId, string InRedirectUri, string InApplicationAzureClientID, string InApplicationAzureClientAppKey)
{
Check.Require(!string.IsNullOrEmpty(InTenantName), "InTenantName must be provided");
Check.Require(!string.IsNullOrEmpty(InUserObjId), "InUserObjId must be provided");
if (CanCompleteSignIn) //redirect from sign-in
{
var clientCredential = new ClientCredential(InApplicationAzureClientID, InApplicationAzureClientAppKey);
var authContext = new AuthenticationContext(Globals.GetLoginAuthority(InTenantName), (TokenCache)new ADALTokenCache(InUserObjId)); //Login Authority is https://login.microsoftonline.com/TenantName
return authContext.AcquireTokenByAuthorizationCode(VerificationCode, new Uri(InRedirectUri), clientCredential, Globals.AZURE_GRAPH_API_RESOURCE_ID); //RESOURCE_ID is "https://graph.microsoft.com/"
}
return null;
}
参见相关文章。