4

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.

4

3 回答 3

13

try using following syntax

<g:hiddenField name="user.id" value="${sec.loggedInUserInfo(field:"id")}"/>
于 2012-02-10T18:59:08.253 回答
5

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.

class MyController {
  def springSecurityService

  def myAction() {
    def currentUser = springSecurityService.currentUser
  }
}
于 2012-02-09T10:03:09.370 回答
4

Grab the securityService via the applicationContext:

${applicationContext.springSecurityService.currentUser.id}

<g:hiddenField name="user.id" value="${applicationContext.springSecurityService.currentUser.id}"/>
于 2014-03-06T15:17:44.943 回答