source: src/main/java/edu/gjoko/schedlr/config/AppAuthenticationSuccessHandler.java@ 401a211

Last change on this file since 401a211 was cf9cdbf, checked in by Gjoko <goko_kostadinov@…>, 21 months ago

Initial commit.

  • Property mode set to 100644
File size: 2.7 KB
Line 
1package edu.gjoko.schedlr.config;
2
3import org.apache.commons.logging.Log;
4import org.apache.commons.logging.LogFactory;
5import org.springframework.security.core.Authentication;
6import org.springframework.security.core.GrantedAuthority;
7import org.springframework.security.web.DefaultRedirectStrategy;
8import org.springframework.security.web.RedirectStrategy;
9import org.springframework.security.web.WebAttributes;
10import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
11
12import javax.servlet.ServletException;
13import javax.servlet.http.HttpServletRequest;
14import javax.servlet.http.HttpServletResponse;
15import javax.servlet.http.HttpSession;
16import java.io.IOException;
17import java.util.Collection;
18import java.util.HashMap;
19import java.util.Map;
20
21public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
22
23 protected Log logger = LogFactory.getLog(this.getClass());
24 private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
25
26 @Override
27 public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
28 handle(request, response, authentication);
29 clearAuthenticationAttributes(request);
30 }
31
32 protected void handle(HttpServletRequest request,
33 HttpServletResponse response,
34 Authentication authentication) throws IOException {
35 String targetUrl = determineTargetUrl(authentication);
36
37 if (response.isCommitted()) {
38 logger.debug("Response has already been committed. Unable to redirect to " +
39 targetUrl);
40 return;
41 }
42 redirectStrategy.sendRedirect(request, response, targetUrl);
43 }
44
45 protected String determineTargetUrl(final Authentication authentication) {
46 Map<String, String> roleTargetUrlMap = new HashMap<>();
47 roleTargetUrlMap.put("DATE", "/date");
48 roleTargetUrlMap.put("GUESS_NUMBER", "/number");
49
50 final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
51 for (final GrantedAuthority grantedAuthority : authorities) {
52 String authorityName = grantedAuthority.getAuthority();
53 if (roleTargetUrlMap.containsKey(authorityName)) {
54 return roleTargetUrlMap.get(authorityName);
55 }
56 }
57 throw new IllegalStateException();
58 }
59
60 protected void clearAuthenticationAttributes(HttpServletRequest request) {
61 HttpSession session = request.getSession(false);
62 if (session == null) {
63 return;
64 }
65 session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
66 }
67}
Note: See TracBrowser for help on using the repository browser.