Spring security plugin - how to access user id from hidden field

I am trying to set hiddenField in the "create" view, where the field is set to the id of the current user. What do you get from springSecurityService.principal.id property.

I was wondering if it is possible to do this exclusively from the template, and not pass the value from the controller. eg.

<%@ 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 a reference to the "main" property.

Is there a way to do this, or do I need to explicitly pass the identifier of the current user in the system from the "create" method?

NOTE. Yes, I know that for any person, you can create a POST request with a protected hidden field. There are checks in the controller code to ensure that the current user can only create, edit, delete their own messages. My question is more related to the fact that you do not need to enter the code to transfer the current user in three different forms.

+4
source share
3 answers

try using the following syntax

 <g:hiddenField name="user.id" value="${sec.loggedInUserInfo(field:"id")}"/> 
+13
source

Saving the current user ID as a hidden field in the view is a very bad idea, because anyone with basic knowledge of how the website works can replace that value with another user ID.

Instead, you should use springSecurityService on the server side to get the curren user. You can get a link to this service through dependency injection in the domain class, controller, service, taglib, etc.

 class MyController { def springSecurityService def myAction() { def currentUser = springSecurityService.currentUser } } 
+4
source

Take SecurityService through applicationContext:

$ {applicationContext.springSecurityService.currentUser.id}

 <g:hiddenField name="user.id" value="${applicationContext.springSecurityService.currentUser.id}"/> 
+4
source

Source: https://habr.com/ru/post/1395570/


All Articles