-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCustomizeAuthenticationSuccessHandler.java
More file actions
70 lines (61 loc) · 2.51 KB
/
Copy pathCustomizeAuthenticationSuccessHandler.java
File metadata and controls
70 lines (61 loc) · 2.51 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ca.gc.tbs.config;
import java.io.IOException;
import java.net.URI;
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.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
@Component
public class CustomizeAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
@GetMapping(value = "/login")
public void onAuthenticationSuccess(
HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null
|| savedRequest.getRedirectUrl().contains("signin")
|| !isSameOrigin(savedRequest.getRedirectUrl(), request)) {
for (GrantedAuthority auth : authentication.getAuthorities()) {
if ("ADMIN".equals(auth.getAuthority())) {
response.sendRedirect("/u/index");
} else {
response.sendRedirect("/pageFeedback");
}
}
return;
}
clearAuthenticationAttributes(request);
// Use the DefaultSavedRequest URL
String targetUrl = savedRequest.getRedirectUrl();
logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
private boolean isSameOrigin(String url, HttpServletRequest request) {
if (url.startsWith("/")) {
return true;
}
try {
URI uri = URI.create(url);
return !uri.isAbsolute() || request.getServerName().equalsIgnoreCase(uri.getHost());
} catch (IllegalArgumentException e) {
return false;
}
}
}