【问题标题】:Spring Security returning anonymous user after successful authenticaitonSpring Security 认证成功后返回匿名用户
【发布时间】: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


【解决方案1】:

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

http .csrf().disable()
            .formLogin().disable()
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers("v1/mobile/**")
            .authenticated().and().httpBasic()

我假设您使用正确的令牌作为响应身份验证令牌端点请求而收到的授权标头,如屏幕截图所示。

【讨论】:

  • 这会做什么?
  • 我只需要获取当前认证用户的用户名
  • 没有找到认证的方法
  • @IonicMan 感谢您的反对。我已经更新了我的答案。它正在接受匿名身份验证。因此想禁用它,看看主体是否给你需要。
  • 让我知道它是否有效。我会建议通过这个 git repo 并在逐步调试模式下运行整个代码。您可以在过滤器上设置调试点。这样,您将了解向您的代码发送请求时发生的每一个步骤。 github.com/cvillaseca/mobileAPI
猜你喜欢
  • 2019-06-03
  • 1970-01-01
  • 2019-11-30
  • 2021-10-27
  • 1970-01-01
  • 2022-09-23
  • 2012-02-21
  • 1970-01-01
  • 2014-08-09
相关资源
最近更新 更多