【发布时间】:2019-09-27 01:28:23
【问题描述】:
Spring security antMatcher permitAll 未按预期工作。
我正在使用 kotlin 运行 Spring Boot 应用程序 当我尝试访问时
/service-status/v1/task/status
我已经在 ant matcher 中添加了这个 url,允许所有在下面的代码中
它给了我未经授权的错误
@Configuration
@EnableWebSecurity
class SecurityConfig(val authenticationEntryPoint: AuthenticationEntryPoint) : WebSecurityConfigurerAdapter() {
@Autowired
@Throws(Exception::class)
fun configureGlobal(auth: AuthenticationManagerBuilder) {
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("pass"))
.authorities("ROLE_USER")
}
@Throws(Exception::class)
override fun configure(http: HttpSecurity?) {
http?.csrf()?.disable()
?.authorizeRequests()
?.antMatchers(
"/",
"/service-status/v1/task/status",
"/*.html",
"/*.js",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.png",
"/webjars/**",
"/configuration/**",
"/v2/**",
"/swagger-resources/**",
"/**/*.js")?.permitAll()
?.anyRequest()?.authenticated()
?.and()
?.httpBasic()
?.authenticationEntryPoint(authenticationEntryPoint)
}
@Bean
fun passwordEncoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
}
出现如下错误
{
"timestamp": "2019-05-09T08:37:25.976+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/service-status/v1/task/status"
}
身份验证入口点
@Component
class AuthenticationEntryPoint : BasicAuthenticationEntryPoint(){
override fun commence(request: HttpServletRequest?, response: HttpServletResponse?, authException: AuthenticationException?) {
response?.addHeader("WWW-Authenticate", "Basic realm=$realmName")
response?.status = HttpServletResponse.SC_UNAUTHORIZED
response?.writer?.println("HTTP Status 401 - " + authException?.message)
}
override fun afterPropertiesSet() {
realmName = "service-status"
super.afterPropertiesSet()
}
}
如何解决这个问题???
【问题讨论】:
-
您是否在请求中发送了 HTTP
Authentication标头?你使用 Spring Boot 吗? -
在我看来,调用的顺序很重要,也许你可以颠倒 antMatcher("").permitAll 和 anyRequest().authenticated()。并且您可以将 HttpSecurity 参数设置为不可为空。
-
我正在使用spring boot,我没有发送任何标题
标签: spring-mvc kotlin spring-security