@352inc/react-native-aws-cognito-js 中文文档教程
react-native-aws-cognito-js
这是 Amazon Cognito Identity SDK for JavaScript 与 AWS SDK for JavaScript for 反应本机。
该项目使用 Native Modules 来处理使用 React Native 桥接的设备上的密集数学运算。
Installation
安装在你的应用目录:
npm install --save react-native-aws-cognito-js
或
yarn add react-native-aws-cognito-js
链接项目:
react-native link react-native-aws-cognito-js
MemoryStorage
本地MemoryStorage可以处理认证端的所有事情,但是当应用重新打开时数据丢失了。 存储同步方法将仅从 AsyncStorage 获取 MemoryStorage 数据并使用这些值更新本地 MemoryStage。
可以从 userPool 或 cognitoUser 使用新的同步方法:
userPool.storage.sync((err, result) => {
// MemoryStorage is now updated with AsyncStorage values
});
或
cognitoUser.storage.sync((err, result) => {
// MemoryStorage is now updated with AsyncStorage values
});
Usage
参考 Amazon Cognito Identity SDK 了解 JavaScript 用法 例子。
Example
这是一个用户身份验证示例:
//imports
import {
Config,
CognitoIdentityCredentials
} from 'aws-sdk/dist/aws-sdk-react-native';
import {
AuthenticationDetails,
CognitoUser,
CognitoUserPool,
CognitoUserAttribute
} from 'react-native-aws-cognito-js';
const appConfig = {
region: '',
IdentityPoolId: '',
UserPoolId: '',
ClientId: '',
}
//setting config
Config.region = appConfig.region;
//component:
state = {
username: '',
password: '',
}
login = () => {
const { username, password } = this.state;
const authenticationData = {
Username: username,
Password: password,
};
const authenticationDetails = new AuthenticationDetails(authenticationData);
const poolData = {
UserPoolId: appConfig.UserPoolId,
ClientId: appConfig.ClientId
};
const userPool = new CognitoUserPool(poolData);
const userData = {
Username: username,
Pool: userPool
};
const cognitoUser = new CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
console.log('access token + ' + result.getAccessToken().getJwtToken());
Config.credentials = new CognitoIdentityCredentials({
IdentityPoolId: appConfig.IdentityPoolId,
Logins: {
[`cognito-idp.${appConfig.region}.amazonaws.com/${appConfig.UserPoolId}`]: result.getIdToken().getJwtToken()
}
});
alert('Success');
console.log(Config.credentials);
},
onFailure: (err) => {
alert(err);
},
});
}
Advanced Example
//- AWS.js
//create AWS with userPool using dotenv to hold environment variables
import AWS, { CognitoIdentityServiceProvider } from 'aws-sdk/dist/aws-sdk-react-native';
import * as enhancements from 'react-native-aws-cognito-js';
import { AWS_REGION, AWS_POOL_ID, AWS_POOL_CLIENT_ID } from 'react-native-dotenv';
Object.keys(enhancements).forEach(key => (CognitoIdentityServiceProvider[key] = enhancements[key]));
AWS.config.update({ region: AWS_REGION });
export const poolData = {
UserPoolId: AWS_POOL_ID,
ClientId: AWS_POOL_CLIENT_ID,
};
export const userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
export default AWS;
//import AWS and userPool
import AWS, { userPool } from './AWS';
//component:
state = {
username: '',
password: '',
}
login = () => {
const { username, password } = this.state;
const authenticationData = { Username: username, Password: password };
const authenticationDetails = new AWS.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
const userData = { Username: username, Pool: userPool };
const cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
console.log('result', result);
console.log('access token:', result.getAccessToken().getJwtToken());
},
onFailure: (error) => {
Alert.alert(error.code, error.message);
},
});
}
react-native-aws-cognito-js
This is an adaptation of Amazon Cognito Identity SDK for JavaScript in combination with AWS SDK for JavaScript for React Native.
This project uses Native Modules to handle intensive math operations on the device using the React Native bridge.
Installation
Install in your application directory:
npm install --save react-native-aws-cognito-js
or
yarn add react-native-aws-cognito-js
Link project:
react-native link react-native-aws-cognito-js
MemoryStorage
The local MemoryStorage can handle everything on the authentication side, but the data is lost when the app is reopened. The storage sync method will grab only the MemoryStorage data from AsyncStorage and update the local MemoryStage with the values.
The new sync method can be used from either the userPool or cognitoUser:
userPool.storage.sync((err, result) => {
// MemoryStorage is now updated with AsyncStorage values
});
or
cognitoUser.storage.sync((err, result) => {
// MemoryStorage is now updated with AsyncStorage values
});
Usage
Refer to the Amazon Cognito Identity SDK for JavaScript usage examples.
Example
This is a user authentication sample:
//imports
import {
Config,
CognitoIdentityCredentials
} from 'aws-sdk/dist/aws-sdk-react-native';
import {
AuthenticationDetails,
CognitoUser,
CognitoUserPool,
CognitoUserAttribute
} from 'react-native-aws-cognito-js';
const appConfig = {
region: '',
IdentityPoolId: '',
UserPoolId: '',
ClientId: '',
}
//setting config
Config.region = appConfig.region;
//component:
state = {
username: '',
password: '',
}
login = () => {
const { username, password } = this.state;
const authenticationData = {
Username: username,
Password: password,
};
const authenticationDetails = new AuthenticationDetails(authenticationData);
const poolData = {
UserPoolId: appConfig.UserPoolId,
ClientId: appConfig.ClientId
};
const userPool = new CognitoUserPool(poolData);
const userData = {
Username: username,
Pool: userPool
};
const cognitoUser = new CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
console.log('access token + ' + result.getAccessToken().getJwtToken());
Config.credentials = new CognitoIdentityCredentials({
IdentityPoolId: appConfig.IdentityPoolId,
Logins: {
[`cognito-idp.${appConfig.region}.amazonaws.com/${appConfig.UserPoolId}`]: result.getIdToken().getJwtToken()
}
});
alert('Success');
console.log(Config.credentials);
},
onFailure: (err) => {
alert(err);
},
});
}
Advanced Example
//- AWS.js
//create AWS with userPool using dotenv to hold environment variables
import AWS, { CognitoIdentityServiceProvider } from 'aws-sdk/dist/aws-sdk-react-native';
import * as enhancements from 'react-native-aws-cognito-js';
import { AWS_REGION, AWS_POOL_ID, AWS_POOL_CLIENT_ID } from 'react-native-dotenv';
Object.keys(enhancements).forEach(key => (CognitoIdentityServiceProvider[key] = enhancements[key]));
AWS.config.update({ region: AWS_REGION });
export const poolData = {
UserPoolId: AWS_POOL_ID,
ClientId: AWS_POOL_CLIENT_ID,
};
export const userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
export default AWS;
//import AWS and userPool
import AWS, { userPool } from './AWS';
//component:
state = {
username: '',
password: '',
}
login = () => {
const { username, password } = this.state;
const authenticationData = { Username: username, Password: password };
const authenticationDetails = new AWS.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
const userData = { Username: username, Pool: userPool };
const cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
console.log('result', result);
console.log('access token:', result.getAccessToken().getJwtToken());
},
onFailure: (error) => {
Alert.alert(error.code, error.message);
},
});
}