我最近从JSecurity插件转到了Spring Security。如何从控制器中获取经过身份验证的用户?
发布于 2009-04-22 00:50:31
我使用的是0.5.1,下面的代码对我有效:
class EventController {
def authenticateService
def list = {
def user = authenticateService.principal()
def username = user?.getUsername()
.....
.....
}
}发布于 2009-04-22 06:13:10
它目前没有文档,但是在插件安装文件中,有3个方法可以添加到每个控制器中,这样你就不需要注入authenticationService了:
private void addControllerMethods(MetaClass mc) {
mc.getAuthUserDomain = {
def principal = SCH.context?.authentication?.principal
if (principal != null && principal != 'anonymousUser') {
return principal?.domainClass
}
return null
}
mc.getPrincipalInfo = {
return SCH.context?.authentication?.principal
}
mc.isUserLogon = {
def principal = SCH.context?.authentication?.principal
return principal != null && principal != 'anonymousUser'
}
}这意味着您可以直接调用
principalInfo来获取主体对象。它还有"isUserLogin“用于查看用户是否已登录,"authUserDomain”用于获取与已登录用户的主体相关联的实际域类实例( Person/ user )。
发布于 2011-06-08 03:28:55
下面的代码来自Spring Security Core Plugin (Version: 1.1.2) - Reference Documentation - Section 6.2
grails.plugins.springsecurity.SpringSecurityService提供了安全实用程序功能。它是一个常规的Grails服务,因此您可以使用依赖注入将其注入到控制器、服务、标记库等中:
class SomeController {
def springSecurityService
def someAction = {
def user = springSecurityService.currentUser
…
}
}https://stackoverflow.com/questions/775053
复制相似问题