“redirect_uri”对于 Microsoft 登录 MSAL 身份验证 Azure 无效

时间:2021-06-10 20:30:07

标签: reactjs typescript azure azure-active-directory msal

在 Azure AD B2C 上使用 Microsoft 登录时出现以下错误:

<块引用>

invalid_request:为输入参数“redirect_uri”提供的值无效。预期值是一个 URI,该 URI 与为此客户端应用程序注册的重定向 URI 匹配。

我可以联系其他提供商并使用电子邮件登录,而不是 Microsoft .. 哈哈。

我已经搜索了几个小时并尝试了我能想到的所有方法,希望其他人可以帮助确定问题。最初我只能使用 https://login.microsoft.com/common 或类似的东西让 Microsoft 登录工作,但没有使用我的用户流/允许其他提供者。现在,我的应用程序中的用户流正在运行,我无法通过 Microsoft 登录。下面是我的配置和代码。

我最初在这里学习了 Microsoft 教程:

<块引用>

https://docs.microsoft.com/en-us/azure/developer/javascript/tutorial/single-page-application-azure-login-button-sdk-msal

然后将其他人拼凑起来以使其使用我的用户流来执行,并且它除了使用 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

}

azure-authentication-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;
        }
      },
    },
  },
};

azure-authentication-context.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;

1 个答案:

答案 0 :(得分:0)

在 AzureAD 中导航到 Home => App Registrations > YOUR_APP

在“单页应用程序”下,您应该会看到列出的重定向 URI。我的理解是,您 MSAL_CONFIG 文件中 Auth 下的 redirectUri 值需要匹配此处列出的 URI。你确认是这样吗?我无法根据您的配置判断“window.location.origin”正在生成什么。