问题
I am very new to Spring security and my problem is as follows:
I have a member mysql table that contains information about the website's members, including their usernames, passwords and roles. So far so good: I can use this table to configure a <jdbc-user-service.
However I also want to have a super user that is not going to be in the member table.
- Is it possible and recommended to have this super-user in an in-memory user repository and therefore mix jdbc user service with in-memory user service? If so how?
- If 1. is not possible perhaps I can have a second mysql table called for instance moderator. Then what sort of sql query would I need to authenticate against these two tables?
回答1:
Collissions
The problem with multiple repositories is that you need to ensure that you differentiate which user is which. For example assume your data looks like the following
member table
username
----------------------
member
moderator table
username
----------------------
moderator
Then you have some data associated to your users
data table
username value
----------------------------------------
moderator secret
What now happens if you get a collision? For example, a user signs up and your member table now looks like this:
member table
username
----------------------
member
moderator
Which moderator owns the data? There is no way to distinguish between the two users.
Alternative Approach
The alternative approach would be to use a mapping of users to roles. It would be to use something like this:
member table
username is_moderator
----------------------
member false
moderator true
Then when a user tries to sign up for with an existing username, there is a constraint violation so you do not need to differentiate between the two. Of course you could map the roles using another table. This is what Spring Security does normally using the authorities table.
Using multiple UserDetailsService
If you really want to use multiple user repositories anyways, you can simply declare multiple UserDetailsService entries in your configuration. An in memory configuration example is shown below:
<authentication-manager>
<authentication-provider>
<jdbc-user-service .. />
</authentication-provider>
<authentication-provider>
<user-service>
<user username="moderator"
password="password"
authorities="ROLE_MODERATOR"/>
</user-service>
</authentication-provider>
</authentication-manager>
If you want to do both in the database, you need to determine what your SQL queries for each table are and then add two elements. For example:
<authentication-manager>
<authentication-provider>
<jdbc-user-service .. />
</authentication-provider>
<authentication-provider>
<jdbc-user-service .. />
</authentication-provider>
</authentication-manager>
Use the attributes to control your sql queries. You can refer to the Spring Security appendix for example queries.
来源:https://stackoverflow.com/questions/12240544/authenticating-users-with-spring-security-against-two-user-services