jonsaw / amazon-cognito-identity-dart Goto Github PK
View Code? Open in Web Editor NEWUnofficial Amazon Cognito Identity Provider Dart SDK, to easily add user sign-up and sign-in to your mobile and web apps with AWS.
License: MIT License
Unofficial Amazon Cognito Identity Provider Dart SDK, to easily add user sign-up and sign-in to your mobile and web apps with AWS.
License: MIT License
Whenever i log in an user with authenticateUser(), I can get the user's info by calling getCurrentUser() as long as the app is still running. However, when the app is relaunched, getCurrentUser() will always return null and thus user will have to login again
Hi,
iam using the HTTP Presigned Post to Upload Files to S3. I copied your example and the Upload is working quite well, except the response. In my Case the Stream is fully empty and i cant see if the Upload was ok or not.
set MediaType(image,png) in http.MultipartFile
http.MultipartFile('file', stream, length, filename: path.basename(file.path), contentType: MediaType(mimeTypeData[0], mimeTypeData[1]))
doesnot work.
It seems to set something like " res.fields['Content-Type'] = 'image/png'; "
but I am not familiar aws .
Please help out here!
Thank you
Hi there,
trying to implement your aws package to my app. Using the sample code with my aws credentials throws error "'An unknown client error occured';
"
"'An unknown client error occured';" is thrown due to following error:
'cognito-idp.us-east-1.amazonaws.com';
https://cognito-idp.us-east-1.amazonaws.com is the official aws endpoint for cognito in my region.
Anyone facing the same problem or has a clue how to fix it?
Thank you so much!
EDIT: I don't know why but after reopening Android Studio it worked. Magic ...
I would like to have a two step sign-up. First the user should enter it's E-Mail. If the E-Mail is already known, the user should be asked for his password. If the user is unknown, it should show the password and password_confirmation field. Is this possible?
The only way I found is to use a wrong password and then catch the error:
userPool.signUp('[email protected]', 'veryunlikelypassword');
-----
ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: CognitoClientException{statusCode: 400, code: UsernameExistsException, name: UsernameExistsException, message: An account with the given email already exists.
But this doesn't seem right. Is there an alternative?
EDIT: Stupid from my side. That would register the user with that password 🤦♂️
if the cognito session (namely the accesstoken/idtoken) is not valid (_session.isValid()
) I get a new token in exchange for the refreshtoken by calling _cognitoUser.getSession()
. This is working.
Once in a while I would like to invalidate the session and retrieve a new accesstoken/idtoken in exchange for the refreshtoken.
Something like _session.invalidateToken()
so that the next attempt to retrieve the token results in refreshing the token from cognito-server:
Future<String> retrieveToken() async { if (_session.isValid()) return _session.getIdToken().getJwtToken(); this._session = await _cognitoUser.getSession(); return _session.getIdToken().getJwtToken(); }
Is this possible somehow already? If not can this implemented into the library?
when I use amazon-cognito-identity-dart to fullfill the sign-up, it alerts "Unknown client error occurred"
please let me know how can I fix it? Thank you very much
Hi,
is it possible to use social idp like google to sign in to a user pool via this SDK? https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-social-idp.html
I have been testing with a user pool which is configured to ask the user whether the device being logged in should be remembered or not and the code is throwing a CognitoUserConfirmationNecessaryException.
Now, I had initially assumed that this exception was used to indicate the user needs confirmation using a pin but if it is also used to indicate device confirmation, there is no way to distinguish the two different flows. Should the device confirmation requirement be signalled using a different exception?
And safe to assume the methods to confirm a device are still work in progress?
Thanks,
Johan
Hi,
The Use Case 4 says that when Authenticating and a CognitoUserNewPasswordRequiredException is thrown, handle the new password challenge. Looking through cognito_user.dart I can't see a way of doing that. Am I missing something?
Thanks.
Please add export 'src/cognito_access_token.dart'; in cognito.dart file as it is missing.
Is it just me or am I kind of stuck using the io http client?
I am trying to utilize this package in an angulardart app but I get this error when instantiating a CognitoUserPool object:
EXCEPTION: Unsupported operation: Platform._version
STACKTRACE:
dart:sdk_internal new
package:http/src/io_client.dart 23:56 new
package:http/src/client.dart 30:23 new
package:amazon_cognito_identity_dart/src/client.dart 24:26 new
package:amazon_cognito_identity_dart/src/cognito_user_pool.dart 36:14 new
package:angular_app/src/core/cognito/cognito_service.dart 20:14 new
I believe this error is a consequence of using the http client in the browser. The Client class allows for injecting the http.Client into it, but the CognitoUserPool does not have a constructor that allows injection of the Client. It is possible to change the client after instantiation but then I would always get this error. Should I make a pull request with that capability?
Great library!
Please provide an example on signing an ElasticSearch and a DynamoDB request.
Simple testprogram (even without changing the user pool id):
import 'package:amazon_cognito_identity_dart/cognito.dart';
import 'package:flutter_test/flutter_test.dart';
final userPool = new CognitoUserPool(
'ap-southeast-1_xxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxxxxxxx');
final userAttributes = [
new AttributeArg(name: 'first_name', value: 'Jimmy'),
new AttributeArg(name: 'last_name', value: 'Wong'),
];
void main() {
testWidgets('Amazon Cognito signup-test', (WidgetTester tester) async {
var data = await userPool.signUp('[email protected]', 'Password001',
userAttributes: userAttributes);
});
}
The system responds with the followin stacktrace:
Unexpected end of input (at character 1)
^
When the exception was thrown, this was the stack:
#0 _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1362:5)
#1 _ChunkedJsonParser.close (dart:convert/runtime/libconvert_patch.dart:506:7)
#2 _parseJson (dart:convert/runtime/libconvert_patch.dart:30:10)
#3 JsonDecoder.convert (dart:convert/json.dart:542:36)
#4 JsonCodec.decode (dart:convert/json.dart:169:41)
#5 Client.request (package:amazon_cognito_identity_dart/src/client.dart:50:23)
#6 CognitoUserPool.signUp (package:amazon_cognito_identity_dart/src/cognito_user_pool.dart:95:34)
#7 main. (file:///E:/develop/flutter_testapp/flutter_testapp/test/cognito_test.dart:14:31)
#8 testWidgets... (package:flutter_test/src/widget_tester.dart:63:25)
...
Though the solution is obvious I think a better/tailored exception is preferred since such error may also occur in production if the systems are for example overloaded.
I cloned the repo and built the sample.
It runs fine but entering credentials gives the error:
"Unknown client error occurred"
I set the following...
const _awsUserPoolId = 'us-west-2_J********';
const _awsClientId = '3ugt2ss9vtls0s2p*********';
The UserPoolId I got from General Settings > Pool Id
and ClientId from General Settings > AppClients > App client id
. Is that right?
I believe Cognito is set up correctly but not 100% sure as I am not that familiar with it.
Any suggestions to what I can do?
I also tried logging a user that does not exist and that error is:
Unable to verify secret hash for client 3ugt2ss9vtls0s2p*********
Hello @jonsaw !
At first, thank for your package.
I'm trying to use it on my project, where I use AWS Cognito. There are 2 apps: iOS native and Flutter. In an iOS app with native SDK everything works, but in the Flutter one, I always have the error:
CognitoClientException{statusCode: 400, code: NotAuthorizedException, name: NotAuthorizedException, message: Unable to verify secret hash for client client_id
}
Credentials are the same on both app (cliendID, pool id and etc).
@jonsaw great demo. Thanks for sharing.
I'm trying to call APPSYNC using this package in the example project. I'm guided by the example Appsync use case in @ncb000gt pull request.
Below is the UserService
method in the UserService
class modified. It throws the following error when I run it.
I/flutter (26309): {
I/flutter (26309): "errors" : [ {
I/flutter (26309): "errorType" : "UnauthorizedException",
I/flutter (26309): "message" : "Unable to parse JWT token."
I/flutter (26309): } ]
I/flutter (26309): }
Future<UserService> _getValues(BuildContext context) async {
try {
await _userService.init();
_isAuthenticated = await _userService.checkAuthenticated();
if (_isAuthenticated) {
// get user attributes from cognito
_user = await _userService.getCurrentUser();
// get session credentials
final credentials = await _userService.getCredentials();
_awsSigV4Client = new AwsSigV4Client(
credentials.accessKeyId, credentials.secretAccessKey, _endpoint,
region: _region,
sessionToken: credentials.sessionToken,
serviceName: 'AMAZON_COGNITO_USER_POOLS');
// get previous count
_citiesService = new CitiesService(_awsSigV4Client);
_cities = await _citiesService.getCities();
// _counterService = new CounterService(_awsSigV4Client);
// _counter = await _counterService.getCounter();
}
return _userService;
} on CognitoClientException catch (e) {
if (e.code == 'NotAuthorizedException') {
await _userService.signOut();
Navigator.pop(context);
}
throw e;
}
}
In javascript aws-sdk the params we have to pass are:
https://github.com/dabit3/appsync-react-native-with-user-authorization/blob/b312924fe57e0936186b4688d7c856b13e76c27b/App.js#L30-L37
const client = new Client({
url: AppSync.graphqlEndpoint,
region: AppSync.region,
auth: {
type: 'AMAZON_COGNITO_USER_POOLS',
jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
}
});
I'm thinking that solution is to pass AMAZON_COGNITO_USER_POOLS
to awsSigV4Client
some way. Any ideas on how to do this correctly?
Thank you.
Hello there!
Thanks for putting up this package :) Nice work!
I am trying to use it by running the example app, but when I try to sign in (sign-up has already been done via another app), I get a error "Unable to verify secret hash for client xxxxxxx".
I don't see a way to specify the app client secret anywhere. Is it the secret that is generated in the AWS Cognito console, under the pool's "App Clients" section ? If yes, how can you make your example app work without it ? I am confused...
Hi,
In cognito_user.dart
(line 176) there is the code
final clockDrift = int.parse(await storage.getItem(clockDriftKey)) ?? 0;
When storage.getItem
returns null it crashes.
I think the ?? 0
should either be within the brackets or int.tryParse should be used.
Regards,
Florian
I hope you can help me.
When i generate a token using getIdToken().getJwtToken() it works great, the problem is that i dont know how to deal with refresh. So, eventually the token expires and i get a 401 error.
Can anyone please tell me how can i get a new token ? thanks!
Nick
I saw @BerndWessels added the ability to authenticate via Google & Facebook - I assume the same mechanism can be used to use Azure AD, but I am not sure what gets passed as the 'authenticator' parameter - right now I am getting an "Invalid login token. Issuer doesn't match providerName" error.
Thanks,
Bob
Wondering if you had more Appsync examples with offline data usage.
Hi,
I'm totally new to Dart and AWS Cognito. I downloaded the project, modified the value and run. I was able to register a new user but when I tried to log in, I got an error "Incorrect username and password".
Thanks,
VV
Do you have an example for generating a presigned URL for a S3 Object Get with a temporary session id?
Hey everyone,
I'm in need of some help with my app. In my app, I was hoping to provide read-only access to AppSync for unauthenticated users. To do this I allowed unauthenticated identities in my Identity User pool and attached an appropriate role. I can't seem to figure out though how to make an unauthenticated request using this package.
Edit:
Ok, I figured it out. You can simply remove the login parameter in both getIdentityId
and getAwsCredentials
. As far as I can see there is no such functionality already present. Should I open a pull request with this change?
Greetings
Noureddine
CognitoClientException{statusCode: 400, code: InvalidParameterException, name: InvalidParameterException, message: 1 validation
how can i add custom attributes when signup?
can i use ClientMataData ?
Thanks.
First of all, thanks for sharing this SDK.
I need help using the custom authentication flow.
Do you have any way to use the custom authentication flow? Do you have an example?
Thanks
Afternoon,
I've been following the examples & have managed to get the login working, as well as the basic API Gateway 'GET' call, which is brilliant.
But when I come to add the Cognito Authorizer to the API Gateway, the call fails with 'Unauthenticated' & there's nothing I can see in Cloudwatch that points to what's wrong.
I've attempted to add the Authorization token to the header for the call but it hasn't made any difference:
`final awsSigV4Client = new AwsSigV4Client(
credentials.accessKeyId,
credentials.secretAccessKey,
Common.API_GATEWAY,
sessionToken: credentials.sessionToken,
region: 'eu-west-2'
);
final signedRequest = new SigV4Request(
awsSigV4Client,
method: 'GET',
path: '/playlists',
headers: {
'Authorization': credentials.sessionToken
},
);
try {
_response = await http.get(signedRequest.url, headers: signedRequest.headers);
} `
Is there anything I'm missing here, or anything I've done wrong, please point me in the right direction!
I am also assuming that once the above is working, the cognito:username will be passed through as part of the claims in the requestContext?
Thanks,
James
when i signin with a temporary password ,the cognito require a new password to complete the flow.
how to complete new password challenge?
thanks
How should our DynamoDB be setup?
My understanding is that you have a couple of lambda's setup working with the DynamoDB.
Currently I have a table made named "users" with a primary key of "email". Figured it be the most proper setup.
Does anyone have additional information on the prerequisites for the example app?
One nice feature would be to allow once you login with a user, to be able to attach the user to an specific group.
Right now with the current version of the library, I am not sure how to do it.
This is a functionality I would be quite happy to have, and I could collaborate into it.
The idea is to use this functionality:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#adminAddUserToGroup-property
So I have been able to use the plugin to send GraphQL mutations and queries to AppSync, but has anyone been able to setup a working subscription? The websocket / mqtt endpoint seems to be extremely particular...
Thanks,
Bob
Thanks for putting this out there. I ran into an issue trying to authenticate using the library so I broke the code out into an example application and was able to isolate the issue to lib/cognito_user.dart:144
.
Receiver: Instance of 'Future'
Tried calling: []("UserConfirmationNecessary") - #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:46:5)
#1 CognitoUser._authenticateUserInternal (package:amazon_cognito_identity_dart/src/cognito_user.dart:144:20)
<asynchronous suspension>
#2 CognitoUser._authenticateUserDefaultAuth (package:amazon_cognito_identity_dart/src/cognito_user.dart:627:12)
<asynchronous suspension>
#3 CognitoUser.authenticateUser (package:amazon_cognito_identity_dart/src/cognito_user.dart:436:20)
<asynchronous suspension>
#4 AuthService.login (file:///Users/ncampbell/Code/flutter_cognito_auth_test/lib/auth.dart:122:34)
<asynchronous suspension>
#5 _AuthGatewayState.submit (file:///Users/ncampbell/Code/flutter_cognito_auth_test/lib/main.dart:68:23)
<asynchronous suspension>
#6 _AuthGatewayState.build.<anonymous closure>.<anonymous closure> (file:///Users/<…>
I noticed the issue in 0.0.17
and pulled master
to double check. The issue exists there as well.
I have a fix in a branch I'm working on and will push a PR up for it once I'm comfortable that all the issues are resolved.
After upgrading flutter, I am getting the following error:
Because every version of flutter_test from sdk depends on http 0.12.0 and every version of amazon_cognito_identity_dart depends on http ^0.11.3, flutter_test from sdk is incompatible with amazon_cognito_identity_dart.
I am new to flutter and am trying to get my application integrated with aws cognito.
I took your example main.dart file and replaced the following code in the login screen class (sending the user to a new screen instead of displaying the snackbar message. I tested with the message and it does display I am logged in.
/**
final snackBar = new SnackBar(
content: new Text(message),
action: new SnackBarAction(
label: 'OK',
onPressed: () {
if (signUpSuccess) {
Navigator.pop(context);
if (!_user.confirmed) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
new ConfirmationScreen(email: _user.email)),
);
}
}
},
),
duration: new Duration(seconds: 30),
);
Scaffold.of(context).showSnackBar(snackBar);
**/
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
On the second screen, I moved the copied the code from the _SecureCounterScreenState class in the main.dart example file to build my own screen:
class _SecondScreenState extends State {
final _userService = new UserService(userPool);
User _user = new User();
bool _isAuthenticated = false;
CognitoUser _cognitoUser;
Future _getValues(BuildContext context) async {
try {
await _userService.init();
_isAuthenticated = await _userService.checkAuthenticated();
if (_isAuthenticated) {
// get user attributes from cognito
_user = await _userService.getCurrentUser();
_cognitoUser = await _userService.getCognitoUser();
// get session credentials
final credentials = await _userService.getCredentials();
}
return _userService;
} on CognitoClientException catch (e) {
if (e.code == 'NotAuthorizedException') {
await _userService.signOut();
Navigator.pop(context);
}
throw e;
}
}
@OverRide
Widget build(BuildContext context) {
final f = new DateFormat.yMMMMd("en_US");
return new FutureBuilder(
future: _getValues(context),
builder: (context, AsyncSnapshot<UserService> snapshot) {
//if (snapshot.hasData) {
//if (!_isAuthenticated) {
// return new LoginScreen();
//}
return new Scaffold(
appBar: AppBar(
title: Text(f.format(new DateTime.now())),
backgroundColor: Color.fromARGB(255, 234, 100, 34),
),
body: new Container(
decoration: new BoxDecoration(
color: Color.fromARGB(255, 212, 43, 63),
),
child: _cognitoUser == null
? Container(
child: Text("null"),
)
: Container(
child: Text(_cognitoUser.getUsername()),
),
),
);
//};
}
);
}
}
If I uncomment this code:
if (snapshot.hasData) {
//if (!_isAuthenticated) {
// return new LoginScreen();
//}
I receive a builder returned null error.
With it commented out, _cognitoUser == null
Can you help me understand what I am doing wrong?
I am trying to use the login screen, then send the user to a second screen that uses displays the cognito user's username. The storage doesn't seem to be either saving or retrieving the user properly.
Thanks for your help
Was trying to add this package in my project and it showing following error:
The current Dart SDK version is 2.0.0-dev.58.0.flutter-f981f09760.
Because every version of flutter_test from sdk depends on package_resolver 1.0.2 which depends on http ^0.11.0, every version of flutter_test from sdk requires http ^0.11.0.
And because amazon_cognito_identity_dart >=0.0.19+2 depends on http ^0.12.0 and amazon_cognito_identity_dart >=0.0.19 <=0.0.19+1 requires SDK version >=2.1.0-dev.8.0 <3.0.0, flutter_test from sdk is incompatible with amazon_cognito_identity_dart >=0.0.19.
So, because flutter_app_aws_signup depends on both amazon_cognito_identity_dart ^0.0.19 and flutter_test any from sdk, version solving failed.
pub get failed (1)
hey there, what's lacking from this to become official? would you be interested in help to make this feature rich as with the js aws-amplify lib?
The API returns a "The request signature we calculated does not match the signature you provided" error for this request:
final awsSigV4Client = new AwsSigV4Client(accessKeyId,
secretAccessKey, 'https://dynamodb.us-east-2.amazonaws.com',
serviceName: 'dynamodb', sessionToken: sessionToken, region: 'us-east-2', defaultContentType: 'application/x-amz-json-1.0');
final query = {
"TableName": "xxx",
"KeyConditionExpression": "(#0 = :0 AND begins_with (#1, :1))",
"ExpressionAttributeNames": {
"#0" : "pk",
"#1" : "sk"
},
"ExpressionAttributeValues": {
":0": {"S": "Foo"},
":1": {"S": "C10108000"},
},
"ReturnConsumedCapacity": "TOTAL"
};
final signedRequest = new SigV4Request(awsSigV4Client,
method: 'POST',
path: '/',
headers: new Map<String, String>.from(
{'X-Amz-Target': 'DynamoDB_20120810.Query'}),
body: query);
It seems like this package isn't supported anymore, last update was 9 month ago, 14 PR are opened.
When I am using GET the request succeeds.
But when I use POST I get this error response
The request signature we calculated does not match the signature you provided. ...
Is there a problem with POST and signing for API Gateway ?
Hi,
Is this library still actively maintained? If not, could you maybe create an issue and pin it just to make people aware that is it no longer maintained? Thanks
Not working with latest flutter v1.15.0
When I was testing on emulator the login UI works fine. But on a real device (especially iOS) the UI just freeze and I was not able to display loading. So I debugging to the source code found out that the cause of this was operations on BigInt values. For my case I separate some of the functions to be run on Isolate (to not be run on the main thread). Now it works fine. I implemented this only on login. To be implemented in the whole library will be much more work. And I am not sure is there a better solution?
Implement getUserAttributes()
updateAttributes()
& deleteAttributes()
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.