PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label amazon-cognito. Show all posts
Showing posts with label amazon-cognito. Show all posts

Thursday, October 20, 2022

[FIXED] How to use AWS Cognito as a provider in Passport?

 October 20, 2022     amazon-cognito, idp, oauth-2.0, passport.js     No comments   

Issue

I have a Javascript backend (NestJS with Express + Passport).

I would like to outsource the complexity of authentication (e.g. social auth) to Cognito but avoid getting locked in. I was wondering if I can use Cognito as a provider in Passport, similar to social providers (Google, Facebook, etc). That way, I could integrate many providers with the effort of integrating just one. I would still manage user data, authorization, etc in my own app, therefore, if I wanted to in the future, I could implement Google, Facebook, etc. social auth in my own app and get rid of Cognito.

If I understand it correctly this is possible with Auth0.

Ideally, I would like to implement an OAuth flow where the user is redirected to a simple "sign up / log in" Cognito app, logs in, gets redirected to a callback URL in my app where I receive user data. If AWS doesn't host a solution for this, I can also use their UI elements to build & host this app.

If implemented as a provider / strategy, this could be as simple as:

passport.use(new CognitoStrategy({
    key: KEY,
    secret: SECRET,
    callbackURL: "http://www.example.com/auth/cognito/callback"
  },
  function(token, tokenSecret, profile, done) {
      User.findOrCreate({ uuid: profile.id }, function (err, user) {
        return done(err, user);
      });
  }
));

app.get('/auth/cognito', passport.authenticate('cognito'));
app.get('/auth/cognito/callback', 
  passport.authenticate('cognito', { failureRedirect: '/auth/cognito' }),
  function(req, res) {
    res.redirect('/');
  });

Is there a solution for this? Does this make sense in principle? Am I missing any complexity in the many-for-one idea?

Related resources:

  • https://github.com/aws-amplify/amplify-js/tree/master/packages/amazon-cognito-identity-js
  • https://brightinventions.pl/blog/using-cognito-with-nest-js
  • NestJs/Angular/Cognito flow

Solution

It's possible to use both User Pools and Identity Pools via OAuth. Cognito even has a self-hosted UI, with own domain & branding available. Setup steps: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-integration.html

I used a generic OAuth2 Passport strategy: https://github.com/jaredhanson/passport-oauth2

Endpoint details: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html

After the setup, Federated Identities can be set up from the AWS console.

In the end an unbranded screen looks like this:

enter image description here



Answered By - thisismydesign
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 4, 2022

[FIXED] How to set sign up with email or phone-number option in AWS Cognito?

 September 04, 2022     amazon-cognito, amazon-web-services, authentication     No comments   

Issue

How to set sign up with email or phone-number option in AWS Cognito?

So I would like to have a simple sign-up. I want users to sign-up with username, email/phone-number, password and repeat password. How can I configure the ability to make it that either email or phone-number is required?


Solution

A way to require attributes conditionally is to have them as not required in the User Pool settings and define a Pre sign-up Lambda trigger function that will verify the presence of at least one of the fields at Sign up, and reject if none is provided (similar to this example):

exports.handler = (event, context, callback) => {
    // Impose a condition that the email or phone_number is provided.
    var userAttributes = event.request.userAttributes;
    if (!userAttributes.email && !userAttributes.phone_number) {
        var error = new Error("Cannot register users without email or phone number");
        // Return error to Amazon Cognito, fail sign up
        callback(error, event);
    }
    // Return to Amazon Cognito, proceed with sign up
    callback(null, event);
};


Answered By - ammendonca
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 16, 2022

[FIXED] How to config Cognito to get Facebook Login to pass back picture url included?

 July 16, 2022     amazon-cognito, aws-amplify, facebook-login     No comments   

Issue

Recently I had configure to use amplify with @aws-amplify/ui-react library to login Federated users.

Once login, for google user, I would get payload like

{
  "id": "",
  "email": "",
  "name": "",
  "picture": "",
  "token": ""
}

Yet for facebbook user, I get similar stuff but no picture info

{
  "id": "",
  "email": "",
  "name": "",
  "token": ""
}

I had tried to update config enter image description here in my Cognito for Facebook provider. However, this failed to get picture info for me.

Is it possible to make amplify's federated login through Facebook to pass me back picture info as well? I know I could just call another Facebook api to retrieve picture, but I wish this could be avoided, since Google login would return picture info automatically.

