Spring安全性 - REST调用获取404错误

时间:2016-07-11 18:42:29

标签: spring spring-security

我有一个使用Spring Security保护的应用程序。我使用注释启用它:

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

然后我通过覆盖configure()方法来配置它:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
    .and()
        .addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
        .exceptionHandling()
        .accessDeniedHandler(new CustomAccessDeniedHandler())
        .authenticationEntryPoint(authenticationEntryPoint)
    .and()
        .formLogin()
        .loginProcessingUrl("/api/authentication")
        .successHandler(ajaxAuthenticationSuccessHandler)
        .failureHandler(ajaxAuthenticationFailureHandler)
        .usernameParameter("username")
        .passwordParameter("password")
        .permitAll()
    .and()
        .logout()
        .logoutUrl("/api/logout")
        .logoutSuccessHandler(ajaxLogoutSuccessHandler)
        .deleteCookies("JSESSIONID", "CSRF-TOKEN")
        .permitAll()
    .and()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .authorizeRequests()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/admin/**").hasAuthority(AuthoritiesConstants.ADMIN);
}

当我尝试访问主页时,我正在重定向到登录页面,但是一旦我输入我的凭据并尝试登录,我就会得到/ api / authentication REST调用的404 not found错误。 / p>

loginProcessingUrl()方法指定要进行的调用。我不需要自己实现这个,因为Spring应该为我做到这一点?还有什么我想念的吗?

2 个答案:

答案 0 :(得分:1)

As far as I understood the login-processing-url, you have to handle the login process by yourself if you specify a special url to process the login.

Have you tried to just remove this line?:

.loginProcessingUrl("/api/authentication")

As you use springs default login form, you should just be able to remove the line and the generated login form will also change.

Maybe there's another way to solve your problem but this should also work.

If you're looking for an example on how to use custom login forms, this link might helo you.

答案 1 :(得分:0)

我想通了,这是我需要改变的几件事:

  1. 我没有初始化程序类。在我添加了以下类之后,我从404未找到错误转到403错误:

    公共类SecurityWebApplicationInitializer             扩展AbstractSecurityWebApplicationInitializer { }

  2. 注意:您还可以在web.xml中添加相应的过滤器(在此处阅读更多内容:http://websystique.com/spring-security/spring-security-4-hello-world-annotation-xml-example/

    1. 上述更改使用Spring容器注册安全性。但我仍然需要禁用CSRF,因为我没有从客户端发送正确的令牌。对于我的应用程序,我还不需要CSRF所以我暂时禁用它。但是,建议不要这样做,所以在进行此更改之前,请确保知道自己在做什么:

      http.csrf()。禁用()