用户未通过身份验证(放大)

我正在使用 aws-amplify 和 typescript 将后端 API 构建为 NPM 包。包装所有功能效果很好。但我在加载 currentSignedIn 用户时遇到问题。

我的登录脚本:

import {Auth} from "aws-amplify";
import "../app.config";
import {SignInOpts} from "@aws-amplify/auth/src/types";
import {CognitoUser} from "amazon-cognito-identity-js";

/**
 * @name SignIn
 * @description:
 *      sign in with username, password.
 *
 * @type function
 * @async
 * @param {string} usernameOrSignInOpts the email of the user
 * @param {string} pw the password of the user
 * @return {Promise<CognitoUser | any>}
 */
const SignIn = async (
    usernameOrSignInOpts: string | SignInOpts,
    pw?: string
): Promise<CognitoUser | any> => {
   try {
       return await Auth.signIn(usernameOrSignInOpts, pw);
   } catch (err) {
       throw err;
   }
}

export {
    SignIn
}

export default SignIn;

在此之后我尝试使用登录功能(在我注册了一个新用户并得到确认之后)。但它确实捕获了一个错误:“用户未通过身份验证”。

我搜索了很多,但没有找到我的问题的答案。

我的配置文件:

import Amplify from 'aws-amplify';
import awsExports from './aws-exports';
import * as dotenv from 'dotenv';

Amplify.configure(awsExports);
dotenv.config();

登录工作的脚本:

import {SignUp, ConfirmSignUp, ResendSignUp} from "./Authentication/SignUp";
import SignIn from "./Authentication/SignIn";
import Validator from "./Services/Validator";
import {RegexPatterns, RegexTypes} from "./Enums/Regex";
import SignOut from "./Authentication/SignOut";
import DeleteUser from "./Authentication/DeleteUser";
import UserManagement, {ChangePassword} from "./Authentication/UserManagement";
import "./app.config";
import {Auth} from "aws-amplify";
import NotAuthorizedException from "./Exceptions/NotAuthorizedException";

export default {
    SignIn,
    SignUp,
    SignOut,
    ConfirmSignUp,
    ResendSignUp,
    Validator,
    UserManagement,
    RegexPatterns,
    DeleteUser,
}

SignIn('xxxxxx', 'xxxx').then(() =>
    Auth.currentAuthenticatedUser()
    .then(authenticatedUser => {
        console.log(authenticatedUser);
    }).catch(err => {
        throw new NotAuthorizedException(err);
}));

但是,如果我将登录功能和 cuurentAuthenticatedUser 分开,我会收到错误消息。我的问题是登录是否会在某处为用户保存会话?我希望能够在我的应用程序的另一个文件中调用 cuurentAuthenticatedUser 并获取当前用户。

简而言之,为什么登录功能无法保存与我登录用户的会话?我只能在同一运行时登录,之后用户未通过身份验证。

请帮忙!

stack overflow The user is not authenticated (amplify)
原文答案

答案:

作者头像

您可以使用 useAuthenticator 钩子在反应功能组件中检查登录用户。

import { useAuthenticator } from '@aws-amplify/ui-react';

const Home = () => {
  const { user, signOut } = useAuthenticator((context) => [context.user]);

  return <button onClick={signOut}>Welcome, {user.username}!</button>;
};

您可以使用 useAuthenticator 挂钩来访问代表当前 authStateroute 字符串。

import { useAuthenticator } from '@aws-amplify/ui-react';

const App = () => {
  const { route } = useAuthenticator(context => [context.route]);

  // Use the value of route to decide which page to render
  return route === 'authenticated' ? <Home /> : <Authenticator />;
};
作者头像

操作,您可能需要添加一个条件语句,如下所示:

if (!authenticatedUser) return <Authenticator /> (or your custom sign in component);

相关问题