P.S. Here's my Facebook identity providers config: enter image description here

PPS. Here's my recent Cognito attribute mapping config:

For Facebook: enter image description here and in CognitoUserSession's idToken's payload: the picture field would include a JSON object about profile picture's information enter image description here

For Google, much simpler: enter image description here and the payload: the picture field is simply the image link enter image description here


Solution

Assuming you're requesting public_profile, use "picture" from Facebook Attribute is actually correct, I do face similar problems that I couldn't receive it until i delete the userpool, and creating a new one.

The value you will get from picture should be something like this

{
    "data": {
        "height": 50,
        "is_silhouette": false,
        "url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?etcetcetcetc",
        "width": 50
    }
}


Answered By - xion
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is my amplify federated sign-in in react native adding an extra 'https'?

 July 16, 2022     amazon-cognito, aws-amplify, facebook-login, google-signin, react-native     No comments   

Issue

I am using a manual auth configuration in my react native app to add OAuth to my react native app. I have followed all of the steps outlined here for Google and Facebook.

My problem is when I click on the button I have created in the front-end that redirects me to a federated sign-in, there is an extra 'https' in the link.

In AWS Cognito User Pools, my sign in and sign out URLS are set to myapp:// and have configured my hosted UI in the AWS console. I have also set the hosted UI url to the OAuth Redirect URI's in both facebook and google for my app clients.

This is my aws configuration in react native:

export default awsConfig = {
    Auth: {
      "aws_project_region": "us-west-2",
      identityPoolId: 'us-east-1:*******',
      region: 'us-east-1',
      userPoolId: '************'
      userPoolWebClientId: '*************'
      oauth: {
        domain: "https://myapp.auth.us-east-1.amazoncognito.com",
        scope: [
            "email",
            "openid",
        ],
        redirectSignIn: process.env.NODE_ENV === "myapp://",
        redirectSignOut: process.env.NODE_ENV === "myapp://",
        responseType: "code"
      },
      federationTarget: "COGNITO_USER_POOLS"
    }
}

In my case, the problem occurs when I click either the "Sign in with Facebook" or "Sign in with Google" buttons.

iOS React Native App

This is what comes up when I click either link:

Safari cannot open page

and the whole url is https://https//aspen-dev.auth.us-east-1.amazoncognito.com/oauth2/authorize?redirect_uri=false&response_type=code&client_id=****&identity_provider=Google&scope=email%20openid&state=****&code_challenge=xQX-****&code_challenge_method=S256

As you can see, there is an extra https, and I don't know what is causing it.


Solution

in awsConfig, I took out the 'https://' of the oauth.domain and now it is working



Answered By - Dane B
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, May 17, 2022

[FIXED] How To Verify Access Token on Server

 May 17, 2022     amazon-cognito, php     No comments   

Issue

So I want to create a game, but I don't want to store user sensitive data on my server (due to new laws ... etc). So I thought cognito might work out well. I read this article of a possible setup https://aws.amazon.com/blogs/gametech/how-to-set-up-player-authentication-with-amazon-cognito/. So I am trying to setup authentification were the client fetches tokens from cognito, and then the server will allow the user call certain functions if it can verify that token.

One thing that confused me is that in the c++ code sample they provided is they verified the client obtained access_token by calling getUserRequest.SetAccessToken(accessToken); to set and ultimately verify the token on the server. Well, in my server I am using php, and I cannot find anything in the sdk to set the access token like this (I looked here https://github.com/aws/aws-sdk-php/tree/master/src). However after doing some research on verifying access_tokens from cognito, I found this article https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html. This article states that access tokens are just JWTs, and you could verify them with a 3rd party JWT library. So I am a little confused... Should I find a function in the aws sdk that verifies the access token on the server, or should I just verify the JWT on its own? In the c++ example, the server also set up a cognito client, is this required to ensure the token is refreshed when it expires?

Thanks for any help.


Solution

You can use the getUser method in the amazon PHP SDK

https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html

Example:

$client = new CognitoIdentityProviderClient([
    'version' => '2016-04-18',
    'region' => '<aws region>',
]);

try {
    $user = $client->getUser([
        'AccessToken' => '<access_token>',
    ]);
} catch (\Aws\CognitoIdentityProvider\Exception\CognitoIdentityProviderException $e) {
    var_dump($e);
}


Answered By - atymic
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing