【问题标题】:Grails springSecurityService.getCurrentUser() is Null when using custom AuthenticationProvider使用自定义 AuthenticationProvider 时,Grails springSecurityService.getCurrentUser() 为 Null
【发布时间】:2012-05-21 23:45:41
【问题描述】:

我的应用程序中的一个控制器需要可供通过外部数据库进行身份验证的用户访问。

我已经设置了一个自定义用户对象,

class CustomUserDetails extends GrailsUser {

    final String externalId

    CustomUserDetails(String username, String password, boolean enabled,
        boolean accountNonExpired, boolean credentialsNonExpired,
        boolean accountNonLocked,
        Collection<GrantedAuthority> authorities,
        long id, String externalId) {

        super(username, password, enabled, accountNonExpired,
        credentialsNonExpired, accountNonLocked, authorities, id)

        this.externalId = externalId 
    }       
}

和一个自定义的 AuthenticationProvider

class CustomAuthenticationProvider implements AuthenticationProvider {
    def springSecurityService

    Authentication authenticate(Authentication customAuth) {

    /* Do stuff to validate the user's credentials here */

        def userDetails = new CustomUserDetails(customAuth.getPrincipal(), customAuth.getCredentials(), true, true, true, true, 
                [new GrantedAuthorityImpl('ROLE_SPECIAL_USER')], 9999999, "externalDatabaseIdString")

        def token = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities)

        return token
    }

    boolean supports(Class authentication) {
        return true
    }
}

我已在 Config.groovy 中创建条目以将其添加到 springsecurity.providerNames 列表中,并将以下内容添加到 conf/spring/resources.groovy

beans = {
customAuthenticationProvider(info.proadvisors.auth.CustomAuthenticationProvider){ bean ->   bean.autowire = "byName" }

userDetailsService(org.codehaus.groovy.grails.plugins.springsecurity.GormUserDetailsService){ bean -> bean.autowire = "byName" }
}

这是问题所在 - 在我的控制器中,springSecurityService 正在被注入,但 springSecurityService.getCurrentUser() 为空,并且当我尝试访问应该在经过身份验证的用户对象上的 externalId 属性时返回空指针异常。

如果在我的 CustomAuthenticationProvider 中,我使用 GormUserDetailsS​​ervice 给我一个 GrailsUser 对象并使用它来构建令牌,而不是创建 CustomUserDetails 的实例,则控制器可以正常工作并且 getCurrentUser() 可以正常工作。

关于为什么这不起作用的任何想法?

【问题讨论】:

    标签: grails spring-security


    【解决方案1】:

    springSecurityService.getPrincipal() 给了我想要的东西。

    不知道为什么 getCurrentUser() 不起作用而 getPrincpal() 起作用,但它就是这样。

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 2018-12-11
      相关资源
      最近更新 更多