Auth.currentAuthenticatedUser not loading name and family name attributes (and others) from Cognito - react-native

I'm using the Auth.currentAuthenticatedUser method to retrieve the attributes recorded for the logged user from AWS Cognito - but only basic atributes are showing. The ones I want are "name" and "family name", but they don't seem to be loaded in the Promise.
This is only the beggining, but I'm concerned as I will want to retrieve other attributes which are not showing up, like user picture, for instance.
Tried to use currentAuthenticatedUser and currentUserInfo with the same results.
async componentDidMount() {
await Auth.currentAuthenticatedUser({bypassCache: true})
.then ( user => this.setUserInfo( user ) )
.catch( err => console.log(err))
}
CognitoUser {
"Session": null,
"attributes": Object {
"email": "r...#gmail.com",
"email_verified": true,
"phone_number": "+5...",
"phone_number_verified": false,
"sub": "246e9...",
},
"authenticationFlowType": "USER_SRP_AUTH",
"client": Client {
"endpoint": "https://cognito-idp.us-east-2.amazonaws.com/",
"userAgent": "aws-amplify/0.1.x react-native",
},
"deviceKey": undefined,
"keyPrefix": "CognitoIdentityServiceProvider.12ddetjn0c0jo0npi6lrec63a7",
"pool": CognitoUserPool {
"advancedSecurityDataCollectionFlag": true,
"client": Client {
"endpoint": "https://cognito-idp.us-east-2.amazonaws.com/",
"userAgent": "aws-amplify/0.1.x react-native",
},
"clientId": "12ddetjn0c0jo0npi6lrec63a7",
"storage": [Function MemoryStorage],
"userPoolId": "us-east...",
},
"preferredMFA": "NOMFA",
"signInUserSession": CognitoUserSession {
"accessToken": CognitoAccessToken {
"jwtToken": "e...oJPg",
"payload": Object {
"auth_time": 1565137817,
"client_id": "1...6lrec63a7",
"event_id": "c3...-4bd9-ad42-200f95f9921c",
"exp": 15...2,
"iat": 156...5872,
"iss": "https://cognito-idp.us-east-2.amazonaws.com/us-east-...",
"jti": "5483e...544149c42e58",
"scope": "aws.cognito.signin.user.admin",
"sub": "246e93...f4d8e6f4725b",
"token_use": "access",
"username": "r...f",
},
},
"clockDrift": -2,
"idToken": CognitoIdToken {
"jwtToken": "eyJraWQiOiJk...",
"payload": Object {
"aud": "12ddetjn0c0j..rec63a7",
"auth_time": 1565137817,
"cognito:username": "r..",
"email": "r..#gmail.com",
"email_verified": true,
"event_id": "c3ae..200f95f9921c",
"exp": ..2,
"iat": ..2,
"iss": "https://cognito-idp.us-east-2.amazonaws.com/us-east-..",
"phone_number": "+5...3",
"phone_number_verified": false,
"sub": "246e937..f4d8e6f4725b",
"token_use": "id",
},
},
"refreshToken": CognitoRefreshToken {
"token": "eyJjd...",
},
},
"storage": [Function MemoryStorage],
"userDataKey": "CognitoIdentityServiceProvider.12ddetjn0....userData",
"username": "r...ff",
}

To get all user attributes, you may be looking for the Auth.userAttributes() function. To use this you want something like this code:
const authUser = await Auth.currentAuthenticatedUser();
const attributes = await Auth.userAttributes(authUser);
// the next line is a convenience that moves the attributes into
// the authUser object
attributes.forEach((attr) => {
authUser.attributes[attr.Name] = attr.Value;
});
If you're still not getting the attributes you need, take a look here, and you can see that you can enable the reading of other attributes from the Amplify command line.
So, in the root of your project:
Type "amplify update auth" at the console.
Select "Walkthrough the auth configurations"
Step through making all the same selections as you've done before.
When it asks, "Do you want to specify the user attributes this app can read and write?" it's "Y", and then you select the attributes you want to be able to read.
When you finish the wizard, use "amplify push auth"
When that's completed, try re-running.
As an alternative to steps 1-4 above, you can also edit cli-inputs.json in the amplify\backend\auth<your auth config name> directory. It's in "userpoolClientReadAttributes". Simply add the attributes you would like to this array (e.g. "name").
This answer was verified with amplify CLI version 8.1.0.

