首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Spring Security认证成功后返回匿名用户

Spring Security认证成功后返回匿名用户
EN

Stack Overflow用户
提问于 2020-11-04 19:21:30
回答 1查看 400关注 0票数 0

我是Spring Security的新手,想要获得当前用户的用户名。到目前为止,身份验证是有效的,但是当我尝试获取user的当前用户名时,我得到了一个anonymousUser

我在用Kotlin。

这就是我正在尝试的:

SecurityConfig.kt:

代码语言:javascript
复制
@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:

代码语言:javascript
复制
//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这样的方法时,它会记录当前用户名(代码如下):

代码语言:javascript
复制
var currentPrincipalName: String? = 
SecurityContextHolder.getContext().authentication.principal.toString()

logger.info { "currentPrincipalName!" }
logger.info { currentPrincipalName }

输出显示为anonymousUser

我不明白为什么。谁能告诉我我做错了什么?感谢大家的帮助!

EN

回答 1

Stack Overflow用户

发布于 2020-11-04 19:51:49

让我们尝试禁用匿名身份验证-

代码语言:javascript
复制
http .csrf().disable()
            .formLogin().disable()
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers("v1/mobile/**")
            .authenticated().and().httpBasic()

我假设您正在使用right token作为auth token端点请求的响应中接收的自动化头,如屏幕截图所示。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64679097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档