我试图在“创建”视图中设置一个hiddenField,其中该字段设置为当前登录用户的id。您可以从“springSecurityService.principal.id”属性获得。
我想知道是否可以专门从模板执行此操作,而不是从控制器传递值。例如,
<%@ page import="grails.plugins.springsecurity.SpringSecurityService" %>
<% def springSecurityService %>
<html>
...
...
<g:hiddenField name="user.id" value="${springSecurityService.principal.id}"/>
...
我尝试了这段代码,但最终得到了引用“principal”属性的 NullPointer 异常。
有什么方法可以做到这一点,或者我是否必须从“create”方法显式传递当前登录用户的ID?
注意:是的,我知道对于任何人来说,使用经过修改的隐藏字段构建 POST 请求都是微不足道的。控制器代码中有一些检查,以确保当前登录的用户只能创建、编辑、删除自己的帖子。我的问题更多地与不必键入代码将当前登录的用户传递到三个不同的视图有关。
I'm trying to set a hiddenField in a "create" view, where the field is set to the id of the currently logged in user. Which you get from the "springSecurityService.principal.id" property.
I was wondering if it was possible to do this exclusively from the template instead of passing the value from a controller. e.g.
<%@ page import="grails.plugins.springsecurity.SpringSecurityService" %>
<% def springSecurityService %>
<html>
...
...
<g:hiddenField name="user.id" value="${springSecurityService.principal.id}"/>
...
I tried this code, but ended up getting a NullPointer exception with reference to the "principal" property.
Is there any way to do this or do I have to explicitly pass the id of the currently logged in user from the "create" method?
NOTE: Yes I know that it's trivial for anyone to construct a POST request with a doctored hidden field. There are checks in the controller code to ensure that the currently logged in user can only create, edit, delete their own posts. My question is more to do with not having to type out the code to pass the currently logged in user to three different views.
发布评论
评论(3)
尝试使用以下语法
try using following syntax
将当前登录用户的 ID 存储为视图中的隐藏字段是一个非常糟糕的主意,因为任何具有 Web 工作原理基本知识的人都可以用另一个用户的 ID 替换该值。
相反,您应该在服务器端使用 springSecurityService 来获取当前用户。您可以通过域类、控制器、服务、标签库等中的依赖项注入来获取对此服务的引用。
Storing the id of the currently logged-in user as a hidden field in the view is a really bad idea, because anyone with a basic knowledge of how the web works can replace this value with the ID of another user.
Instead you should use the
springSecurityService
on the server side to get the curren user. You can get a reference to this service via dependency-injection in a domain class, controller, service, taglib, etc.通过 applicationContext 获取 securityService:
${applicationContext.springSecurityService.currentUser.id}
Grab the securityService via the applicationContext:
${applicationContext.springSecurityService.currentUser.id}