Related

Authenticating via Okta that uses 2FA

I built a simple asp.net core application and need to authenticate an account that uses MFA in addition to username & password.
The service I'm trying to log into exposes an authentication endpoint described here:
https://developer.okta.com/docs/reference/api/authn/#request-example-for-primary-authentication-with-public-application
When I provide the username and password it returns the expected JSON:
{
"stateToken": "00zQZJ1ZY3Em2401r4T69Dhx35TdF1VTFP5KRTa8ib",
"expiresAt": "2020-05-30T21:11:14.000Z",
"status": "MFA_REQUIRED",
"_embedded": {
"user": {
"id": "00u10vk1torIgBBxxxxx",
"profile": {
"login": "john.doe#email.com",
"firstName": "John",
"lastName": "Doe",
"locale": "en",
"timeZone": "America/Los_Angeles"
}
},
"factors": [{
"id": "ost1g59468dXOddAE0h8",
"factorType": "token:software:totp",
"provider": "OKTA",
"vendorName": "OKTA",
"profile": {
"credentialId": "john.doe#email.com"
},
"_links": {
"verify": {
"href": "https://company.okta.com/api/v1/authn/factors/ost1g59468dXOddxxxxx/verify",
"hints": {
"allow": ["POST"]
}
}
}
}, {
Does anyone know who I can also add 2FA into the request to get it to work?

IdentityServer4 {"error":"invalid_client"}

I am using IdentityServer4 (version 3.0.2.0) and facing no client id issue. The exact error is
ERROR| No client with id 'myclientId' found. aborting
Startup.cs of IdentityServer4 project
services.AddIdentityServer()
.AddDeveloperSigningCredential()
// .AddInMemoryCaching()
.AddInMemoryApiResources(Configuration.GetSection("IdentityServer:ApiResources"))
.AddInMemoryClients(Configuration.GetSection("IdentityServer:Clients"))
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = Convert.ToBoolean(Configuration["CleanUp:IsEnabled"]);
options.TokenCleanupInterval = Convert.ToInt32(Configuration["CleanUp:Interval"]); // interval in seconds
});
Also, I have sha256 converted client_secret in appsettings.json file, sample appsettings.json
"IdentityServer": {
"ApiResources": [
{
"Name": "myapi",
"DisplayName": "my api",
"Scopes": [
{
"Name": "mycustomscope"
},
{
"Name": "openid"
}
],
"ApiSecrets": [
{
"Value": "my sha256 converted secret string",
"Description": "my api"
}
]
}
],
"Clients": [
{
"Enabled": true,
"ClientId": "myclientId",
"AccessTokenLifetime": 100000000,
"ProtocolType": "oidc",
"RequireClientSecret": true,
"IdentityTokenLifetime": 300,
"AuthorizationCodeLifetime": 300,
"ConsentLifetime": 300,
"AbsoluteRefreshTokenLifetime": 2592000,
"SlidingRefreshTokenLifetime": 1296000,
"RefreshTokenExpiration": true,
"AlwaysSendClientClaims": false,
"ClientName": "myclientId",
"ClientSecrets": [
{
"Value": "my sha256 converted secret string",
"Type": "SharedSecret"
}
],
"AllowedGrantTypes": [ "client_credentials", "password" ],
"AllowedScopes": [ "mycustomscope", "openid" ],
"RequireConsent": true
}
]
}
Sample token request from postman/JMeter
url: https://myip:port/myappPool/connect/token
method type: POST
Parameters are:
{
"client_id":"myclientId",
"client_secret": "plaintext secret",
"username":"abcdefghijkl",
"scope":"mycustomscope",
"device_id":"custom property",
"password": "mypassword",
"grant_type":"password",
"app_version":"custom property",
"hashed_value":"custom property"
}
I am posting answer to my own question because I have solved the issue. For me below given field was making an issue. After removing this field, the code ran just fine.
"RefreshTokenExpiration": true
Turns out, IdentityServer4.Models.Client does not have any boolean field named RefreshTokenExpiration but class object.

Docusign : 400 Error "Unable to parse multipart body" when trying to create envelope from Template ID from UI5 application

We are trying to figure out whether Docusign can be used in productive scenarios for our client requirements.
We have a UI5 application which will be used to sign Documents. We have created a template in the demo instance of Docusign.
However when we are trying to create an envelope from the application we are getting 400 Error Unable to parse multipart body. Now the same payload when used in POSTMAN application results in the envelope getting created successfully. The headers passed are also the same.
In Ui5 App :
var settings = {
"async": true,
"crossDomain": true,
"url": "/docusign/envelopes",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "User DnVj27euWrCi4ANoMV5puvxVxYAcUCG3PlkUSpWpC08=, Organization 6ba64ce816dec995b17d04605e329a30, Element X4XuUq/T5UUh2o9xwaamZCCRwOKUCPr1Kv1Nj+qHPj0=",
"Content-Type": "application/json"
},
"data": JSON.stringify({
"status": "sent",
"compositeTemplates": [{
"compositeTemplateId": "1",
"inlineTemplates": [{
"recipients": {
"signers": [{
"email": "johndoe#testmail.com",
"name": "John Doe",
"recipientId": "1",
"roleName": "Signer",
"clientUserId": "12345",
"tabs": {
"textTabs": [{
"tabLabel": "firstName",
"value": "John"
}, {
"tabLabel": "lastName",
"value": "Doe"
}, {
"tabLabel": "phoneNo",
"value": "022-635363"
}, {
"tabLabel": "email",
"value": "test#gmail.com"
}]
}
}]
},
"sequence": "1"
}],
"serverTemplates": [{
"sequence": "1",
"templateId": "0bf97611-a457-4e8e-ac7e-1593c17ba3f6"
}]
}]
})
};
var deferred = $.Deferred();
$.ajax(settings).done(function (response) {
deferred.resolve(response);
}.bind(this)).fail(function (error) {
deferred.reject(error);
}.bind(this));
In Postman :
Help would be greatly appreciated in resolving this issue.
Could you stringify outside of the json settings and perhaps break your call down a little before placing everything in settings.
i.e. Try and re-shape your jquery ajax call:
var headers = {"Authorization": "User DnVj27euWrCi4ANoMV5puvxVxYAcUCG3PlkUSpWpC08=, Organization 6ba64ce816dec995b17d04605e329a30, Element X4XuUq/T5UUh2o9xwaamZCCRwOKUCPr1Kv1Nj+qHPj0=", "Content-Type": "application/json" };
var payload = JSON.stringify({
"status": "sent",
"compositeTemplates": [{
"compositeTemplateId": "1",
"inlineTemplates": [{
"recipients": {
"signers": [{
"email": "johndoe#testmail.com",
"name": "John Doe",
"recipientId": "1",
"roleName": "Signer",
"clientUserId": "12345",
"tabs": {
"textTabs": [{
"tabLabel": "firstName",
"value": "John"
}, {
"tabLabel": "lastName",
"value": "Doe"
}, {
"tabLabel": "phoneNo",
"value": "022-635363"
}, {
"tabLabel": "email",
"value": "test#gmail.com"
}]
}
}]
},
"sequence": "1"
}],
"serverTemplates": [{
"sequence": "1",
"templateId": "0bf97611-a457-4e8e-ac7e-1593c17ba3f6"
}]
}]
});
$.ajax({
"async": true,
"crossDomain": true,
"url": "/docusign/envelopes",
"method": "POST",
"timeout": 0,
"headers": headers,
"data": payload
});
I am sure this will lead you to your final "consolidated" answer.
If the exact same JSON is being sent from Postman and from the UI5 application, then you'll get the same results. But you aren't, so something is different.
Probably the UI5 system is sending the API as a mime multi-part request, but isn't setting the content type for the JSON request part correctly.
To verify: use the DocuSign API logger to see what is being received by DocuSign. Compare between the request being sent from UI5 and from Postman.
To fix: you'll need to set additional UI5 parameters so the request is NOT sent as a multi-part mime message. Or send the multi-part message with the needed settings. See the docs and see a multi-part example.
PS PLEASE post an answer to your question with the solution to your problem (once you've found it) to help others in the future. Thank you!!
I was able to fix the issue by directly using the Docusign API (https://demo.docusign.net/restapi/v2/accounts). I was earlier using the SAP Openconnector to connect to Docusign.
https://api.openconnectors.eu3.ext.hanatrial.ondemand.com/elements/api-v2
Thanks all for the help.
I have run into the very same issue recently, and almost decided to give up, but finally, I have managed to find a way to make it work!
The thing is that you need to execute the Ajax call in the following way:
_createEnvelops: function () {
var deferred = $.Deferred();
var oTemplateData = this._getTemplateData();
var oFormData = new FormData();
oFormData.append('envelope', JSON.stringify(oTemplateData));
var settings = {
"async": true,
"crossDomain": true,
"url": '/docusign/envelopes',
"method": "POST",
"data": oFormData,
processData: false,
contentType: false,
"headers": {
"Authorization": sAuthToken
}
};
$.ajax(settings).done(function (response) {
deferred.resolve(response);
}.bind(this)).fail(function (error) {
deferred.reject(error);
}.bind(this));
return deferred;
},
Maybe it will be useful for someone in the future ;)

Update Account (PUT) Endpoint in new Yodlee API for MFA

Background
I am using the newer Yodlee Aggregation API that differs from what I was previously building off of.
I am currently using this endpoint in the account registration flow to put the MFA response:
PUT /{cobrandName}/v1/providers/{providerAccountId}
My request looks like this:
{
url: `${this.rest}providers/${providerAccountId}`,
headers: {
'Authorization': `cobSession=${self.appToken}, userSession=${token}`
},
form: {
'MFAChallenge': JSON.stringify(newMfa)
}
}
where this.rest is my personal rest url, providerAccountId is the appropriate providerAccountId for the refresh, self.appToken is the current cobrand session token, token is the current user's login token, and newMfa is a JSON object being stringified that matches this profile:
{
"loginForm": {
"mfaTimeout": 94650,
"formType": "questionAndAnswer",
"row": [
{
"id": "SQandA--QUESTION_1--Row--1",
"fieldRowChoice": "0001",
"form": "0001",
"label": "What is the name of your state?",
"field": [
{
"id": "SQandA_QUESTION_1_1",
"name": "QUESTION_1",
"isOptional": false,
"value": "Enter the answer",
"valueEditable": true,
"type": "text"
}
]
},
{
"id": "SQandA--QUESTION_2--Row--2",
"fieldRowChoice": "0001",
"form": "0001",
"label": "What is the name of your first school",
"field": [
{
"id": "SQandA_QUESTION_2_2",
"name": "QUESTION_2",
"isOptional": false,
"value": "Enter the answer",
"valueEditable": true,
"type": "text"
}
]
}
]
}
with the exeption being the value fields of the field object, which have been encrypted with PKI as per instructions.
Issue
However, when I carry out this PUT request, I get this error from Yodlee:
{ errorCode: 'Y803',
errorMessage: 'MFAChallenge or providerParam required',
referenceCode: 'p1460412835654A4Q24t' }
though I clearly have an MFAChallenge parameter in my form. Any ideas on why I could be getting this error if the MFAChallenge is present (and note that it is the only info that is passed through the PUT request other than through headers or url parameters)? I tried putting it through as body data, but that doesn't seem to work, and very few of the API endpoints actually seem to use body over form encoded strings, though there was at least one.
You have to send this information MFAChallenge as part of URL, see below example
https://developer.api.yodlee.com/ysl/restserver/v1/providers/10114184?MFAChallenge=%7B%20%22loginForm%22%3A%20%7B%20%20%20%20%20%22mfaTimeout%22%3A%2094650%2C%20%20%20%20%20%22formType%22%3A%20%22questionAndAnswer%22%2C%20%20%20%20%20%22row%22%3A%20%5B%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%22id%22%3A%20%22SQandA--QUESTION_1--Row--1%22%2C%20%20%20%20%20%20%20%20%20%22fieldRowChoice%22%3A%20%220001%22%2C%20%20%20%20%20%20%20%20%20%22form%22%3A%20%220001%22%2C%20%20%20%20%20%20%20%20%20%22label%22%3A%20%22What%20is%20the%20name%20of%20your%20state%3F%22%2C%20%20%20%20%20%20%20%20%20%22field%22%3A%20%5B%20%20%20%20%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22id%22%3A%20%22SQandA_QUESTION_1_1%22%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22name%22%3A%20%22QUESTION_1%22%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22isOptional%22%3A%20false%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22value%22%3A%20%22Enter%20the%20answer%22%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22valueEditable%22%3A%20true%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22type%22%3A%20%22text%22%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%5D%20%20%20%20%20%7D%2C%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%22id%22%3A%20%22SQandA--QUESTION_2--Row--2%22%2C%20%20%20%20%20%20%20%20%20%22fieldRowChoice%22%3A%20%220001%22%2C%20%20%20%20%20%20%20%20%20%22form%22%3A%20%220001%22%2C%20%20%20%20%20%20%20%20%20%22label%22%3A%20%22What%20is%20the%20name%20of%20your%20first%20school%22%2C%20%20%20%20%20%20%20%20%20%22field%22%3A%20%5B%20%20%20%20%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22id%22%3A%20%22SQandA_QUESTION_2_2%22%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22name%22%3A%20%22QUESTION_2%22%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22isOptional%22%3A%20false%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22value%22%3A%20%22Enter%20the%20answer%22%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22valueEditable%22%3A%20true%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22type%22%3A%20%22text%22%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%5D%20%20%20%20%20%7D%20%5D%20%7D

Loopback unauthorized request when trying to login

I have created a custom user model that inherits form the built-in User model. Then I added a boot script that creates a default user.
User.create([{
username: 'admin',
email: 'email#email.com',
password: 'admin'
}], on_usersCreated);
This creates a document in the monogdb database,. However when I try to login, it send a 401 unauthorized request.
I tried to find the root of the problem, and it seems that loopback cannot fins such user in the database. More specifically, in node_modules/loopback/common/models/user there is this:
self.findOne({where: query}, function(err, user) {
var defaultError = new Error('login failed');
defaultError.statusCode = 401;
....
where
query = { email: "email#email.com" }
But the problem is that it cannot find a user with that email in the database although it does exist.
This is the user.json file
{
"name": "user",
"base": "User",
"idInjection": true,
"properties": {},
"validations": [],
"relations": {},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW"
}
],
"methods": []
}
I managed to solve this issue. As #superkhau stressed out, you should use the custom User model to create the default users.
Additionally, I had to expose the user model API and hide the build-in User API; So in model-config.js
...
"User": {
"dataSource": "db",
"public": false
},
"user": {
"dataSource": "db",
"public": true
},
...
You might have two collections: User and user. In your models, user extends from User. Which model did you use the create the user record?