Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added example for case with presign s3 url #51

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,98 @@ $payload''';
}
```

#### For PreSign S3 url


```dart
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:amazon_cognito_identity_dart/cognito.dart';
import 'package:amazon_cognito_identity_dart/sig_v4.dart';
import 'package:http/http.dart' as http;

void main() {
const _awsUserPoolId = 'ap-southeast-1_xxxxxxxx';
const _awsClientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';

const _identityPoolId =
'ap-southeast-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
final _userPool = CognitoUserPool(_awsUserPoolId, _awsClientId);

final _cognitoUser = CognitoUser('+60100000000', _userPool);
final authDetails =
AuthenticationDetails(username: '+60100000000', password: 'p@ssW0rd');

CognitoUserSession _session;
try {
_session = await _cognitoUser.authenticateUser(authDetails);
} catch (e) {
print(e);
return;
}

final _credentials = CognitoCredentials(_identityPoolId, _userPool);
await _credentials.getAwsCredentials(_session.getIdToken().getJwtToken());

final service = 's3';
final region = 'ap-southeast-1';
final bucket = 'bucket-name'
final host = '$bucket.$service.$region.amazonaws.com';
final headers = {"Host": host};
final key = 'public/square-cinnamon.jpg';

Map<String, String> params = {};

final datetime = SigV4.generateDatetime();
final credentialScope = SigV4.buildCredentialScope(datetime, region, service);

params['X-Amz-Security-Token'] = _credentials.sessionToken;
params['X-Amz-Algorithm'] = aws_sha_256;
params['X-Amz-Date'] = datetime;
params['X-Amz-SignedHeaders'] = SigV4.buildCanonicalSignedHeaders(headers);
params['X-Amz-Expires'] = '3599';
params['X-Amz-Credential'] = '${credentials.accessKeyId}/$credentialScope';

final canonicalRequest = SigV4.buildCanonicalRequest(
'GET',
'/$key',
params,
headers,
'UNSIGNED-PAYLOAD', false);

final stringToSign = SigV4.buildStringToSign(datetime, credentialScope, SigV4.hashCanonicalRequest(canonicalRequest));

final signingKey = SigV4.calculateSigningKey(_credentials.secretAccessKey, datetime, region, service);
final signature = SigV4.calculateSignature(signingKey, stringToSign);

params['X-Amz-Signature'] = signature;

final url = 'https://$host${'/$key'.split('/').map((s) => Uri.encodeComponent(s)).join('/')}?'
+ params.keys.map((key) => '$key=${Uri.encodeComponent(params[key])}').join('&');

http.Response response;
try {
response = await http.get(url);
} catch (e) {
print(e);
return;
}

final file = File(path.join(
'/path/to/my/folder',
'square-cinnamon-downloaded.jpg'));

try {
await file.writeAsBytes(response.bodyBytes);
} catch (e) {
print(e.toString());
return;
}

print('complete!');
}
```

#### For AppSync's GraphQL

Authenticating Amazon Cognito User Pool using JWT Tokens.
Expand Down
6 changes: 3 additions & 3 deletions lib/sig_v4.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';

const _aws_sha_256 = 'AWS4-HMAC-SHA256';
const aws_sha_256 = 'AWS4-HMAC-SHA256';
const _aws4_request = 'aws4_request';
const _aws4 = 'AWS4';
const _x_amz_date = 'x-amz-date';
Expand Down Expand Up @@ -218,14 +218,14 @@ class SigV4 {
String path,
Map<String, String> queryParams,
Map<String, String> headers,
String payload) {
String payload, [bool signPayload = true]) {
List<String> canonicalRequest = [
method,
buildCanonicalUri(path),
buildCanonicalQueryString(queryParams),
buildCanonicalHeaders(headers),
buildCanonicalSignedHeaders(headers),
hexEncode(hash(utf8.encode(payload))),
if (signPayload) hexEncode(hash(utf8.encode(payload))) else payload,
];
return canonicalRequest.join('\n');
}
Expand Down