我使用 React、Cognito 用户池、Azure AD 为内部单页应用程序实现身份验证。
有很多信息,我无法将各个点连接起来以使整个应用程序正常工作。
我已设置 AWS Cognito 用户池和 Azure AD。我关注了https://aws.amazon.com/blogs/security/how-to-set-up-amazon-cognito-for-federated-authentication-using-azure-ad/
在 React 方面,我遵循 Amplify 的指南 https://docs.amplify.aws/javascript/build-a-backend/auth/add-social-provider/#full-samples 我有“aws-amplify”:“^6.0.4”,
import React, { useEffect, useState } from "react";
import { Amplify } from "aws-amplify";
import { Hub } from "aws-amplify/utils";
import { signInWithRedirect, signOut, getCurrentUser } from "aws-amplify/auth";
import { AuthUser } from "aws-amplify/auth";
Amplify.configure({
Auth: {
Cognito: {
// Amazon Cognito User Pool ID
userPoolId: "XX-xxxx-#_XXXXXXXXXX",
// OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
userPoolClientId: "xxxxxxxxxxxxxxxxxx",
// REQUIRED only for Federated Authentication - Amazon Cognito Identity Pool ID
// identityPoolId: "XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab",
// OPTIONAL - This is used when autoSignIn is enabled for Auth.signUp
// 'code' is used for Auth.confirmSignUp, 'link' is used for email link verification
signUpVerificationMethod: "code", // 'code' | 'link'
loginWith: {
// OPTIONAL - Hosted UI configuration
oauth: {
domain:
"https://my-userpool.auth.us-east-2.amazoncognito.com",
scopes: ["email", "openid"],
redirectSignIn: ["http://localhost:3000/"],
redirectSignOut: ["http://localhost:3000/"],
responseType: "code", // or 'token', note that REFRESH token will only be generated when the responseType is code
},
},
},
},
});
export default function RootApp() {
const [user, setUser] = useState<AuthUser | null>(null);
useEffect(() => {
const unsubscribe = Hub.listen("auth", ({ payload }) => {
switch (payload.event) {
case "signInWithRedirect":
getUser();
break;
case "signInWithRedirect_failure":
console.log("An error has ocurred during the Oauth flow.");
break;
}
});
getUser();
return unsubscribe;
}, []);
const getUser = async (): Promise<void> => {
try {
const currentUser = await getCurrentUser();
setUser(currentUser);
} catch (error) {
console.error(error);
console.log("Not signed in");
}
};
return user !== null ? (
<AuthenticatedApp user={user}></AuthenticatedApp>
) : (
<UnauthenticatedApp />
);
}
function UnauthenticatedApp() {
return (
<div>
<div className="App">
<button
onClick={
() =>
signInWithRedirect({ provider: { custom: "MyAD" } }) //MyAD is identity provider name in AWS cognito
}
>
Log in
</button>
</div>
</div>
);
}
interface Props {
user: AuthUser;
}
function AuthenticatedApp({ user }: Props) {
return (
<div>
<button onClick={() => signOut()}>Sign Out</button>
<div>{user?.username}</div>
</div>
);
}
如果有人能指出正确的方向来解决这个问题,我真的很感激。
尝试从域中删除“https://”:“https://my-userpool.auth.us-east-2.amazoncognito.com”,并验证 Amplify.configure({Auth: { Cognito: {...}}}) 与您在 Cognito 应用程序客户端中配置的完全相同(https 与 http 等)。