forked from movaco/spring-boot-aws-multi-tenant-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CognitoTenantResolver.java
45 lines (39 loc) · 1.72 KB
/
CognitoTenantResolver.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package de.movaco.server.security.cognito;
import com.amazonaws.auth.AWSCredentialsProviderChain;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProvider;
import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProviderClient;
import com.amazonaws.services.cognitoidp.model.AdminGetUserRequest;
import com.amazonaws.services.cognitoidp.model.AdminGetUserResult;
import com.amazonaws.services.cognitoidp.model.AttributeType;
import de.movaco.server.exception.TenantNotDefinedForUserException;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class CognitoTenantResolver {
@Value("${cognito.poolId}")
private String poolId;
private final AWSCredentialsProviderChain awsCredentialsProviderChain;
public CognitoTenantResolver() {
this.awsCredentialsProviderChain = new DefaultAWSCredentialsProviderChain();
}
String getTenant(String userName) {
AWSCognitoIdentityProvider provider =
AWSCognitoIdentityProviderClient.builder()
.withCredentials(this.awsCredentialsProviderChain)
.build();
AdminGetUserRequest adminGetUserRequest =
new AdminGetUserRequest().withUserPoolId(this.poolId).withUsername(userName);
AdminGetUserResult adminGetUserResult = provider.adminGetUser(adminGetUserRequest);
Optional<AttributeType> first =
adminGetUserResult.getUserAttributes().stream()
.filter(a -> a.getName().equals("custom:tenant"))
.findFirst();
if (first.isPresent()) {
return first.get().getValue();
} else {
throw new TenantNotDefinedForUserException();
}
}
}