【问题标题】:Problems in UserDetailsService in Spring SecuritySpring Security 中 UserDetailsS​​ervice 的问题
【发布时间】:2011-09-01 12:08:06
【问题描述】:

我正在为我的 Spring 安全设置使用自定义的 UserDetailsS​​ervice。 自定义的 UserDetailsS​​ervice 只有一种方法覆盖 UserDetailsS​​ervice 中的 loadUserByUsername(final String username)。

我在 applicationConext-security.xml 中有以下配置:

<authentication-manager alias="myAuthenticationManager">
      <authentication-provider user-service-ref="userDetailsService"/>
</authentication-manager>

<beans:bean id="userDetailsService"
    class="temp.com.JpaUserDetailsService" />

但是,当我尝试使用用户名登录时,我收到错误提示“用户名”为空。我想知道用户名来自哪里,如何避免它为空?

【问题讨论】:

  • 你能发布 JpaUserDetailsS​​ervice 吗?它是否实现了 UserDetailsS​​ervice?不会错过要注入的数据源吗?

标签: spring spring-security


【解决方案1】:

这有多种可能性,并且由于您没有发布任何堆栈跟踪,因此不清楚问题出在您的代码还是配置中:

  • 您已明确配置过滤器链,并且缺少过滤器或标准过滤器的顺序错误。
    • 建议:将您的自定义过滤器链(暂时)替换为默认过滤器链,并确保其正常工作。
  • 您的自定义 UserDetailsS​​ervice 中存在错误
    • 建议:使用调试器来验证您传递的用户名)。
  • 您的登录表单(假设您使用基于表单的身份验证)未设置正确的用户名/密码字段
    • 建议:j_username 和 j_password 是标准字段名称(除非您自定义了它们)。如果您使用 JSF、GWT 或其他一些会破坏字段名称的 UI 技术,则需要考虑到这一点。
  • 您可能有其他错误配置
    • 建议:删除您的自定义 UserDetailsS​​ervice 并将其替换为标准的简单 in-memory service,以确保您的基本配置在添加自定义内容之前正常工作。

如果您可以发布您的完整配置(特别注意您自定义的任何内容),我/我们可以提供更准确的建议,但我建议您最有可能遇到这些问题。

【讨论】:

  • 谢谢 好像是字段名的问题。该字段的 id 是 j_username 但名称是其他名称所以我将其更改为 j_username 以便它现在可以从该字段中获取值。
【解决方案2】:

在这里,您尝试将您的 userDetailsS​​ervice 作为身份验证提供者注入身份验证管理器中,我猜这是不正确的。

应该是这样的:

<bean id="authenticationManager"   
class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
    <ref local="authenticationProvider" />
</list>
     </property>    
</bean>

<bean id="authenticationProvider" 
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider
">
<property name="userDetailsService" ref="userDetailsService" />     
</bean>

<beans:bean id="userDetailsService"     class="temp.com.JpaUserDetailsService" /> 

【讨论】:

  • 这是一个很好的猜测,但它不正确。他/她发布的 XML 命名空间配置与您所拥有的完全相同。要配置自定义AuthenticationProvider,他/她需要使用AuthenticationProvider 元素的ref 属性。
猜你喜欢
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 2013-05-12
  • 2017-10-27
  • 2015-10-19
  • 2013-02-11
  • 2011-05-02
相关资源
最近更新 更多