The Custom Authentication Success Handle

2022. 1. 20. 12:28·Programming/Spring

Typically these implementations will determine the URL after login and perform a redirect to that URL. This implementation is going to determine the URL to redirect the user to after login based on the role of the user. 

 

First of all, we need to override the onAuthenticationSuccess method:

public class MySimpleUrlAuthenticationSuccessHandler
  implements AuthenticationSuccessHandler {
 
    protected Log logger = LogFactory.getLog(this.getClass());

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication)
      throws IOException {
 
        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }

 

Our customized method calls two helper methods:

protected void handle(
        HttpServletRequest request,
        HttpServletResponse response, 
        Authentication authentication
) throws IOException {

    String targetUrl = determineTargetUrl(authentication);

    if (response.isCommitted()) {
        logger.debug(
                "Response has already been committed. Unable to redirect to "
                        + targetUrl);
        return;
    }

    redirectStrategy.sendRedirect(request, response, targetUrl);
}

 

Where the following method does the actual work and maps the user to the target URL:

protected String determineTargetUrl(final Authentication authentication) {

    Map<String, String> roleTargetUrlMap = new HashMap<>();
    roleTargetUrlMap.put("ROLE_USER", "/homepage.html");
    roleTargetUrlMap.put("ROLE_ADMIN", "/console.html");

    final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (final GrantedAuthority grantedAuthority : authorities) {
        String authorityName = grantedAuthority.getAuthority();
        if(roleTargetUrlMap.containsKey(authorityName)) {
            return roleTargetUrlMap.get(authorityName);
        }
    }

    throw new IllegalStateException();
}

 

Note that this method will return the mapped URL for the first role the user has. So if a user has multiple roles, the mapped URL will be the one that matches the first role given in the authorities collection.

protected void clearAuthenticationAttributes(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    if (session == null) {
        return;
    }
    session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}

 

The determineTargetUrl – which is the core of the strategy – simply looks at the type of user (determined by the authority) and picks the target URL based on this role.

So, an admin user – determined by the ROLE_ADMIN authority – will be redirected to the console page after login, while the standard user – as determined by ROLE_USER – will be redirected to the homepage.

 


참고

https://www.baeldung.com/spring_redirect_after_login

'Programming > Spring' 카테고리의 다른 글

REST API  (0) 2022.01.25
Spring Security: Authentication  (0) 2022.01.21
OAuth2(3) OAuth2 Client 라이브러리 사용 카카오 로그인  (0) 2022.01.20
OAuth2(2) OAuth2 Client 라이브러리 없이 카카오 로그인  (0) 2022.01.20
OAuth2(1) OAuth2 구성 및 동작  (0) 2022.01.18
'Programming/Spring' 카테고리의 다른 글
  • REST API
  • Spring Security: Authentication
  • OAuth2(3) OAuth2 Client 라이브러리 사용 카카오 로그인
  • OAuth2(2) OAuth2 Client 라이브러리 없이 카카오 로그인
사랑우주인
사랑우주인
  • 사랑우주인
    lovelyAlien
    사랑우주인
  • 전체
    오늘
    어제
  • 글쓰기
    관리
    • 분류 전체보기 (209)
      • Programming (4)
        • Spring (28)
        • Java (46)
        • JPA (2)
        • 디자인 패턴 (5)
        • 개발&아키텍처 (0)
      • Network (14)
      • OS (19)
      • Database (1)
      • Kubernetes (0)
      • Kafka (2)
      • Algorithm (49)
        • BaekJoon (1)
        • Programmers (19)
        • Algorithm (5)
        • Socar (2)
        • LeetCode (19)
      • Interview (2)
      • Issues (2)
      • DotJoin (1)
      • Git (4)
      • 독서 (3)
      • 끄적끄적 (1)
      • 외부활동 (26)
        • 항해플러스 (2)
        • JSCODE 네트워크 (19)
        • JSCODE 자바 (5)
      • SQL (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • GitHub
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    디자인 패턴
    LinkedList
    준영속 엔티티
    clone graph
    BFS
    운영체제
    @JsonNaming
    AuthenticationSuccessHandler
    RR
    Oauth2
    @JsonProperty
    OS
    lower bounded wildcards
    Generic
    pacific atlantic water flow
    runner 기법
    JSCode
    algorithm
    Climbing Stairs
    wildcards
    제네릭
    fcfs
    Reorder List
    minimum number of arrows to burst balloons
    추상화 클래스
    Thread
    Process
    rotting oranges
    트랜잭션
    socar
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
사랑우주인
The Custom Authentication Success Handle
상단으로

티스토리툴바