【发布时间】:2021-02-17 02:10:03
【问题描述】:
我是 Spring Security 的新手,想获取当前用户的用户名。到目前为止,身份验证有效,但是当尝试获取用户的当前用户名时,我得到了一个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。
我不明白为什么。谁能告诉我我做错了什么?感谢您的每一个帮助!
【问题讨论】:
-
httpBasic()不是 oauth2 和令牌。当您想要访问受保护的端点时,您必须发送用户名和密码,base64 编码在Authorization标头中。例如Authorization: Basic Zm9vYmFyOnBhc3N3b3JkMTIz,您会得到一个 cookie,每次与端点通信时都需要包含该 cookie。 -
@ThomasAndolf 是的,是的,这就是我正在做的。我得到一个 Bearer 令牌并通过标头在以下请求中发送它,使用
Authorization作为键和Bearer myToken作为值。 -
但是邮递员的照片告诉我你正在发布grant_type?以及令牌端点的用户名和密码?您提供的代码中没有任何 oauth2 内容,并且 spring security 不包括令牌颁发者,如果您使用的是 oauth2,那么 oauth2 代码在哪里?在我看来,您正在混淆 oauth2 和基本身份验证。
标签: java spring spring-boot kotlin spring-security