amazon-archives / amazon-cognito-auth-js

The Amazon Cognito Auth SDK for JavaScript simplifies adding sign-up, sign-in with user profile functionality to web apps.
Apache License 2.0
424 stars 232 forks source link

Redirected back with access and id tokens, but seemed to be logged out #164

Closed YoniH closed 5 years ago

YoniH commented 5 years ago

After logging in in the hosted UI page, I am redirected back to my page with access token and id token, which is good. But then I call some sdk methods and it seems that I'm not logged in: auth.isUserSignedIn() -> false auth.getCurrentUser() -> null auth.getSignInUserSession() -> all tokens are empty strings auth.getUserContextData() -> undefined

Here's my code (React):

import React, { Component } from 'react';
import { CognitoAuth } from 'amazon-cognito-auth-js';

const authData = {
    ClientId: '<my client id>',
    AppWebDomain: '<my domain>',
    TokenScopesArray: ['profile','openid'],
    RedirectUriSignIn: 'http://localhost:3000',
    RedirectUriSignOut: 'http://localhost:3000',
        UserPoolId: '<my pool id>'
};

class App extends Component {
  constructor() {
    super();

    this.auth = new CognitoAuth(authData);

    this.handleSignIn = this.handleSignIn.bind(this);
    this.handleSignOut = this.handleSignOut.bind(this);
    this.test = this.test.bind(this);
  }

  handleSignIn() {
    this.auth.getSession();
  }

  handleSignOut() {
    this.auth.signOut();
  }

  test() {
    console.log(this.auth.isUserSignedIn());
    console.log(this.auth.getCurrentUser());
    console.log(this.auth.getSignInUserSession());
    console.log(this.auth.getUserContextData());
  }

  render() {
    return (
      <div>
        <button onClick={this.handleSignIn}>SignIn</button>
        <button onClick={this.handleSignOut}>SignOut</button>
        <button onClick={this.test}>Test</button>
      </div>
    );
  }
}

export default App;

What am I doing wrong?

chamathsilva commented 5 years ago

Once you redirected back to the page with the access token and id token, you have to call following method.

var curUrl = window.location.href;
auth.parseCognitoWebResponse(curUrl) 

Note : curUrl is your redirected url with the access token and id token

YoniH commented 5 years ago

Thanks! I missed that. It's working now

CalvinWang-Mel commented 4 years ago

Once you redirected back to the page with the access token and id token, you have to call following method.

var curUrl = window.location.href;
auth.parseCognitoWebResponse(curUrl) 

Note : curUrl is your redirected url with the access token and id token

This works! thanks