Grails + Spring Security:无法登录

Posted

技术标签:

【中文标题】Grails + Spring Security:无法登录【英文标题】:Grails + Spring Security: unable to login 【发布时间】:2013-12-22 11:45:31 【问题描述】:

我刚开始学习Grails和Spring,我按照官方教程创建了一个登录系统。但我无法登录,“用户名或密码不匹配”。 我知道在 90% 的情况下这是由于双重编码或多个数据源(这也会导致双重编码),但我也没有这样做。

class BootStrap 

    def init =  servletContext ->

        def adminRole = new SecurityRole(authority: 'ROLE_ADMIN').save(failOnError: true, flush: true)
        def userRole = new SecurityRole(authority: 'ROLE_USER').save(failOnError: true, flush: true)

        def testUser = new User(username: 'admin', password: 'admin')
        testUser.save(failOnError: true, flush: true)

        SecurityUserSecurityRole.create testUser, adminRole, true

        assert User.count() == 1
        assert SecurityRole.count() == 2
        assert SecurityUserSecurityRole.count() == 1

        println testUser.username
        println testUser.password
     

spring-security-core:2.0-RC2 圣杯 2.3.3

【问题讨论】:

你看过这个问题吗? ***.com/questions/20075759/… @BenoitWickramarachi,是的,这就是我提供 Bootstrap.groovy 以表明我没有进行任何显式编码的原因。 好的,您的数据源是否配置为 dbCreate = "create-drop"? (因为否则您每次启动应用程序时都会复制角色和用户)。或者将您的代码更改为: def adminRole = SecRole.findByAuthority('ROLE_ADMIN') ?: new SecRole(authority: 'ROLE_ADMIN').save(failOnError: true) etc.. 以避免重复条目。 @BenoitWickramarachi,是的,我更改为您提供的内容,并通过 mysql Workbench 检查了数据库,没有重复 我不认为这个问题的解决方案,但我的问题就像其他人所说的那样,双重编码。我在Bootstrap.groovyUser 控制器中编码密码 - 谢谢! 【参考方案1】:

我在几个项目中遇到过类似的问题,这对我来说一直是双重编码问题。我使用的是 Spring Security Plugin 的早期版本,但这种技术可以确保它不会双重编码。同样,我使用不同的版本,但可能值得一试。

class User 
    // regular generated code should still be included
    boolean beforeInsertRunOnce = false
    boolean beforeUpdateRunOnce = false

    def beforeInsert() 
        if (! beforeInsertRunOnce) 
            beforeInsertRunOnce = true
            encodePassword()
        
    

    def afterInsert() 
        beforeInsertRunOnce = false
    

    def beforeUpdate() 
        if (isDirty('password') && ! beforeUpdateRunOnce ) 
            beforeUpdateRunOnce = true
            encodePassword()
        
     

    def afterUpdate() 
        beforeUpdateRunOnce = false
    

    protected void encodePassword() 
        password = springSecurityService.encodePassword(password)
    

【讨论】:

我的错误出现在我很久以前创建的服务中,我猜它有一个方法 login() 与 Spring Security Core 功能重叠。但我会接受这个答案,因为我认为 90% 的时间都是这个问题。 很好地找到了 Cormac,感谢您跟进实际情况。

以上是关于Grails + Spring Security:无法登录的主要内容,如果未能解决你的问题,请参考以下文章

grails-spring-security-rest 插件和悲观锁定

Grails + spring-security-core:用户登录后如何分配角色?

Grails Spring Security注释问题

Grails spring-security-oauth-google:如何设置

Grails Spring Security 插件网址

Grails/Spring Security:无法使用新创建的用户登录