I am building a web application that uses AWS Cognito for authentication, and I was wondering how I could allow people to choose their own roles at sign-up. I followed a tutorial that helped me create a role-based login, but it doesn’t allow users to choose their own role. It just gives them a default role and doesn’t let them pick one. Could someone please let me know how that’s done? Below is the code that the tutorial helped me with (they would chose either owner or customer at sign up).
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class adminEndpoint {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminEndpoint() {
return "Admin content";
}
}
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
for (GrantedAuthority auth : authentication.getAuthorities()) {
DefaultOidcUser defaultOidcUser = (DefaultOidcUser) authentication.getPrincipal();
Map<String, Object> userAttributes = defaultOidcUser.getAttributes();
System.out.println(userAttributes);
if ("ROLE_ADMIN".equals(auth.getAuthority())) {
System.out.println(userAttributes.get("cognito:username") + " Is Admin!");
response.sendRedirect("/admin/greetMe");
} else if ("ROLE_USER".equals(auth.getAuthority())) {
System.out.println(userAttributes.get("cognito:username") + " Is User!");
response.sendRedirect("/user/greetMe");
}
}
}
}
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.web.util.UriComponentsBuilder;
public class CustomLogoutHandler extends SimpleUrlLogoutSuccessHandler {
private final String logoutUrl;
private final String logoutRedirectUrl;
private final String clientId;
public CustomLogoutHandler(String logoutUrl, String logoutRedirectUrl, String clientId) {
this.logoutUrl = logoutUrl;
this.logoutRedirectUrl = logoutRedirectUrl;
this.clientId = clientId;
}
@Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) {
return UriComponentsBuilder
.fromUri(URI.create(logoutUrl))
.queryParam("client_id", clientId)
.queryParam("logout_uri", logoutRedirectUrl)
.encode(StandardCharsets.UTF_8)
.build()
.toUriString();
}
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
private final CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
@Value("${aws.cognito.logoutUrl}")
private String logoutUrl;
@Value("${aws.cognito.logout.success.redirectUrl}")
private String logoutRedirectUrl;
@Value("${spring.security.oauth2.client.registration.cognito.client-id}")
private String clientId;
public SecurityConfiguration(
CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler) {
this.customizeAuthenticationSuccessHandler = customizeAuthenticationSuccessHandler;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(request -> request.requestMatchers("/").permitAll()
.requestMatchers("/admin/*").hasRole("ADMIN")
.requestMatchers("/user/*").hasAnyRole("ADMIN", "USER").anyRequest().authenticated())
.oauth2Login(oauth -> oauth.redirectionEndpoint(endPoint -> endPoint.baseUri("/login/oauth2/code/cognito"))
.userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userAuthoritiesMapper(userAuthoritiesMapper()))
.successHandler(customizeAuthenticationSuccessHandler))
.logout(httpSecurityLogoutConfigurer -> {
httpSecurityLogoutConfigurer.logoutSuccessHandler(
new CustomLogoutHandler(logoutUrl, logoutRedirectUrl, clientId));
});
return http.build();
}
@Bean
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
return (authorities) -> {
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
try {
OidcUserAuthority oidcUserAuthority = (OidcUserAuthority) new ArrayList<>(authorities).get(
0);
mappedAuthorities = ((ArrayList<?>) oidcUserAuthority.getAttributes()
.get("cognito:groups")).stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toSet());
} catch (Exception exception) {
System.out.println("Not Authorized!");
System.out.println(exception.getMessage());
}
return mappedAuthorities;
};
}
}
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class WelcomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Welcome To The Index Page!");
return "index";
}
@GetMapping("/admin/greetMe")
public String adminGreet(Model model) {
String response = "Welcome admin! You developed an amazing website!";
model.addAttribute("response", response);
return "greeting";
}
@GetMapping("/user/greetMe")
public String userGreet(Model model) {
String response = "Welcome user! God bless you with an amazing future!";
model.addAttribute("response", response);
return "greeting";
}
}
3