Spring Security 在除 get 之外的所有请求上总是收到 401 错误

问题描述 投票:0回答:1

我对 Spring security 非常陌生,我的 WebSecurityConfiguration.kt 类如下所示:

@Configuration
@EnableWebSecurity
class WebSecurityConfiguration: WebSecurityConfigurerAdapter() {

@Autowired
lateinit var authenticationEntryPoint: WebSecurityEntryPoint

@Autowired
@Throws(Exception::class)
fun configureGlobal(auth: AuthenticationManagerBuilder) {
    auth.inMemoryAuthentication()
            .withUser("user").password(passwordEncoder().encode("du"))
            .authorities(Role.ADMIN.poziom)
}

@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
    http.authorizeRequests()
            .antMatchers("/securityNone").permitAll()
            .antMatchers("/marka/insert").authenticated() // but I beted this would help
            .anyRequest().authenticated() // I know this should cover all requests
            .and()
            .httpBasic()
            .authenticationEntryPoint(authenticationEntryPoint)
            .and()
            .formLogin()



}

@Bean
fun passwordEncoder(): PasswordEncoder {
    return BCryptPasswordEncoder()
}




}

我的问题是,当我发出任何请求时,我总是收到 401 或 403 错误(在相同情况下有时是 401,有时是 403)错误代码,但除了 GET 请求返回 200 代码并且似乎有效。还可以通过浏览器中的登录表单登录。 我正在使用邮递员发出请求,我使用基本身份验证,是的,我在发出请求之前单击预览身份验证

我做错了什么?请各位朋友帮忙。如果不解决这个问题,我就无法在这个项目中做任何其他事情。

[编辑 30 III 2020]

我已经部分解决了问题:

如果通过前端或curl命令发出请求,则请求有效 使用选项 -u user:du 所以 JSON 的完整命令如下所示:

{
"id" : -1,
 "nazwa" : "Mercedes",
 "models" : [ ]
}

完整的curl命令是:

curl -u user:du -X PUT -d @mercedes.json http://localhost:8091/marka/insert -H "Content-Type: application/json"

如果 mercedes.json 位于调用命令的目录中。

但是

通过邮递员发送请求仍然不起作用。

朋友们有什么想法吗?

spring spring-boot kotlin spring-security postman
1个回答
0
投票

我知道这个问题创建已经过去了 4 年,但是...检查您的 CORS 和 CSRF 政策。您也可以通过此对其进行硬编码(不适用于生产):

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  return http.authorizeHttpRequests(expressionInterceptUrlRegistry ->
                  expressionInterceptUrlRegistry....
          .csrf().disable()
          .cors().disable()
          .build();
}
© www.soinside.com 2019 - 2024. All rights reserved.