reactjs - 'redirect_uri' 对于 Microsoft 登录 MSAL 身份验证 Azure 无效
问题描述
在 Azure AD B2C 上使用 Microsoft 登录我收到以下错误:
invalid_request:为输入参数“redirect_uri”提供的值无效。预期值是一个 URI,它与为此客户端应用程序注册的重定向 URI 匹配。
我可以联系其他提供商并使用电子邮件登录,而不是 Microsoft.. 大声笑。
我已经搜索了几个小时并尝试了我能想到的一切,希望其他人可以帮助确定问题。最初,我只能使用https://login.microsoft.com/common或类似的东西让 Microsoft 登录工作,但没有使用我的用户流/允许其他提供商。现在我的应用程序中的用户流正在运行,我无法使用 Microsoft 登录。下面是我的配置和代码。
我最初在这里遵循 Microsoft 教程:
然后将其他人拼凑在一起以使其使用我的用户流来执行,并且它除了使用 Microsoft 登录之外还可以工作。
在 Azure 上注册的应用程序清单:
{
"id": "<ID>",
"acceptMappedClaims": null,
"accessTokenAcceptedVersion": 2,
"addIns": [],
"allowPublicClient": true,
"appId": "<app id>",
"appRoles": [],
"oauth2AllowUrlPathMatching": false,
"createdDateTime": "2021-06-09T22:15:39Z",
"disabledByMicrosoftStatus": null,
"groupMembershipClaims": null,
"identifierUris": [],
"informationalUrls": {
"termsOfService": null,
"support": null,
"privacy": null,
"marketing": null
},
"keyCredentials": [],
"knownClientApplications": [],
"logoUrl": null,
"logoutUrl": null,
"name": "Management",
"oauth2AllowIdTokenImplicitFlow": true,
"oauth2AllowImplicitFlow": true,
"oauth2Permissions": [],
"oauth2RequirePostResponse": false,
"optionalClaims": null,
"orgRestrictions": [],
"parentalControlSettings": {
"countriesBlockedForMinors": [],
"legalAgeGroupRule": "Allow"
},
"passwordCredentials": [],
"preAuthorizedApplications": [],
"publisherDomain": "dwsdevb2c.onmicrosoft.com",
"replyUrlsWithType": [
{
"url": "https://jwt.ms/",
"type": "Spa"
},
{
"url": "https://jwt.ms",
"type": "Spa"
},
{
"url": "http://localhost:3000/",
"type": "Spa"
},
{
"url": "http://localhost:3000",
"type": "Spa"
}
],
"requiredResourceAccess": [
{
"resourceAppId": "00000003-0000-0000-c000-000000000000",
"resourceAccess": [
{
"id": "37f7f235-527c-4136-accd-4a02d197296e",
"type": "Scope"
},
{
"id": "7427e0e9-2fba-42fe-b0c0-848c9e6a8182",
"type": "Scope"
}
]
}
],
"samlMetadataUrl": null,
"signInUrl": "http://localhost:3000/",
"signInAudience": "AzureADandPersonalMicrosoftAccount",
"tags": [
"notApiConsumer",
"singlePageApp"
],
"tokenEncryptionKeyId": null
}
天蓝色身份验证-config.tsx
import { Configuration, LogLevel } from '@azure/msal-browser';
const AzureActiveDirectoryAppClientId: any =
process.env.REACT_APP_AZURE_ACTIVE_DIRECTORY_APP_CLIENT_ID;
export const b2cPolicies = {
names: {
signUpSignIn: 'B2C_1_dwsdevuserflow01',
forgotPassword: 'B2C_1_dwsdevuserflow01',
editProfile: 'B2C_1_dwsdevprofileflow01',
},
authorities: {
signUpSignIn: {
authority:
'https://dwsdevb2c.b2clogin.com/dwsdevb2c.onmicrosoft.com/B2C_1_dwsdevuserflow01',
},
forgotPassword: {
authority:
'https://dwsdevb2c.b2clogin.com/dwsdevb2c.onmicrosoft.com/B2C_1_dwsdevuserflow01',
},
editProfile: {
authority:
'https://dwsdevb2c.b2clogin.com/dwsdevb2c.onmicrosoft.com/B2C_1_dwsdevprofileflow01',
},
},
authorityDomain: 'https://dwsdevb2c.b2clogin.com',
// authorityDomain: 'https://login.microsoft.com/common',
};
export const MSAL_CONFIG: Configuration = {
auth: {
clientId: AzureActiveDirectoryAppClientId,
authority: b2cPolicies.authorities.signUpSignIn.authority,
knownAuthorities: [b2cPolicies.authorityDomain],
redirectUri: window.location.origin,
postLogoutRedirectUri: window.location.origin, // Indicates the page to navigate after logout.
navigateToLoginRequestUrl: false,
},
cache: {
cacheLocation: 'sessionStorage',
storeAuthStateInCookie: true,
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.error(message);
return;
case LogLevel.Verbose:
console.error(message);
return;
case LogLevel.Warning:
console.error(message);
return;
default:
break;
}
},
},
},
};
天蓝色身份验证上下文.tsx
import {
PublicClientApplication,
AuthenticationResult,
AccountInfo,
EndSessionRequest,
RedirectRequest,
PopupRequest,
} from '@azure/msal-browser';
import { MSAL_CONFIG } from './azure-authentication-config';
export class AzureAuthenticationContext {
private myMSALObj: PublicClientApplication = new PublicClientApplication(
MSAL_CONFIG,
);
private account?: AccountInfo;
private loginRedirectRequest?: RedirectRequest;
private loginRequest?: PopupRequest;
public isAuthenticationConfigured = false;
constructor() {
// @ts-ignore
this.account = null;
this.setRequestObjects();
if (MSAL_CONFIG?.auth?.clientId) {
this.isAuthenticationConfigured = true;
}
}
private setRequestObjects(): void {
this.loginRequest = {
scopes: ['openid', 'profile'],
prompt: 'select_account',
};
this.loginRedirectRequest = {
...this.loginRequest,
redirectStartPage: MSAL_CONFIG.auth.redirectUri, //window.location.href,
};
}
login(signInType: string, setUser: any): void {
if (signInType === 'loginPopup') {
this.myMSALObj
.loginPopup(this.loginRequest)
.then((resp: AuthenticationResult) => {
this.handleResponse(resp, setUser);
})
.catch((err) => {
console.error(err);
});
} else if (signInType === 'loginRedirect') {
this.myMSALObj.loginRedirect(this.loginRedirectRequest);
}
}
logout(account: AccountInfo): void {
const logOutRequest: EndSessionRequest = {
account,
};
this.myMSALObj.logout(logOutRequest);
}
handleResponse(response: AuthenticationResult, incomingFunction: any) {
if (response !== null && response.account !== null) {
this.account = response.account;
} else {
this.account = this.getAccount();
}
if (this.account) {
incomingFunction(this.account);
}
}
private getAccount(): AccountInfo | undefined {
console.log(`loadAuthModule`);
const currentAccounts = this.myMSALObj.getAllAccounts();
if (currentAccounts === null) {
// @ts-ignore
console.log('No accounts detected');
return undefined;
}
if (currentAccounts.length > 1) {
// @ts-ignore
console.log(
'Multiple accounts detected, need to add choose account code.',
);
return currentAccounts[0];
} else if (currentAccounts.length === 1) {
return currentAccounts[0];
}
}
}
export default AzureAuthenticationContext;
解决方案
在 AzureAD 中导航到 Home => App Registrations > YOUR_APP
在“单页应用程序”下,您应该会看到列出的重定向 URI。据我了解,您的 MSAL_CONFIG 文件中 Auth 下的 redirectUri 值需要与那里列出的 URI 匹配。你确认是这样的吗?根据您的配置,我无法判断“window.location.origin”正在产生什么。
推荐阅读
- sql - 数据长度v/s数据精度
- javascript - 从 "onkeypress" 转换为 "addeventlistener("keypress",()=>{})
- php - Laravel 7 创建多对多迁移时出错
- javascript - 第 4 行的类型错误:回调不是函数 JavaScript 回调
- c# - 影响 Azure 应用服务 (ASP.NET WebApi) 中的并发性的限制因素是什么?
- c++ - 重载的小于运算符返回相反的布尔值
- python-3.x - 如何计算熊猫列中非空元素的数量?
- c++ - 在 C/C++ 中打开位于“/sys/”下的文件时出错
- spring-boot - SpringBootApplication 与 Spring Starter Web 错误
- node.js - 无法在 mongoDb 集合中保存数据:“ReferenceError:模型未定义”