使用Grails Spring Security自动登录

Dón*_*nal 14 grails spring-security

我的Grails应用程序正在使用Spring Security插件.我需要以编程方式登录用户,而且我无法访问他们的密码.我尝试了以下,当使用Acegi插件(Spring Security插件的祖先)时,它应该有效:

// automatically login a user and assign them the USER role. 
// In my app, the email address is also the username
GrantedAuthority[] auths = [new GrantedAuthorityImpl('USER')]
SecurityContextHolder.context.authentication 
        = new UsernamePasswordAuthenticationToken(email, 'unknown', auths)
Run Code Online (Sandbox Code Playgroud)

看起来这几乎有效,因为如果我springSecurityService.principal在执行上述操作后调用,我会收回自动登录用户的电子邮件地址.但是,如果我打电话,springSecurityService.currentUser我会收到错误.此错误的根本原因是:

SpringSecurityUtils.securityConfig.userLookup.userDomainClassName
Run Code Online (Sandbox Code Playgroud)

返回"Person",它不是我的用户类的名称.各种标签<sec:loggedInUser>也不起作用,大概是出于同样的原因.

我想知道这个问题是否与我使用预先存在的用户和角色域类(而不是插件生成的类)的事实有关?如果用户通过在表单中​​输入用户名和密码(而不是以编程方式)登录,则一切似乎都能正常工作.

更新

按照Burt的建议,我将上面的代码替换为:

springSecurityService.reauthenticate(email)
Run Code Online (Sandbox Code Playgroud)

但我仍然在这些线路上出现错误 SpringSecurityService.getCurrentUser()

String className = SpringSecurityUtils.securityConfig.userLookup.userDomainClassName
grailsApplication.getClassForName(className).get(principal.id)
Run Code Online (Sandbox Code Playgroud)

因为className设置为"Person",而不是我的User类的名称.

Bur*_*ith 18

如果用户在数据库中使用exists springSecurityService.reauthenticate()-看到这个链接或Grails的2 此链接 Grails的3.

此方法旨在在用户更改使其与数据库不同步时更新身份验证,但对于您希望强制对现有用户进行有效身份验证但不知道密码的情况也很有用.

  • 对于唐的情况,这是一个比我更好的答案。:) (2认同)
  • 他们再次搬家:http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html#springSecurityService (2认同)