skip to Main Content

Im currently working in a Next.js frontend and NestJS backend application and im setting the login component with the @aws-amplify/ui-react:

like in the documentation
https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/#option-1-use-pre-built-ui-components

import { Amplify } from 'aws-amplify';
import { withAuthenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';

import awsExports from './aws-exports';
Amplify.configure(awsExports);

function App({ signOut, user }) {
  return (
    <>
      <h1>Hello {user.username}</h1>
      <button onClick={signOut}>Sign out</button>
    </>
  );
}

export default withAuthenticator(App);

The problem is how can i get the jwt token and pass it to axios header?

    const response: any = await axios({
      method: method as Method,
      url: `http://localhost:3001/dev/${query}`,
      headers: {
        Authorization: `Bearer ${jwtToken}`,
        'Content-Type': 'application/json',
      },
      data,
    })

i`ve try to get the token from local storage but the key aways change because of the pool id and the user.

2

Answers


  1. Look at the Example PAM app. It uses a React app and uses Cognito to autheniate users. This app does not use amplify. It uses React, Cloudscape Design System, and the AWS SDK and makes requests to API Gateway endpoints:

    enter image description here

    As you can see in this illustration, the React app lets a user log in via a Cognito call. This app uses a token returned from Cognito. Once you understand that – you can apply it to your projects.

    After you follow the instructions in this example, you get the full app which includes a login screen:

    enter image description here

    Once you log in – you see the app:

    enter image description here

    Look at the code in this example:

    React code is here:

    https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/clients/react/elros-pam

    Backend example is here:

    https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files

    Login or Signup to reply.
  2. Don’t know exact syntax about Next.js, but this is how I did in Angular (TypeScript).

    ProfileComponent.ts

    import { Component } from "@angular/core";
    import { Auth } from "aws-amplify";
    import { UserService } from "src/app/services/user.service";
    
    @Component({
      selector: "app-profile",
      templateUrl: "./profile.component.html",
      styleUrls: ["./profile.component.sass"],
    })
    export class ProfileComponent {
    
      constructor(private userService: UserService) {
    
        Auth.currentSession().then((response) => {
    
          var idToken = response.getIdToken().getJwtToken();
    
          this.userService.getUserInfo(idToken).subscribe((response) => {
            console.log(response);
          });
    
        });
      }
    }
    

    UserService.ts

    export class UserService {
    
      constructor(private http: HttpClient) {}
    
      public getUserInfo(accessToken: string): Observable<Weather[]> {
    
        var headers_object = new HttpHeaders().set("Authorization", "Bearer" + accessToken);
    
        return this.http.get<Weather[]>(
          "https://xxxxx.execute-api.ap-south-1.amazonaws.com/prod/User",
          {
            headers: headers_object,
          }
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search