AWS Cognito:를 생성하는 토큰하고 후 새로 amazon-cognito-id-js SDK

0

질문

나를 구현하는 node.js 백엔드를 사용하여 아마존-cognito-id-js.

내가 원하는 로그인을 만들(사용자 이름,비밀번호)refreshToken(token)Api.

이것은 나의 코드:

import { AuthenticationDetails, CognitoUser, CognitoUserPool, CognitoRefreshToken } from "amazon-cognito-identity-js"


   
public loginWithAmazonCognitoIdentity (username: string, password: string){
        
        var authenticationData = {
        Username : username,
        Password : password,
    };
    var authenticationDetails = new AuthenticationDetails(authenticationData);
    var poolData = { UserPoolId : 'eu-north-1_xxxxxx',
        ClientId : '3al0l3mhcxxxxxqgnp789987'
    };
    var userPool = new CognitoUserPool(poolData);
    var userData = {
        Username : username,
        Pool : userPool
    };
    var cognitoUser = new CognitoUser(userData);
    const user = cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            var accessToken = result.getAccessToken().getJwtToken();
            console.log("token: " + accessToken);
            var refresh = result.getRefreshToken().getToken();
            console.log("RefreshToken: " + refresh);
        },

        onFailure: function(err) {
            console.error(err);
        },

    });

}

이 기능을 반환합니다 accessToken 및 refreshToken 지 않고 오류가 있습니다.

이 후,를 구현하고 있습니다 이 기능:

public refreshToken(refreshToken)
    var poolData = { UserPoolId : 'eu-north-1_xxxxxx',
            ClientId : '3al0l3mhcxxxxxqgnp789987'
            };
            var userPool = new CognitoUserPool(poolData);
    
            var userData = {
                Username : 'lacucudi',
                Pool : userPool
            };
            var cognitoUser  = new  CognitoUser(userData);
            var token = new CognitoRefreshToken({ RefreshToken: refreshToken })
            cognitoUser.refreshSession(token, (err, session) => { if (err) {console.log(err)} else console.log('session: ' + JSON.stringify(session)) });
}

하지만 통과 refreshToken 이전에 검색한 반환합니다:

NotAuthorizedException:잘못된 새로 토큰을 발급합니다.

할 수 있는 사람을 말해 무엇이 올바른 백엔드의 이행 2api?

1

최고의 응답

0

나는 해결에 이 방법:

    import Amplify, { Auth } from "aws-amplify";
    import {
        AdminCreateUserCommand,
        AdminSetUserPasswordCommand,
        AuthFlowType,
        CognitoIdentityProviderClient,
        CognitoIdentityProviderClientConfig,
        GetUserCommand,
        InitiateAuthCommand,
        MessageActionType,
        RevokeTokenCommand,
    } from "@aws-sdk/client-cognito-identity-provider";

    public async login(username: string, password: string): Promise<AuthTokens> {
            if (!username || !password) {
                throw new HttpException(400, "Please provide both username and password");
            }
    
            Amplify.configure({ Auth: config.auth });
    
            const user = await Auth.signIn(username, password);
    
            if (!user.signInUserSession) {
                throw new HttpException(500, `Could not authenticate user ${username}`);
            }
    
            const {
                signInUserSession: {
                    accessToken: { jwtToken: access_token },
                    idToken: { jwtToken: id_token },
                    refreshToken: { token: refresh_token },
                },
            } = user;
    
            return {
                id_token,
                access_token,
                refresh_token,
            };
        }


public async refresh(refresh_token: string): Promise<AuthTokens> {
        if (!refresh_token) {
            throw new HttpException(400, "Please provide a refresh token");
        }

        const refreshTokenAuth = new InitiateAuthCommand({
            ClientId: config.auth.userPoolWebClientId,
            AuthFlow: AuthFlowType.REFRESH_TOKEN_AUTH,
            AuthParameters: {
                REFRESH_TOKEN: refresh_token,
            },
        });
        const response = await this.client.send(refreshTokenAuth);

        const {
            AuthenticationResult: { AccessToken, IdToken },
        } = response;

        return {
            refresh_token,
            access_token: AccessToken,
            id_token: IdToken,
        };
    }


public async logout(refreshToken: string): Promise<boolean> {
        if (!refreshToken) {
            throw new HttpException(400, "Please provide a refresh token");
        }
        try {
            const command = new RevokeTokenCommand({
                ClientId: config.auth.userPoolWebClientId,
                Token: refreshToken,
            });
            const response = await this.client.send(command);
            const { httpStatusCode } = response.$metadata;
            return httpStatusCode == 200 ?? true;
        } catch (e) {
            logger.error(e);
            throw new HttpException(500, e);
        }
    }

내가 사용하는 aws-증폭 로그인 및 aws-sdk/클라이언트-cognito-id-공급자 에 대한 다른 작업입니다.

NotAuthorizedException:잘못된 새로 토큰

오류 메시지가 반환되었기 때문에 장치를 추적하는 옵션을 활성화에 Cognito 설정합니다.

그것은'놀라운 서비스의 AWS 에서 제공하는 제 잘못된 오류 메시지와 매우 작은 그것에 대해 설명서

2021-12-02 15:36:38

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................