gpt4 book ai didi

Grails MongoDB 脏检查在 Spring Security 中失败

转载 作者:行者123 更新时间:2023-12-02 14:39:31 24 4
gpt4 key购买 nike

我将 Grails 3.3.2 与 mongoDB 插件 (v6.1.4) 和 Spring Security Core 插件 (v3.2.0) 一起使用。

我有以下 UserPasswordEncoderListener使用以下 persistenceEvent 方法:

 @Override
protected void onPersistenceEvent(AbstractPersistenceEvent event) {
if (event.entityObject instanceof User) {
User u = (event.entityObject as User)
if (u.password && (event.eventType == EventType.PreInsert || (event.eventType == EventType.PreUpdate && u.hasChanged('password')))) {
event.getEntityAccess().setProperty("password", encodePassword(u.password))
}
}
}

问题是 hasChanged每次我保存具有 的用户对象时,调用总是返回 true没有更新 导致已经编码的密码被重新编码,从而破坏了身份验证。

一种解决方法是使用旧方法,只需从数据库中检索原始密码并在编码之前进行比较,但我想知道为什么 hasChanged错误地返回真。

我测试了 hasChanged通过在 groovy 控制台中运行以下命令在其他地方正常运行:
def user = User.findByEmail("user@email.com")
println "Result: "+ user.hasChanged('password')

结果是 Result: false .
为什么它在持久性监听器类中不起作用?

仅供引用:我在 resources.groovy 中定义了以下 bean:
userPasswordEncoderListener(UserPasswordEncoderListener,ref('mongoDatastore'))

最佳答案

您是否尝试过使用 isDirty()而不是 hasChanged()在你的听众中?

例如:

package com.mycompany.myapp

import grails.plugin.springsecurity.SpringSecurityService
import org.grails.datastore.mapping.engine.event.AbstractPersistenceEvent
import org.grails.datastore.mapping.engine.event.PreInsertEvent
import org.grails.datastore.mapping.engine.event.PreUpdateEvent
import org.springframework.beans.factory.annotation.Autowired
import grails.events.annotation.gorm.Listener
import groovy.transform.CompileStatic

@CompileStatic
class UserPasswordEncoderListener {

@Autowired
SpringSecurityService springSecurityService

@Listener(User)
void onPreInsertEvent(PreInsertEvent event) {
encodePasswordForEvent(event)
}

@Listener(User)
void onPreUpdateEvent(PreUpdateEvent event) {
encodePasswordForEvent(event)
}

private void encodePasswordForEvent(AbstractPersistenceEvent event) {
if (event.entityObject instanceof User) {
User u = event.entityObject as User
if (u.password && ((event instanceof PreInsertEvent) || (event instanceof PreUpdateEvent && u.isDirty('password')))) {
event.getEntityAccess().setProperty('password', encodePassword(u.password))
}
}
}

private String encodePassword(String password) {
springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
}
}

更多信息请访问: https://grails-plugins.github.io/grails-spring-security-core/3.2.x/index.html#tutorials

关于Grails MongoDB 脏检查在 Spring Security 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49692911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com