获取 AWS Amplify UI React 中的 AWS Cognito 令牌。

huangapple go评论76阅读模式
英文:

Getting aws cognito token in aws-amplify ui-react

问题

I'm currently working in a Next.js frontend and NestJS backend application, and I'm 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 the 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 tried to get the token from local storage, but the key always changes because of the pool id and the user.

英文:

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 &#39;aws-amplify&#39;;
import { withAuthenticator } from &#39;@aws-amplify/ui-react&#39;;
import &#39;@aws-amplify/ui-react/styles.css&#39;;

import awsExports from &#39;./aws-exports&#39;;
Amplify.configure(awsExports);

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

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}`,
        &#39;Content-Type&#39;: &#39;application/json&#39;,
      },
      data,
    })

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

答案1

得分: 0

以下是翻译好的部分:

"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:

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:

Once you log in - you see the app:

Look at the code in this example:

React code is here:

Backend example is here:"

英文:

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:

获取 AWS Amplify UI React 中的 AWS Cognito 令牌。

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:

获取 AWS Amplify UI React 中的 AWS Cognito 令牌。

Once you log in - you see the app:

获取 AWS Amplify UI React 中的 AWS Cognito 令牌。

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

答案2

得分: 0

以下是您要翻译的内容:

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,
      }
    );
  }
}

请注意,代码部分已经被保留为原文,不进行翻译。

英文:

Don't know exact syntax about Next.js, but this is how I did in Angular (TypeScript).

ProfileComponent.ts

import { Component } from &quot;@angular/core&quot;;
import { Auth } from &quot;aws-amplify&quot;;
import { UserService } from &quot;src/app/services/user.service&quot;;

@Component({
  selector: &quot;app-profile&quot;,
  templateUrl: &quot;./profile.component.html&quot;,
  styleUrls: [&quot;./profile.component.sass&quot;],
})
export class ProfileComponent {

  constructor(private userService: UserService) {

    Auth.currentSession().then((response) =&gt; {

      var idToken = response.getIdToken().getJwtToken();

      this.userService.getUserInfo(idToken).subscribe((response) =&gt; {
        console.log(response);
      });

    });
  }
}

UserService.ts

export class UserService {

  constructor(private http: HttpClient) {}

  public getUserInfo(accessToken: string): Observable&lt;Weather[]&gt; {

    var headers_object = new HttpHeaders().set(&quot;Authorization&quot;, &quot;Bearer&quot; + accessToken);

    return this.http.get&lt;Weather[]&gt;(
      &quot;https://xxxxx.execute-api.ap-south-1.amazonaws.com/prod/User&quot;,
      {
        headers: headers_object,
      }
    );
  }
}

huangapple
  • 本文由 发表于 2023年5月18日 05:26:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276307.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定