Spring Security + custom User object attached to session for filtered requests
I am not sure how to solve the following problem/ realize my scenario. Maybe someone can give me some hints?
I have a Spring MVC app with Spring Security. I also use a custom Login page. All works fine so far, I can authenticate and display the logged in user on my JSP using the following code.
<sec:authorize ifAnyGranted="ROLE_USER">
Logged in as <sec:authentication property="principal.username" />
</sec:authorize>
The users a re retreieved from a database right now. Code for that in XML is
&l开发者_如何学Pythont;jdbc-user-service data-source-ref="dataSource" users-by-username-query="SELECT username, password , '1' AS enabled FROM users WHERE username = ?" authorities-by-username-query="SELECT username, 'ROLE_USER' FROM users WHERE username = ?" />
All works fine. Problem is, I actually have a custom User class that I would like to use and probably keep in my session as later DB requests should filter the results according to the logged in User.id.
How would I do this?
- What do I need to do to store my User object in my session? Is this the right way to do it?
- I use Hibernate. What is Best pratice to filter request, e.g. for objects called "Task" (in a task manager), according to the logged in user? (I have a column and property user_id in the tasks-table in my MySQL DB)
Any help or hint is much appreciated. Just need some direction :-)
If you are using Spring Security 3.x, you may want to check if Expression Based Access Control (@PostFilter
, for instance) meets your requirement.
For instance, if your Task
objects has the username
member, you could do something like this...
@PostFilter("filterObject.username == authentication.name")
public List<Task> getTasks() {
...
tasks = TaskDao.findAll();
return tasks;
}
This would return those tasks which belonged to the logged in user.
This SO discussion is also possibly relevant.
精彩评论