score:1
import { auth } from "aws-amplify";
import {
cognitousersession,
cognitoidtoken,
cognitorefreshtoken,
cognitoaccesstoken,
} from "amazon-cognito-identity-js";
/**
* injects an access token, id token, and refresh token into aws amplify for idenity and access
* management. cognito will store these tokens in memory and they will persist upon requesting
* additional pages from the same domain.
*
* calling this method should have the same effect as signing in with auth.signin(). when an
* id or access token expires, cognito will automatically retrieve new ones using the refresh
* token passed.
*
* note: token injection is not "officially" supported by amplify. the only forms of sign-in
* amplify supports are username & password or federated sign-in.
*
* @param accesstoken the access token to be injected. access tokens grant access to resources.
* @param idtoken the id token to be injected. id tokens contain claims about identity.
* @param refreshtoken the refresh token to be injected. refresh tokens can obtain new access
* and id tokens for a long period of time (usually up to a year).
*/
const injecttokensintoamplify = (accesstoken: string, idtoken: string, refreshtoken: string) => {
const session = new cognitousersession({
idtoken: new cognitoidtoken({
idtoken: idtoken,
}),
refreshtoken: new cognitorefreshtoken({
refreshtoken: refreshtoken,
}),
accesstoken: new cognitoaccesstoken({
accesstoken: accesstoken,
}),
});
auth.credentials.set(session, "session");
// the function createcognitouser is private in amplify. so, we need to cast it
// in order to call it.
const currentuser = (auth as any).createcognitouser(session.getidtoken().decodepayload()["cognito:username"]);
// this calls cachetokens() in cognito sdk. assigns the tokens to the local identity.
currentuser.setsigninusersession(session);
};
score:2
there's a (now private) function on auth that seems to handle this situation, _handleauthresponse
.
pass the returned url that you get after a successful login, that includes the token to the function.
as it is a private function, it needs this workaround to access _handleauthresponse:
urlwithtoken = 'https://localhost:4200/login#access_token=[access_token]&id_token=[id_token]&state=[state]&token_type=bearer&expires_in=3600'
(auth as any)._handleauthresponse(urlwithtoken)
i'm not sure how many of the parameters are necessary, as these are the ones included in the login redirect that we're getting back from a federated signin.
in our application we're then using a hub listener to obtain the user details:
hub.listen('auth', ({ payload: { event, data } }) => {
console.log('hub:', event);
console.log('hubdata:', data);
if (event == 'signin' && data != undefined) {
//data is a user object
}
});
this is the reference used to piece this together: https://github.com/aws-amplify/amplify-js/issues/4955
Source: stackoverflow.com
Related Query
- Configure Amplify to use existing Cognito token
- AWS - Get user token from an existing Cognito User Pool with username and password on an existing React web app
- How to use refresh token in reactjs
- Use MapBox GL JS without Access Token
- RxDB - Use the existing local DB
- is it safe to use react js state to store token of authenticated user?
- How to use Turborepo for an existing react app created with Create React App in order to make it a monorepo?
- Use Auth0's hook useAuth0 to get token and set header in Apollo client
- How to get new token from Cognito from the frontend?
- How to Use AWS Amplify react components anywhere in an application
- Is it possible to use only Amplify Auth in a react app in isolation?
- Is there a way to use styled-components in a React app, without renaming all existing components?
- AWS amplify cognito users
- AWS amplify google sigin with react doesn't automatically refresh token after 1 hour?
- Persist AWS Cognito User with Amplify
- SyntaxError: Unexpected token export when trying to use @babel/register
- msal in React SPA - use access token received from AcquireTokenRedirect
- Refresh Cognito access token after adding user to a Cognito
- I am not able to use ecma6 import in my code getting error "unexpected token import "
- How to configure Office-js excel react add-in to use react-router-dom or alternative solutions?
- Best way to check if there is already a token in local storage using use effect in React Context
- Amplify - How to setup congnito to use email as username?
- How to use Webpacker for React on an existing Rails 5.0.2 application?
- Unexpected Token - Jest for existing React + Web-pack app
- Configure existing project on reactJS
- Is that safe use jwt decode to decode token in react js?
- ReactJS - use iframe to silently renew token
- Right way to use JWT auth token in React Redux app
- "Failed to Compile" "Parsing error: Unexpected token :" during attempt to migrate to typescript in existing create-react-app
- How do you use react-router-dom to redirect user when token has expired?
More Query from same tag
- How to know if react-router can go back to display back button in react app
- Display issue with CSS
- Handle state variable initialization
- How to use usehook in a function using react and typescript?
- I cant get Redux state Change to Rerender component if the state value is the same
- Y scroll event listener useEffect
- react toggle menu, styling the button different on click
- change background color of component on hover
- Firebase user.updateProfile({...}) not working in React App
- React collapse not working after navbar set to fixed
- React 0.14 - using react-router
- How to use a page as a background in React
- Higher Order Components, Props with Formik & GatsbyJS
- Callback when DOM is loaded in react.js
- WebStorm use wrong @types definition file?
- Firebase returning null references when GET after DELETE
- Conditionally applying className to a react component depending on where the component is used
- React children functional props not working
- SCSS compilation issue in @material/button/_mixins.scss
- Mock forwardRef components jest mockImplementation with typescript
- How to setState in child component when child function called from parent component in ReactJS
- Lodash to find if object property exists in array
- React router v6 : update url param in Link
- connecting react frontend with node js rest api
- Material-ui Card component's shadows and bottom get clipped when within GridList
- React-Native How to handle onPress from Item in flatlist ???
- When to use inputRef.current instead of this.inputRef React.js?
- React child state update based on parent's prop change
- Google Maps API; "CORS header ‘Access-Control-Allow-Origin’ missing" error
- Manipulating JSX element's children collection