grails - grails spring安全登录不起作用,尝试了以前的方法,不起作用

标签 grails spring-security passwords grails-plugin

我正在使用grails 2.3.8。我知道有人问过这个问题,而且大多数都是由于双重编码。但是我仍然不知道我的问题在哪里。
我尝试了以下方法,但是没有用。
grails spring security login is not working

Grails + Spring Security: unable to login

当我尝试登录时,它显示:

“很抱歉,我们找不到使用该用户名和密码的用户。”

我的config.groovy >>>

import grails.plugin.springsecurity.SecurityConfigType
// locations to search for config files that get merged into the main config;
// config files can be ConfigSlurper scripts, Java properties files, or classes
// in the classpath in ConfigSlurper format

// grails.config.locations = [ "classpath:${appName}-config.properties",
//                             "classpath:${appName}-config.groovy",
//                             "file:${userHome}/.grails/${appName}-config.properties",
//                             "file:${userHome}/.grails/${appName}-config.groovy"]

// if (System.properties["${appName}.config.location"]) {
//    grails.config.locations << "file:" + System.properties["${appName}.config.location"]
// }

grails.project.groupId = appName // change this to alter the default package name and Maven publishing destination

// The ACCEPT header will not be used for content negotiation for user agents containing the following strings (defaults to the 4 major rendering engines)
grails.mime.disable.accept.header.userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']
grails.mime.types = [ // the first one is the default format
    all:           '*/*', // 'all' maps to '*' or the first available format in withFormat
    atom:          'application/atom+xml',
    css:           'text/css',
    csv:           'text/csv',
    form:          'application/x-www-form-urlencoded',
    html:          ['text/html','application/xhtml+xml'],
    js:            'text/javascript',
    json:          ['application/json', 'text/json'],
    multipartForm: 'multipart/form-data',
    rss:           'application/rss+xml',
    text:          'text/plain',
    hal:           ['application/hal+json','application/hal+xml'],
    xml:           ['text/xml', 'application/xml']
    ]

// URL Mapping Cache Max Size, defaults to 5000
//grails.urlmapping.cache.maxsize = 1000

// What URL patterns should be processed by the resources plugin
grails.resources.adhoc.patterns = ['/images/*', '/css/*', '/js/*', '/plugins/*']
grails.resources.adhoc.includes = ['/images/**', '/css/**', '/js/**', '/plugins/**']

// Legacy setting for codec used to encode data with ${}
grails.views.default.codec = "html"

// The default scope for controllers. May be prototype, session or singleton.
// If unspecified, controllers are prototype scoped.
grails.controllers.defaultScope = 'singleton'

// GSP settings
grails {
    views {
        gsp {
            encoding = 'UTF-8'
            htmlcodec = 'xml' // use xml escaping instead of HTML4 escaping
            codecs {
                expression = 'html' // escapes values inside ${}
                scriptlet = 'html' // escapes output from scriptlets in GSPs
                taglib = 'none' // escapes output from taglibs
                staticparts = 'none' // escapes output from static template parts
            }
        }
        // escapes all not-encoded output at final stage of outputting
        // filteringCodecForContentType.'text/html' = 'html'
    }
}


grails.converters.encoding = "UTF-8"
// scaffolding templates configuration
grails.scaffolding.templates.domainSuffix = 'Instance'

// Set to false to use the new Grails 1.2 JSONBuilder in the render method
grails.json.legacy.builder = false
// enabled native2ascii conversion of i18n properties files
grails.enable.native2ascii = true
// packages to include in Spring bean scanning
grails.spring.bean.packages = []
// whether to disable processing of multi part requests
grails.web.disable.multipart=false

// request parameters to mask when logging exceptions
grails.exceptionresolver.params.exclude = ['password']

// configure auto-caching of queries by default (if false you can cache individual queries with 'cache: true')
grails.hibernate.cache.queries = false

// configure passing transaction's read-only attribute to Hibernate session, queries and criterias
// set "singleSession = false" OSIV mode in hibernate configuration after enabling
grails.hibernate.pass.readonly = false
// configure passing read-only to OSIV session by default, requires "singleSession = false" OSIV mode
grails.hibernate.osiv.readonly = false

environments {
    development {
        grails.logging.jul.usebridge = true
    }
    production {
        grails.logging.jul.usebridge = false
        // TODO: grails.serverURL = "http://www.changeme.com"
    }
}

// log4j configuration
log4j = {
    // Example of changing the log pattern for the default console appender:
    //
    //appenders {
    //    console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
    //}

    error  'org.codehaus.groovy.grails.web.servlet',        // controllers
           'org.codehaus.groovy.grails.web.pages',          // GSP
           'org.codehaus.groovy.grails.web.sitemesh',       // layouts
           'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
           'org.codehaus.groovy.grails.web.mapping',        // URL mapping
           'org.codehaus.groovy.grails.commons',            // core / classloading
           'org.codehaus.groovy.grails.plugins',            // plugins
           'org.codehaus.groovy.grails.orm.hibernate',      // hibernate integration
           'org.springframework',
           'org.hibernate',
           'net.sf.ehcache.hibernate'
       }


// Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'org.grails.twitter.auth.Person'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'org.grails.twitter.auth.PersonAuthority'
grails.plugin.springsecurity.authority.className = 'org.grails.twitter.auth.Authority'

grails.plugin.springsecurity.userLookup.userDomainClassName = "com.grailsinaction.User"
grails.plugin.springsecurity.userLookup.usernamePropertyName = "loginId"            
grails.plugin.springsecurity.userLookup.passwordPropertyName = "passwordHash"       


