如何允许使用Spring Security转发到外部URL

时间:2015-08-03 20:39:29

标签: java spring spring-mvc spring-security forward

我想知道如何才能使我的"重定向:"使用Spring Security。 All / auth * pathes正常工作。但是当它出现[1]时,它并没有重定向。 Spring Security 4.0.2.RELEASE,Spring MVC 4.0.8.RELEASE

@Controller
@RequestMapping(value = "/auth")
public class SomeAuthController {

    @RequestMapping(value = "/external")
    public String externalAuth(...) {
        if(someCondition) return "redirect:" + someExternalUrl; // [1] https://external-service.com 
        else return "redirect:/"
    }

}



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired 
    public void registerGlobalAuthentication(AuthenticationManagerBuilder auth, 
                                             ShaPasswordEncoder shaPasswordEncoder,
                                             List<AuthenticationProvider> authProviders)
                                                                throws Exception {
        for(AuthenticationProvider provider : authProviders) auth.authenticationProvider(provider);
    }

    @Bean(name="myAuthenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/resources/**").permitAll();

        http.authorizeRequests().antMatchers("/auth/**", "/").permitAll().anyRequest().authenticated();

        http.formLogin()
                .loginPage("/auth/login")
                .loginProcessingUrl("/j_spring_security_check")
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .failureUrl("/auth/login?error")
                .permitAll();

        http.logout()
                .permitAll()
                .logoutUrl("/auth/logout")
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true);
    }


}

1 个答案:

答案 0 :(得分:1)

好的伙计们。这是我的答案。希望它会帮助某人。 第一件事是在安全配置bean中启用JSR250。

@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

之后我为包含重定向的方法添加了@PermitAll注释。

@PermitAll
@RequestMapping(value = "/external")
public String externalAuth(...) {
    if(someCondition) return "redirect:" + someExternalUrl; // [1] https://external-service.com 
    else return "redirect:/"
}

这就是全部。有一个很好的调试J