来自服务的 Grails Spring Security 身份验证

标签 grails spring-security grails-orm

由于我一直在 Grails 应用程序中使用专用服务以便使用 vaadin UI 进行身份验证,因此我在验证登录时遇到问题:

1)在bootstrap中创建一个新用户并记录到db(postgre)

User.withTransaction {
   User test = new User(
      username: "test",
      password: springSecurityService.encodePassword("password"),
      enabled: true,
      accountExpired: false,
      accountLocked: false,
      passwordExpired: false
   ).save()

Role dashManager = new Role(authority: "ROLE_USER").save()

new UserRole(user: test, role: dashManager).save()

2) vaadin ui 正常调用 grails 服务

boolean login(String username, String password) {
   try {
      println username + "----" + password
      security.signIn(username, password)
      return true
   } catch (SecurityServiceException e) {
      Notification.show("Login/Password incorrect", Notification.TYPE_ERROR_MESSAGE);
      return false
   }
}

3)我的 securityService 总是返回无效

import grails.transaction.Transactional
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken

@Transactional
class SecurityService {

    def springSecurityService
    def authenticationManager

    void signIn(String username, String password) {
        try {
            def authentication = new UsernamePasswordAuthenticationToken(username, password)
            SCH.context.authentication = authenticationManager.authenticate(authentication)
        } catch (BadCredentialsException e) {
            throw new SecurityException("Invalid username/password")
        }
    }

    void signOut() {
        SCH.context.authentication = null
    }

    boolean isSignedIn() {
        return springSecurityService.isLoggedIn()
    }
}

最佳答案

您可能对密码进行了双重编码。该插件的最新版本会生成一个用户/个人域类,为您编码密码,因此您无需调用 springSecurityService.encodePassword("password") ,如果你这样做,那么它会被编码两次。这应该有效:

User test = new User(
   username: "test",
   password: "password",
   enabled: true
).save()

我省略了设置accountExpired , accountLocked ,和passwordExpiredfalse因为这些是默认值。

关于来自服务的 Grails Spring Security 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20685982/

相关文章:

spring - 在Spring Security中基于某种所有权设置用户角色

grails - Grails 集成测试名副其实吗?

java - 如何从 spring-security 源代码构建示例

java - Spring Security 与 Project Reactor 集成

Grails addTo* 说明

hibernate - Grails:过滤 gorm 查询

database - 有没有办法在 DataSource 配置中将时区设置为 UTC

grails - 为GSP中显示的数据生成文本(.txt)文件

grails - 如何检查params中是否存在参数?

html - GSP 克 :select option default selection