Aws Cognito Java Sdk Example

Integrate Java with AWS Cognito — Developer Tutorial

Amazon Cognito

What is Amazon Cognito?

Lets code

          <dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-cognitoidp</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
</dependency>
          private AWSCognitoIdentityProvider createCognitoClient() {
AWSCredentials cred = new BasicAWSCredentials(access_key, secret_key);
AWSCredentialsProvider credProvider = new AWSStaticCredentialsProvider(cred);
return AWSCognitoIdentityProviderClientBuilder.standard()
.withCredentials(credProvider)
.withRegion(region)
.build();
}

Sign Up Implementation

          public SignUpResult signUp(String name, String email, String password) {
SignUpRequest request = new SignUpRequest().withClientId(clientId)
.withUsername(email)
.withPassword(password)
.withUserAttributes(
new AttributeType()
.withName("name")
.withValue(name));
SignUpResult result = client.signUp(request);
return result;
}

Confirm Sign Up Implementation

          public ConfirmSignUpResult confirmSignUp(String email, String confirmationCode) {
ConfirmSignUpRequest confirmSignUpRequest = new ConfirmSignUpRequest().withClientId(clientId).withUsername(email).withConfirmationCode(confirmationCode);
return client.confirmSignUp(confirmSignUpRequest);
}

Sign In Implementation

          public Map<String, String> login(String email, String password) {
Map<String, String> authParams = new LinkedHashMap<String, String>() {{
put("USERNAME", email);
put("PASSWORD", password);
}};

AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest()
.withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
.withUserPoolId(userPool)
.withClientId(clientId)
.withAuthParameters(authParams);
AdminInitiateAuthResult authResult = client.adminInitiateAuth(authRequest);
AuthenticationResultType resultType = authResult.getAuthenticationResult();
return new LinkedHashMap<String, String>() {{
put("idToken", resultType.getIdToken());
put("accessToken", resultType.getAccessToken());
put("refreshToken", resultType.getRefreshToken());
put("message", "Successfully login");
}};

}

Authentication & Authorization Flow

  1. The client authenticates against a user pool.
  2. The user pool assigns three JSON Web Tokens (JWT) — ID, access and refresh — to the client.
  3. The Access JSON Web Token is passed to the identity pool, and a role is chosen via the JWT claims. The user receives IAM temporary credentials with privileges that are based on the IAM role that was mapped to the group that the user belongs to.
  4. Then, the user can make calls to other services on AWS and applications such as databases. These privileges are dictated by IAM policies.
          <dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>5.7</version>
</dependency>
  1. JWT Parsing: The access token provided is parsed as a JWT. If the parsing fails, the token will be considered invalid.
  2. Algorithm Check: The JSON Web Key algorithm specified in the JSON Web Token header is checked. If a token with an unexpected algorithm is received, the token will be immediately rejected.
  3. Signature Check: In this step, the digital signature is verified.
  4. JWT Claims Check: The JSON Web Token claims set is validated; to verify JWT claims, the following steps are necessary:
    a. Verify that the token has not expired.
    b. The audience (aud) claim should match the app client ID created in the Amazon Cognito User Pool.
    c. The issuer (iss) claim should match the user pool. For example, a user pool created in the selected region has an 'iss' value of: https://cognito-idp.<region>.amazonaws.com/<userpoolID>.
    d. Check the token_use claim.
    e. If you are only accepting the access token in your Web APIs, its value must be 'access.'
    f. If you are only using the ID token, its value must be 'id.'
    g. If you are using both ID and access tokens, the token_use claim must be either 'id' or 'access.'
    h. You can now trust the claims inside the token.

Implementation

          public Authentication authenticate(HttpServletRequest request) throws Exception {
String idToken = request.getHeader(this.jwtConfiguration.getHttpHeader());
if (idToken != null) {
JWKSource jwkSource = new RemoteJWKSet(new URL(jwkUrl));
JWSAlgorithm jwsAlgorithm = JWSAlgorithm.RS256;
JWSKeySelector keySelector = new JWSVerificationKeySelector(jwsAlgorithm, jwkSource);
configurableJWTProcessor.setJWSKeySelector(keySelector);
JWTClaimsSet claims = this.configurableJWTProcessor.process(this.getBearerToken(idToken),null);
validateIssuer(claims);
verifyIfAccessToken(claims);
String username = claims.getClaims().get("username").toString();
if (username != null) {
List<GrantedAuthority> grantedAuthorities = of( new SimpleGrantedAuthority("ROLE_USER"));
User user = new User(username, "", of());
return new CognitoJwtAuthentication(username, claims, grantedAuthorities);
}
}
return null;
}
}
private void validateIssuer(JWTClaimsSet claims) throws Exception {
if (!claims.getIssuer().equals(userPoolId)) {
throw new Exception(String.format("Issuer %s does not match cognito idp %s", claims.getIssuer(), this.jwtConfiguration.getUserPoolUrl()));
}
}

private void verifyIfAccessToken(JWTClaimsSet claims) throws Exception {
if (!claims.getClaim("token_use").equals("access")) {
throw new Exception("JWT Token is not an ID Token");
}
}

What if Token expires?

          public Map<String, String> refreshToken(String refreshToken) {
Map<String, String> authParams = new LinkedHashMap<String, String>() {{
put("REFRESH_TOKEN", refreshToken);
}};
InitiateAuthRequest authRequest = new InitiateAuthRequest()
.withAuthFlow(AuthFlowType.REFRESH_TOKEN_AUTH)
.withClientId(clientId)
.withAuthParameters(authParams);
InitiateAuthResult authResult = client.initiateAuth(authRequest);
AuthenticationResultType resultType = authResult.getAuthenticationResult();
return new LinkedHashMap<String, String>() {{
put("idToken", resultType.getIdToken());
put("accessToken", resultType.getAccessToken());
put("message", "Successfully login");
}};
}

Conclusions

dinsmorecomand.blogspot.com

Source: https://medium.com/@warrenferns/integrate-java-with-aws-cognito-developer-tutorial-679e6e608951

0 Response to "Aws Cognito Java Sdk Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel