如何使用spring-security通过用户名和密码登录?

问题描述 投票:0回答:1

Grails 3.我无法使用spring-security成功登录。我已经通过def init = {servletContext->创建了用户名和密码。下面的代码示例。

错误类型:http://localhost:8080/login/auth?login_error=1

依赖关系:编译'org.grails.plugins:spring-security-core:3.1.2'

HTML代码

<body>
    <div class="login-form">

        <form action='${postUrl}' method='POST' id='loginForm'>
            <h2 class="text-center">Log in</h2>
            <div class="form-group">
                <input type="text" class="form-control" name='j_username' id="j_username" placeholder="Username" required="required">
            </div>
            <div class="form-group">
                <input type="password" class="form-control" name='j_password' id='j_password' placeholder="Password" required="required">
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary btn-block">Log in</button>
            </div>
            <div class="clearfix">
                <label class="pull-left checkbox-inline"><input type="checkbox"> Remember me</label>
                <a href="#" class="pull-right">Forgot Password?</a>
            </div>
        </form>
        <p class="text-center"><a href="${createLink(controller: 'login', action: 'newRegister')}">Create an Account</a></p>
    </div>
    </body>
</html>

登录控制器和方法

  @Secured('permitAll')
    class LoginController {
        AuthenticationTrustResolver authenticationTrustResolver
        def springSecurityService

        def index() {
            if (springSecurityService.isLoggedIn()) {
                redirect uri: conf.successHandler.defaultTargetUrl
            }
            else {
                redirect action: 'auth', params: params
            }

        }

def auth () {

    def conf = getConf()

    if (springSecurityService.isLoggedIn()) {
        redirect uri: conf.successHandler.defaultTargetUrl
        return
    }

    String postUrl = request.contextPath + conf.apf.filterProcessesUrl
    render view: 'auth', model: [postUrl: postUrl,
                                 rememberMeParameter: conf.rememberMe.parameter,
                                 usernameParameter: conf.apf.usernameParameter,
                                 passwordParameter: conf.apf.passwordParameter]
}

def loginSuccess(){

    redirect(controller: 'registerUser', action: 'index')
    return

}

def authAjax() {
    response.setHeader 'Location', conf.auth.ajaxLoginFormUrl
    render(status: HttpServletResponse.SC_UNAUTHORIZED, text: 'Unauthorized')
}

def ajaxSuccess() {
    render([success: true, username: authentication.name] as JSON)
}

def ajaxDenied() {
    render([error: 'access denied'] as JSON)
}
protected ConfigObject getConf() {
    SpringSecurityUtils.securityConfig
}

protected org.springframework.security.core.Authentication getAuthentication() {
    SecurityContextHolder.context?.authentication
}

BootStrap.groovy中

def init = { servletContext ->
        def authorities = ['ROLE_ADMIN']
        authorities.each {
            if ( !Role.findByAuthority(it) ) {
                new Role(authority: it).save()
            }
        }
        if ( !User.findByUsername('[email protected]') ) {
            def u = new User(username: '[email protected]', password: 'admin')

            u.save()
            def ur = new UserRole(user: u, role:  Role.findByAuthority('ROLE_ADMIN'))
            ur.save()
        }
    }

Application.Groovy

grails.plugin.springsecurity.logout.postOnly = false
grails.plugin.springsecurity.successHandler.defaultTargetUrl = '/login/loginSuccess'

域类

@GrailsCompileStatic
@EqualsAndHashCode(includes='username')
@ToString(includes='username', includeNames=true, includePackage=false)
class User implements Serializable {

    private static final long serialVersionUID = 1

    SpringSecurityService springSecurityService

    String username
    String password
    String firstName
    String lastName
    String address
    String phoneNo
    String dateOfBirth
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    Set<Role> getAuthorities() {
        (UserRole.findAllByUser(this) as List<UserRole>)*.role as Set<Role>
    }

    def beforeInsert() {
        encodePassword()
    }

    def beforeUpdate() {
        if (isDirty('password')) {
            encodePassword()
        }
    }

    protected void encodePassword() {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
    }

    static transients = ['springSecurityService']

    static constraints = {
         username blank: false, unique: true
         password blank: false, password: true
         firstName nullable: true
         lastName nullable: true
         address nullable: true
         phoneNo nullable: true
         dateOfBirth nullable: true
         password nullable: false
    }

    static mapping = {
        password column: '`password`'
    }
}
grails spring-security
1个回答
0
投票

最后我找到了解决方案

用户名和密码应该是:

name='username'
password='password'

代替

name='j_username'
password='j_password'
© www.soinside.com 2019 - 2024. All rights reserved.