grails.plugin.springsecurity.securityConfigType = "InterceptUrlMap"
grails.plugin.springsecurity.interceptUrlMap = [
'/':                  ['permitAll'],
'/index':             ['permitAll'],
'/index.gsp':         ['permitAll'],
'/assets/**':         ['permitAll'],
'/**/js/**':          ['permitAll'],
'/**/css/**':         ['permitAll'],
'/**/images/**':      ['permitAll'],
'/**/favicon.ico':    ['permitAll'],
'/login/**':          ['permitAll'],
'/logout/**':         ['permitAll'],
'/secure/**':         ['ROLE_ADMIN'],
'/finance/**':        ['ROLE_FINANCE', 'isFullyAuthenticated()'],
'/**': ['isAuthenticated()']
]

由于新的Spring Security插件,我没有登录 Controller

我的Bootstrap.groovy >>>
    import org.grails.twitter.auth.*

class BootStrap {

    def springSecurityService

    def init = { servletContext ->
        if (!Person.count()) {
            createData()
        }
    }

    def destroy = {
    }

    private void createData() {
        def userRole = new Authority(authority: 'ROLE_USER').save()

        String password = springSecurityService.encodePassword('password')

        [li: 'Ruifeng Li', todd: 'todd kurtz', maia: 'maia black', peter: 'Peter Lin'].each { userName, realName ->
            def user = new Person(username: userName, realName: realName, password: password, enabled: true).save()
            PersonAuthority.create user, userRole, true
        }
    }
}

我的Person.groovy >>>
package org.grails.twitter.auth

class Person {

    transient springSecurityService

    String realName
    String username
    String password
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired



    static transients = ['springSecurityService']

    static constraints = {
        username blank: false, unique: true
        password blank: false
    }

    static mapping = {
        password column: '`password`'
    }

    Set<Authority> getAuthorities() {
        PersonAuthority.findAllByPerson(this).collect { it.authority }
    }




}

我的Authority.groovy >>>
package org.grails.twitter.auth

class Authority {

    String authority

    static mapping = {
        cache true
    }

    static constraints = {
        authority blank: false, unique: true
    }
}

my.PersonAuthority.groovy >>
package org.grails.twitter.auth

import org.apache.commons.lang.builder.HashCodeBuilder

class PersonAuthority implements Serializable {

    private static final long serialVersionUID = 1

    Person person
    Authority authority

    boolean equals(other) {
        if (!(other instanceof PersonAuthority)) {
            return false
        }

        other.person?.id == person?.id &&
        other.authority?.id == authority?.id
    }

    int hashCode() {
        def builder = new HashCodeBuilder()
        if (person) builder.append(person.id)
        if (authority) builder.append(authority.id)
        builder.toHashCode()
    }

    static PersonAuthority get(long personId, long authorityId) {
        PersonAuthority.where {
            person == Person.load(personId) &&
            authority == Authority.load(authorityId)
        }.get()
    }

    static boolean exists(long personId, long authorityId) {
        PersonAuthority.where {
            person == Person.load(personId) &&
            authority == Authority.load(authorityId)
        }.count() > 0
    }

    static PersonAuthority create(Person person, Authority authority, boolean flush = false) {
        def instance = new PersonAuthority(person: person, authority: authority)
        instance.save(flush: flush, insert: true)
        instance
    }

    static boolean remove(Person u, Authority r, boolean flush = false) {
        if (u == null || r == null) return false

        int rowCount = PersonAuthority.where {
            person == Person.load(u.id) &&
            authority == Authority.load(r.id)
        }.deleteAll()

        if (flush) { PersonAuthority.withSession { it.flush() } }

        rowCount > 0
    }

    static void removeAll(Person u, boolean flush = false) {
        if (u == null) return

        PersonAuthority.where {
            person == Person.load(u.id)
        }.deleteAll()

        if (flush) { PersonAuthority.withSession { it.flush() } }
    }

    static void removeAll(Authority r, boolean flush = false) {
        if (r == null) return

        PersonAuthority.where {
            authority == Authority.load(r.id)
        }.deleteAll()

        if (flush) { PersonAuthority.withSession { it.flush() } }
    }

    static constraints = {
        authority validator: { Authority r, PersonAuthority ur ->
            if (ur.person == null) return
            boolean existing = false
            PersonAuthority.withNewSession {
                existing = PersonAuthority.exists(ur.person.id, r.id)
            }
            if (existing) {
                return 'userRole.exists'
            }
        }
    }

    static mapping = {
        id composite: ['authority', 'person']
        version false
    }
}

最佳答案

您是否尝试过启用日志记录进行调试?

配置槽

log4j = {
...
调试'org.springframework.security'
}

关于grails - grails spring安全登录不起作用,尝试了以前的方法,不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29645623/

相关文章:

hibernate - Grails Gorm静态锁定导致HibernateOptimisticLockingFailureException

spring - Grails是否默认使用Spring Dependency Injection

java - 错误 ="invalid_grant", error_description ="Bad credentials"在 Spring oauth2

带有 Windows 客户端的 ubuntu 机器上的 Git

php - 用户注册(以及稍后的身份验证)——我的方法还是使用 OpenID?

grails - hasErrors 的错误仅出现在第二次提交中

grails - Grails中的CommonsMultipartFile

java - 该页面没有正确重定向 Spring Security

grails - 我是否需要为grails中的facebook connect + spring security创建自定义身份验证提供程序?

Android Edittext可见字符但没有自动完成