下面两段功能具体要怎么做有没有示例代码:nconnect-使用普通的-usenamepassword-方式password为我们自定义的jwt。n需要自定义权限校验也就是由我们的服务或者lambda对usernamepassword-进行校验。成功后才允许建立连接。
对于第一段功能,可以使用AWS Amplify库中的API模块来实现。具体步骤如下:
- 安装AWS Amplify库:
npm install aws-amplify --save
- 在代码中引入API模块:
import Amplify, { API } from 'aws-amplify';
- 配置API模块:
Amplify.configure({
Auth: {
identityPoolId: 'YOUR_IDENTITY_POOL_ID',
region: 'YOUR_REGION',
userPoolId: 'YOUR_USER_POOL_ID',
userPoolWebClientId: 'YOUR_USER_POOL_CLIENT_ID',
mandatorySignIn: true,
authenticationFlowType: 'CUSTOM_AUTH'
},
API: {
endpoints: [
{
name: 'myApi',
endpoint: 'YOUR_API_GATEWAY_ENDPOINT',
custom_header: async () => {
return { Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}` }
}
}
]
}
});
其中,你需要将 YOUR_IDENTITY_POOL_ID、YOUR_REGION、YOUR_USER_POOL_ID、YOUR_USER_POOL_CLIENT_ID、YOUR_API_GATEWAY_ENDPOINT 替换为你自己的配置。
- 调用API方法:
API.post('myApi', '/myApiEndpoint', {
headers: {
Authorization: `Bearer ${jwt}`
}
}).then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
其中,myApi是你在配置API模块时定义的端点名称,/myApiEndpoint是API Gateway上的端点路径,jwt是你自定义的JWT令牌。
对于第二段功能,可以使用Lambda函数来实现。具体步骤如下:
- 创建Lambda函数,代码示例:
exports.handler = async (event) => {
const { username, password } = event;
// 在这里对username/password进行校验
if (username === 'admin' && password === 'jwt') {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Success' })
};
} else {
return {
statusCode: 401,
body: JSON.stringify({ message: 'Unauthorized' })
};
}
};
-
在API Gateway上创建端点,将其关联到Lambda函数上。
-
配置API模块:
Amplify.configure({
Auth: {
identityPoolId: 'YOUR_IDENTITY_POOL_ID',
region: 'YOUR_REGION',
userPoolId: 'YOUR_USER_POOL_ID',
userPoolWebClientId: 'YOUR_USER_POOL_CLIENT_ID',
mandatorySignIn: true,
authenticationFlowType: 'CUSTOM_AUTH',
storage: window.localStorage
},
API: {
endpoints: [
{
name: 'myApi',
endpoint: 'YOUR_API_GATEWAY_ENDPOINT',
custom_header: async () => {
return { Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}` }
}
}
]
}
});
其中,你需要将 YOUR_IDENTITY_POOL_ID、YOUR_REGION、YOUR_USER_POOL_ID、YOUR_USER_POOL_CLIENT_ID、YOUR_API_GATEWAY_ENDPOINT 替换为你自己的配置。
- 调用API方法:
API.post('myApi', '/myApiEndpoint', {
body: {
username: 'admin',
password: 'jwt'
}
}).then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
其中,myApi是你在配置API模块时定义的端点名称,/myApiEndpoint是API Gateway上的端点路径,username和password是你要校验的用户名和密码。
原文地址: https://www.cveoy.top/t/topic/qn3 著作权归作者所有。请勿转载和采集!