由于我一直在 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
,和passwordExpired
至false
因为这些是默认值。
关于来自服务的 Grails Spring Security 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20685982/