springsecurity設定不同角色登入後跳轉到不同頁面
阿新 • • 發佈:2019-02-19
要在WebSecurityConfig中的configure方法中配置登入
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/home").successHandler(new LoginSuccessHandle())
.permitAll()
重點在.successHandler
建立一個LoginSuccessHandle的類
LoginSuccessHandle類中根據使用者是ROLE_ADMIN還是其他角色使用response.sendRedirect跳轉到了不同的頁面。class LoginSuccessHandle implements AuthenticationSuccessHandler { public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException,ServletException { Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities()); String path = request.getContextPath() ; String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; if (roles.contains("ROLE_ADMIN")){ response.sendRedirect(basePath+"adminHome"); return; } response.sendRedirect(basePath+"home"); }