![](/img/trans.png)
[英]How to Access User Pools using the Amazon Cognito Identity SDK for Java
[英]How to configure AWS user cognito authentication flow for generating identity token,access token in Java sdk backend?
下面是代碼:
AnonymousAWSCredentials awsCreds = new AnonymousAWSCredentials();
AWSCognitoIdentityProvider provider = AWSCognitoIdentityProviderClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(//region)
.build();
AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest()
.withAuthFlow(AuthFlowType.USER_PASSWORD_AUTH)
.withClientId("")
.withUserPoolId("")
.withAuthParameters(map);
Map<String,String> map = new HashMap<>();
map.put("USERNAME","");
map.put("PASSWORD","");
這里地圖將有用戶名和密碼。
有人可以幫助如何在 Java 中配置身份驗證以生成 id 令牌和訪問令牌嗎? 提前致謝!!
您的代碼可能如下所示。 請注意:
使用 ADMIN_USER_PASSWORD_AUTH 流進行身份驗證。 請參閱AdminInitiateAuth
在 Cognito 中,在客戶端設置中,在“Auth Flows Configuration”部分下,應啟用下一個選項“Enable username password auth for admin APIs for authentication (ALLOW_ADMIN_USER_PASSWORD_AUTH)” 。
public static void auth(String username, String password) { AwsBasicCredentials awsCreds = AwsBasicCredentials.create(AWS_KEY, AWS_SECRET); CognitoIdentityProviderClient identityProviderClient = CognitoIdentityProviderClient.builder() .credentialsProvider(StaticCredentialsProvider.create(awsCreds)) .region(Region.of(REGION)) .build(); final Map<String, String> authParams = new HashMap<>(); authParams.put("USERNAME", username); authParams.put("PASSWORD", password); authParams.put("SECRET_HASH", calculateSecretHash(CLIENT_ID, CLIENT_SECRET, username)); final AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder() .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH) .clientId(CLIENT_ID) .userPoolId(POOL_ID) .authParameters(authParams) .build(); AdminInitiateAuthResponse result = identityProviderClient.adminInitiateAuth(authRequest); System.out.println(result.authenticationResult().accessToken()); System.out.println(result.authenticationResult().idToken());
}
方法 calculateSecretHash 取自 AWS Documentation Signing Up and Confirming User Accounts :
private static String calculateSecretHash(String userPoolClientId, String userPoolClientSecret, String userName) { final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; SecretKeySpec signingKey = new SecretKeySpec( userPoolClientSecret.getBytes(StandardCharsets.UTF_8), HMAC_SHA256_ALGORITHM); try { Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); mac.init(signingKey); mac.update(userName.getBytes(StandardCharsets.UTF_8)); byte[] rawHmac = mac.doFinal(userPoolClientId.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(rawHmac); } catch (Exception e) { throw new RuntimeException("Error while calculating "); }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.