Spring安全:重定向未经授权的URL

时间:2015-10-08 01:17:49

标签: spring spring-mvc spring-security

    @PreAuthorize("hasPermission(#id,'Integer','write')")
    @RequestMapping(value="events/{id}/edit",method=RequestMethod.GET)
    public String edit(Model model,@PathVariable("id") int id) {
        model.addAttribute("event", eventService.getEvent(id));
        return "events/edit";
    }

安全配置

public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/", "/index", "/register", "/regitrationConfirm", "/forgotPassword", "/accountRecovery", "/passwordReset", "/public/**").permitAll()
                .antMatchers(HttpMethod.POST, "/register", "/accountRecovery","/passwordReset").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .loginPage("/login?error")
                .permitAll()
                .failureHandler(authFailureHandler)
                .and()
            .rememberMe()
                .tokenValiditySeconds(3600)
                .key("rememberTracker")
                .and()
            .logout()
                .permitAll()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/")
                .and()
            .sessionManagement()
                 .maximumSessions(1)
                 .expiredUrl("/login?expired");

    }
}

如果授权失败,我想重定向或向用户显示自定义页面。有办法吗?

使用spring安全代码进行了更新。

由于

1 个答案:

答案 0 :(得分:4)

我更新了SecurityConfig以添加 failureUrl successHandler

public class SecurityConfig extends WebSecurityConfigurerAdapter{
 @Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/", "/index", "/register", "/regitrationConfirm", "/forgotPassword", "/accountRecovery", "/passwordReset", "/public/**").permitAll()
            .antMatchers(HttpMethod.POST, "/register", "/accountRecovery","/passwordReset").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .loginPage("/login?error")
            .permitAll()
            .failureUrl("/your-unsuccessful-authentication-url-here") 
            .successHandler(yourSuccesshandler) //create your success handler to redirect the user to different places depending on his role 
            //.failureHandler(authFailureHandler) I deleted this line, we just need a redirect
            .and()
        .rememberMe()
            .tokenValiditySeconds(3600)
            .key("rememberTracker")
            .and()
        .logout()
            .permitAll()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/")
            .and()
        .sessionManagement()
             .maximumSessions(1)
             .expiredUrl("/login?expired");

    }
}

成功处理程序

public class SuccessAuthenticationHandler implements AuthenticationSuccessHandler{
public SuccessAuthenticationHandler(){

}

@Override
public void onAuthenticationSuccess(HttpServletRequest request, 
        HttpServletResponse response, Authentication auth) throws     IOException, ServletException {
    HttpSession session = request.getSession(); 
    User user =   (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
    String redirect = ""; 
    if(user != null){
        session.setAttribute("username", user.getUsername());
        if(user.getAuthorities().contains(new   SimpleGrantedAuthority("ROLE_ADMIN")) 
                || user.getAuthorities().contains(new   SimpleGrantedAuthority("ROLE_SUPER_ADMIN")))
            redirect = "admin/"; 
        else if(user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_YOUR_ROLE")))
            redirect = "yourrole/"; 
    }
    if(redirect.isEmpty())
        redirect = "signin"; 

    response.sendRedirect(redirect); 
}

}