我是Spring Security的新手,想要获得当前用户的用户名。到目前为止,身份验证是有效的,但是当我尝试获取user的当前用户名时,我得到了一个anonymousUser
。
我在用Kotlin。
这就是我正在尝试的:
SecurityConfig.kt:
@Configuration
@EnableWebSecurity(debug = true)
class SecurityConfig(): WebSecurityConfigurerAdapter(){
@Throws(Exception::class)
override fun configure(auth: AuthenticationManagerBuilder){
auth.inMemoryAuthentication()
.withUser("user").password("123456").roles("USER")
.and()
.withUser("admin").password("123456").roles("USER", "ADMIN")
}
@Throws(Exception::class)
override fun configure(http: HttpSecurity){
http.authorizeRequests()
.antMatchers("v1/mobile/**")
.authenticated().and().httpBasic()
}
...
}
AuthorizationServerConfig.kt:
//class header not shown here
@Throws(Exception::class)
override fun configure(clients: ClientDetailsServiceConfigurer){
clients
.inMemory()
.withClient("spiritdev")
.secret("thisissecret")
.authorities("USER","ADMIN")
.scopes("all")
.authorizedGrantTypes("password","client_credentials")
}
首先,我像这样在Postman中进行身份验证:
这样做效果很好。但是当使用像http://localhost:8080/v1/mobile/tickets
这样的方法时,它会记录当前用户名(代码如下):
var currentPrincipalName: String? =
SecurityContextHolder.getContext().authentication.principal.toString()
logger.info { "currentPrincipalName!" }
logger.info { currentPrincipalName }
输出显示为anonymousUser
。
我不明白为什么。谁能告诉我我做错了什么?感谢大家的帮助!
发布于 2020-11-04 19:51:49
让我们尝试禁用匿名身份验证-
http .csrf().disable()
.formLogin().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("v1/mobile/**")
.authenticated().and().httpBasic()
我假设您正在使用right token作为auth token端点请求的响应中接收的自动化头,如屏幕截图所示。
https://stackoverflow.com/questions/64679097
复制相似问题