【问题标题】:Why has Spring duplicate fields in Authentication and UserDetails?为什么 Spring 在 Authentication 和 UserDetails 中有重复字段?
【发布时间】:2012-04-11 20:11:39
【问题描述】:

在使用 Spring Security 实现一些安全方面时,我注意到 AuthenticationUserDetails 都有重复的方法,例如 getAuthoritiesgetCredentials 等等。

这背后的目的是什么?对我来说,这似乎是一种无用的冗余。

编辑:因为人们懒得检查签名。两个接口都有相同的方法。我不是指getCredentialsgetAuthorities 是相同的。为什么要让人们做出这样的假设?

【问题讨论】:

  • 我也对此感到惊讶,但我没有看到一个好的解释。我实现了一个自定义 AuthenticationProvider 并且在 authenticate() 方法中我必须返回这个:return new UsernamePasswordAuthenticationToken(new User(username,password, AUTHORITIES),password,AUTHORITIES);
  • 在对 Spring Security 进行了几次检查后,我认为是这样的:Authentication 仅供 Spring Security 使用。 UserDetails 仅用于客户端代码。由于不同的编码日期,它们以某种方式相交。所以请记住,Authentication 不适合您。希望他们能在 Spring Security 3.0 中清理它。

标签: spring authentication spring-security


【解决方案1】:

UserDetails用于安全目的,它只是一个“用户信息”bean。 Spring Security 使用 Authentication 实例。所以Authentication 实例通常只有让用户登录所需的信息(基本上是用户名、凭据和角色)。 UserDetails 更通用,可以包含与用户管理相关的任何内容(例如联系信息、帐户信息、照片等)。

通常,您将拥有一个由 UserDetails 实例支持的 Authentication 实例。

【讨论】:

  • 似乎是这样,但我仍然能够在几个 Spring 课程中找到UserDetails#getPassword 的多个电话。我想这是遗产。 UserDetails 类不像 Authentication 类那样通用。
【解决方案2】:
getAuthorities 

用于基于角色的安全性。它在 SpringSecurity 中通常是有用的功能。

getCredentials

用于获取密码或散列密码以检查主体是否正确。在安全方面也是必要的方法。

如果您确定不需要此功能,您可以用空的方法覆盖此方法。

【讨论】:

    猜你喜欢
    • 2014-03-04
    • 2019-01-17
    • 2013-07-18
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多