![](/img/trans.png)
[英]User object is getting populated but Auth.currentSession is returning "No user found"
[英]Auth.currentSession says no current user
我有一個基本的反應應用程序,我正在嘗試使用 aws-amplify 進行身份驗證。 我在 cognito 中設置了一個用戶池。 我能夠將用戶發送到托管的 ui。 用戶可以登錄,但是當我嘗試獲取當前會話時,我收到一條消息說no current user
。
這是我的代碼。
import React, { Component } from 'react';
import './App.css';
import Amplify, { Auth } from 'aws-amplify';
import awsmobile from "./aws-exports";
const auth = {
AppWebDomain: "funnybusty.auth.us-east-2.amazoncognito.com",
TokenScopesArray: ["phone", "email", "profile", "openid", "aws.cognito.signin.user.admin"],
RedirectUriSignIn: "http://localhost:3000",
RedirectUriSignOut: "http://localhost:3000",
responseType: "token",
ClientId: "aaaaa",
UserPoolId: "aaaa",
};
Amplify.configure(awsmobile);
Auth.configure({ oauth: auth });
class App extends Component {
componentDidMount() {
Auth.currentSession()
.then(data => console.log(data))
.catch(err => console.log(err));
}
click = () => {
const config = Auth.configure().oauth
const url = 'https://' + config.AppWebDomain + '/login?redirect_uri=' + config.RedirectUriSignIn + '&response_type=' + config.responseType + '&client_id=' + config.ClientId;
window.location.assign(url);
}
render() {
return (
<div className="App">
<button onClick={this.click}>
Sign in with AWS
</button>
</div>
);
}
}
export default App;
我哪里錯了?
我從未使用過 reactjs,但我注意到一些事情:
signIn
事件。 否則,您將無法取回您的用戶信息。redirectSignIn
和redirectSignOut
(最后的/
很重要,我是通過艱難的方式學到的..) 您可能必須將ClientId
和UserPoolId
從const auth 中移出,因為 oauth 配置的模式是:
const oauth = { domain: 'your_cognito_domain', scope: ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin'], redirectSignIn: 'http://localhost:3000/', redirectSignOut: 'http://localhost:3000/', responseType: 'code' // or token };
有關更多信息,您可以查看文檔中提供的完整示例: https : //aws-amplify.github.io/docs/js/authentication#make-it-work-in-your-app
我知道這是一個舊線程,但我會回答其他有此問題的人。
我讀到在componentDidMount()
中調用Auth.currentSession()
並不是一個好的做法。 嘗試在異步函數中調用它並將await
放在Auth.currentSession()
之前。
例子 :
import { withAuthenticator } from 'aws-amplify-react'
import Amplify, { Auth } from 'aws-amplify';
Amplify.configure(aws_exports);
class App extends Component {
constructor(props) {
super(props);
this.state = {
postId: null
};
}
async example() {
let user = await Auth.currentSession().then(data =>
console.log(data));
}
render() {
return (
<div className="App">
<h5 className="card-header">Simple POST Request</h5>
<div className="card-body">
</div>
<button onClick={this.example}>
Req1!
</button>
</div>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.