forked from movaco/spring-boot-aws-multi-tenant-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CognitoAuthenticationManager.java
48 lines (42 loc) · 1.8 KB
/
CognitoAuthenticationManager.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
46
47
48
package de.movaco.server.security.cognito;
import static de.movaco.server.security.Roles.withRolePrefix;
import de.movaco.server.security.Roles;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
@Component
public class CognitoAuthenticationManager implements AuthenticationManager {
private final CognitoAccessTokenReader accessTokenReader;
private final CognitoTenantResolver tenantResolver;
@Autowired
public CognitoAuthenticationManager(
CognitoAccessTokenReader accessTokenReader, CognitoTenantResolver tenantResolver) {
this.accessTokenReader = accessTokenReader;
this.tenantResolver = tenantResolver;
}
@Override
public Authentication authenticate(Authentication authentication) {
if (authentication instanceof CognitoAuthenticationToken) {
return authentication;
}
String accessToken = (String) authentication.getPrincipal();
List<String> roles = this.accessTokenReader.getRoles(accessToken);
List<GrantedAuthority> authorities =
roles.stream()
.map(role -> new SimpleGrantedAuthority(withRolePrefix(role)))
.collect(Collectors.toList());
String userName = this.accessTokenReader.getUserName(accessToken);
String tenant;
if (roles.contains(Roles.SUPER_ADMIN)) {
tenant = null;
} else {
tenant = this.tenantResolver.getTenant(userName);
}
return new CognitoAuthenticationToken(userName, accessToken, authorities, tenant);
}
}