弹簧安全403错误

ken*_*ken 39 spring spring-mvc spring-security

我正在尝试按照网络指南使用Spring安全保护我的网站.所以在我的服务器端,WebSecurityConfigurerAdapter和控制器看起来像这样

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
implements ApplicationContextAware {

@Override
protected void registerAuthentication(AuthenticationManagerBuilde r authManagerBuilder) throws Exception {
authManagerBuilder.inMemoryAuthentication()
.withUser("user").password("password").roles("ADMI N");
}
}

@Controller
//@RequestMapping("/course")
public class CourseController implements ApplicationContextAware{

@RequestMapping(value="/course", method = RequestMethod.GET, produces="application/json")
public @ResponseBody List<Course> get(// The critirion used to find.
@RequestParam(value="what", required=true) String what,
@RequestParam(value="value", required=true) String value) {
//.....
}

@RequestMapping(value="/course", method = RequestMethod.POST, produces="application/json")
public List<Course> upload(@RequestBody Course[] cs) {
}
}
Run Code Online (Sandbox Code Playgroud)

令我困惑的是服务器没有响应POST/DELETE方法,而GET方法工作正常.顺便说一下,我在客户端使用RestTemplate.例外情况是:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:574)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:530)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:487)
    at org.springframework.web.client.RestTemplate.delete(RestTemplate.java:385)
    at hello.Application.createRestTemplate(Application.java:149)
    at hello.Application.main(Application.java:99)
Run Code Online (Sandbox Code Playgroud)

我在互联网上搜索了好几天.仍然没有线索.请帮忙.非常感谢

Rob*_*nch 93

问题可能是由于CSRF保护.如果用户不在Web浏览器中使用您的应用程序,则可以安全地禁用CSRF保护.否则,您应确保在请求中包含CSRF令牌.

禁用CSRF保护,您可以使用以下命令:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig
    extends WebSecurityConfigurerAdapter implements ApplicationContextAware {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...
            .csrf().disable();
    }

    @Override
    protected void registerAuthentication(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("ADMIN");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢罗伯。这是csrf问题。是的,我不希望我的用户使用Web浏览器来使用我的应用程序。在客户端运行良好。但是在服务器端我得到了:osweb.servlet.PageNotFound:请求方法'POST'不支持Strange。我应该忽略它吗? (2认同)
  • 我认为PageNotFound是我要解决的单独问题。您可能需要发布另一个问题,并提供有关此错误的更多信息。 (2认同)

小智 8

该问题很可能是由于 CSRF 保护造成的,同意最上面的评论。然而,通过使用此配置,该方法取消了 spring security。

所以你可以使用下面的代码:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

        auth
                .inMemoryAuthentication()
                    .withUser("admin")
                        .password(encoder.encode("admin"))
                        .roles("ADMIN", "USER")
                .and()
                    .withUser("user")
                        .password(encoder.encode("password"))
                        .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();

        http.csrf().disable();
    }
}
Run Code Online (Sandbox Code Playgroud)


Oma*_*azi 5

该问题可能与 CSRF 或 CORS 安全保护有关。

  • 对于 CSRF:如果应用程序用户没有从浏览器使用它,您可以禁用它。
  • 对于 CORS:您可以指定来源并允许 HTTP 方法。

以下代码禁用 CSRF 并允许所有来源和 HTTP 方法。所以使用时要注意。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  implements WebMvcConfigurer {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*");
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 不要禁用 csrf。这是一个巨大的安全风险。如果您不知道这一点,我**强烈**建议您在禁用它之前_查找_它是什么。 (2认同)

小智 5

将服务升级到 Spring Boot 3 后,我遇到了这个问题。自动测试开始失败,状态为 403。经过一番头痛之后,我发现这是由于从 URL 匹配中删除尾部斜杠引起的。 此处描述了更改。因此请检查您调用的 URL 是否正确。

错误的:

/api/foo/
Run Code Online (Sandbox Code Playgroud)

正确的:

/api/foo
Run Code Online (Sandbox Code Playgroud)