인증 없이 API에 대한 사용자 액세스 허용(익명 사용자 액세스)
20388 단어 apigatewaycognito

사진 제공 Marek Okon
Amazon Cognito 자격 증명 풀은 인증된 사용자와 인증되지 않은 사용자를 모두 지원합니다. 인증되지 않은 사용자는 자격 증명 공급자(IdP)로 로그인하지 않은 경우에도 AWS 리소스에 대한 액세스 권한을 받습니다. 이 액세스 수준은 로그인하기 전에 사용자에게 콘텐츠를 표시하는 데 유용합니다. 인증되지 않은 각 사용자는 개별적으로 로그인 및 인증되지 않았더라도 자격 증명 풀에서 고유한 자격 증명을 가집니다.
이 문서에서는 사용자가 인증되지 않은 ID로 로그인하는 것에서 인증된 ID를 사용하는 것으로 전환하도록 선택하는 경우에 대해 설명합니다.
이 사례에 대한 전체 솔루션을 시연합니다. GitHub에서 이 솔루션에 대한 코드를 얻을 수 있습니다.
데모에는 두 부분이 있습니다.
인프라: 데모용 인프라를 설정합니다.
// create a auth service, this will create a user pool and user pool client
// it also creates 2 roles, one for unauthenticated and one for authenticated
// the roles will be used to create the authorizer and the integration
const auth = new AuthService(this, 'AuthService', {});
// ==== HTTP API ====
const api = new HttpApi(this, 'HttpApi', {
description: 'This is a sample HTTP API',
corsPreflight: {
allowHeaders: [
'Content-Type',
'X-Amz-Date',
'Authorization',
'X-Api-Key',
'X-Amz-Security-Token',
],
allowMethods: [
CorsHttpMethod.OPTIONS,
CorsHttpMethod.GET,
CorsHttpMethod.POST,
CorsHttpMethod.PUT,
CorsHttpMethod.PATCH,
CorsHttpMethod.DELETE,
],
allowCredentials: true,
allowOrigins: ['http://localhost:8080'],
},
});
// add http iam authorizer
const authorizer = new apiGatewayAuthorizers.HttpIamAuthorizer();
// lambda function
const fn = new NodejsFunction(this, 'SampleFunction', {
entry: './lambda/index.ts',
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'main',
architecture: lambda.Architecture.ARM_64,
logRetention: logs.RetentionDays.ONE_WEEK,
bundling: {
externalModules: ['aws-sdk'],
minify: true,
},
});
// add route with lambda integration
api.addRoutes({
path: '/api/test',
methods: [HttpMethod.GET],
integration: new apiGatewayIntegrations.HttpLambdaIntegration(
'fn-integration',
fn,
{}
),
authorizer, // use IAM authorizer
});
// allow unauthenticated access to the API
// This is very important for the API to work
auth.unAuthRole.attachInlinePolicy(
new iam.Policy(this, 'UnAuthPolicy', {
statements: [
new iam.PolicyStatement({
actions: ['execute-api:*'],
resources: [
// allow unauthenticated access to the API /api
// arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path
`arn:aws:execute-api:${Stack.of(this).region}:*:*/*/*/api/*`,
],
}),
],
})
);
// output api url
new CfnOutput(this, 'ApiUrl', {
value: `${api.apiEndpoint}/api/test`,
});
}
사용 풀에는 인증되지 않은 역할과 인증된 역할의 두 가지 역할이 있습니다. 인증되지 않은 역할은 권한 부여자와 통합을 생성하는 데 사용됩니다. 그러면 Cognito 자격 증명 풀이 생성됩니다. 자격 증명 풀에서 allowUnauthenticatedIdentities 기능을 활성화해야 합니다.
// cognito identity providers
const identityPool = new cognito.CfnIdentityPool(this, 'CognitoIdentityProvider', {
allowUnauthenticatedIdentities: true,
cognitoIdentityProviders: [
{
clientId: client.userPoolClientId,
providerName: (userPool as cognito.UserPool).userPoolProviderName,
},
],
})
auth.unAuthRole.attachInlinePolicy(
new iam.Policy(this, 'UnAuthPolicy', {
statements: [
new iam.PolicyStatement({
actions: ['execute-api:*'],
resources: [
// allow unauthenticated access to the API /api
// arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path
`arn:aws:execute-api:${Stack.of(this).region}:*:*/*/*/api/*`,
],
}),
],
})
)
프런트엔드 애플리케이션.
AWS-amplify를 사용하여 프런트엔드 애플리케이션을 생성합니다. AWS Amplify는 클라우드 지원 애플리케이션을 구축하는 프런트엔드 및 모바일 개발자를 위한 JavaScript 라이브러리입니다. You can see more here
파일
App.vue
을 보면 인증되지 않은 사용자와 API 호출을 수행하는 스니펫 코드를 볼 수 있습니다(AWS IAM 권한 부여자 사용).// get current credentials. With aws-amplify, you can get current credentials from `Auth.currentUserCredentials`
const cre = await Auth.currentCredentials();
const signedRequest = sigV4Client
.newClient({
accessKey: cre.accessKeyId,
secretKey: cre.secretAccessKey,
sessionToken: cre.sessionToken,
region: awsExports.aws_cognito_region,
endpoint: config.baseURL,
})
.signRequest({
method: config.method,
path: config.url,
body: config.data,
});
sigV4Client
는 요청에 서명하는 도우미 클래스입니다. 여기sigV4Client에서 자세한 내용을 볼 수 있습니다. 요청을 API로 보내기 전에 서명해야 합니다.AWS에 배포
백엔드를 AWS에 배포합니다.
yarn deploy
배포 후 파일로 내보낼 수 있습니다
cdk-outputs.json
.파일
app/src/aws-exports.js
을 편집하고 키 값apiUrl
을 파일ApiUrl
의 키 값cdk-outputs.json
으로 바꿉니다...테스트
cd app
yarn install
yarn dev
응용 프로그램은 localhost:8080에서 실행됩니다. 브라우저를 열고 http://localhost:8080으로 이동하여 결과를 확인하십시오.
{
"accessKey": "ASIA36FRBAMP6DINCSON",
"accountId": "xxx",
"callerId": "AROA36FRBAMPTRORUFVL7:CognitoIdentityCredentials",
"cognitoIdentity": {
"amr": ["unauthenticated"],
"identityId": "ap-southeast-1:af38fa97-b29f-470b-8224-f58cc561e333",
"identityPoolId": "ap-southeast-1:3cd835c2-19a8-40f5-8f14-2e30924a5fd3"
},
"principalOrgId": "aws:PrincipalOrgID",
"userArn": "arn:aws:sts::xxxx:assumed-role/CdkStarterStackStack-AuthServiceIdentityPoolUnAuth-1GDNK5A20FXPC/CognitoIdentityCredentials",
"userId": "AROA36FRBAMPTRORUFVL7:CognitoIdentityCredentials"
}
와우, 인증 없이 API 호출 결과를 볼 수 있습니다.
청소
청소하는 것을 잊지 마십시오.
npx cdk destroy
읽어 주셔서 감사합니다. 이 기사가 도움이 되었기를 바랍니다. 질문이 있으시면 자유롭게 의견을 남겨주세요. 나는 당신의 질문에 답하려고 노력할 것입니다.
Reference
이 문제에 관하여(인증 없이 API에 대한 사용자 액세스 허용(익명 사용자 액세스)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/aws-builders/allow-user-access-to-your-api-without-authentication-anonymous-user-access-hf0텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)