Skip to content

Commit 4e79aa9

Browse files
committed
feat: enhance SAML2 login handling by validating user existence and roles
1 parent 26e4fc0 commit 4e79aa9

1 file changed

Lines changed: 6 additions & 12 deletions

File tree

backend/src/main/java/com/park/utmstack/security/saml/Saml2LoginSuccessHandler.java

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.park.utmstack.security.saml;
22

3+
import com.park.utmstack.domain.User;
34
import com.park.utmstack.repository.UserRepository;
45
import com.park.utmstack.security.jwt.TokenProvider;
56
import lombok.RequiredArgsConstructor;
@@ -21,6 +22,7 @@
2122
import java.net.URI;
2223
import java.util.Collection;
2324
import java.util.Objects;
25+
import java.util.Optional;
2426

2527
import static com.park.utmstack.config.Constants.FRONT_BASE_URL;
2628

@@ -50,33 +52,25 @@ public void onAuthenticationSuccess(HttpServletRequest request,
5052
String frontBaseUrl = scheme + "://" + host;
5153

5254
Saml2AuthenticatedPrincipal samlUser = (Saml2AuthenticatedPrincipal) authentication.getPrincipal();
53-
var roles = samlUser.getAttribute("roles");
54-
5555
String username = samlUser.getName();
5656

57-
if (roles == null || ((Collection<?>) roles).isEmpty() || userRepository.findOneByLogin(username).isEmpty()) {
58-
log.error("{}: Attempted SAML2 login with invalid roles or non-existing user account.", username);
59-
failureHandler.onAuthenticationFailure(request, response,
60-
new BadCredentialsException("The provided credentials do not match any active user account or the account lacks required roles."));
61-
return;
62-
}
57+
User user = userRepository.findOneByLogin(username)
58+
.orElseThrow(() -> new BadCredentialsException("The provided credentials do not match any active user account."));
6359

64-
Collection<? extends GrantedAuthority> authorities = Objects.requireNonNull(samlUser.getAttribute("roles"))
60+
Collection<? extends GrantedAuthority> authorities = Objects.requireNonNull(user.getAuthorities())
6561
.stream()
6662
.map(Objects::toString)
6763
.filter(r -> r.startsWith("ROLE_"))
6864
.map(SimpleGrantedAuthority::new)
6965
.toList();
7066

7167
UsernamePasswordAuthenticationToken auth =
72-
new UsernamePasswordAuthenticationToken(username, null, authorities);
68+
new UsernamePasswordAuthenticationToken((Object) username, null, authorities);
7369

7470
SecurityContextHolder.getContext().setAuthentication(auth);
7571

76-
// Generate JWT
7772
String token = tokenProvider.createToken(auth, false, true);
7873

79-
// Redirect to frontend with token
8074
URI redirectUri = UriComponentsBuilder.fromUriString(frontBaseUrl)
8175
.path("/")
8276
.queryParam("token", token)

0 commit comments

Comments
 (0)