0

我想使用彈簧安全,但我從來沒有在它之前使用過。我想從我的表(用戶,角色和user_roles)檢索用戶和角色。我有調查了大約用戶 - 用戶名 - 查詢。在所有示例中都與以下示例相同。春季安全用戶通過用戶名查詢與id_user

<authentication-manager> 
    <authentication-provider> 
    <jdbc-user-service data-source-ref="dataSource" 
     users-by-username-query= 
     "select username,password, enabled from users where username=?" 
     authorities-by-username-query= 
     "select username, role from user_roles where username =? " /> 
    </authentication-provider> 
</authentication-manager> 

但我想用id_userid_role,而不是用戶名作用。可能嗎 ?我必須更改登錄頁面字段名稱嗎? 在此先感謝

+0

這裏是一個關於它的很好的討論https://stackoverflow.com/questions/9069019/user-by-username-query-needing-more-than-1-parameter –

+1

爲什麼你不檢索您的領域'id_user'和'id_role',並在相同的查詢中只是一個別名?這可能是實現這一目標的最簡單方法。從來就做了好幾次:'用戶按用戶名查詢=「\t選擇user.user_login作爲用戶名,user.user_pwd作爲密碼,user.user_enabled從用戶啓用其中user.user_login =?」' – jlumietu

+0

確定,如果它可以像你說的那樣使用,我會嘗試一下。謝謝你的回覆。 –

回答

2

這是常見的情況。

首先,正如我在評論中所建議的,使用別名來重命名代表用戶名,密碼以及用戶是否啓用的字段。就像這樣:

users-by-username-query= 
    "select user.user_login as username, user.user_pwd as password, user.user_enabled as enabled 
    from user where user.user_login=?" 

然後,就是平時也有authorities在不同的表與表user主題相關。這是一個常見的情況:

enter image description here

當用戶與在n-to-n關係的角色有關。

在這種情況下,authorities-by-username-query應該是這樣的

authorities-by-username-query= 
     "SELECT users.name as username, roles.role as role 
     FROM users 
     INNER JOIN user_role ON users.id_user = user_role.id_user 
     INNER JOIN roles ON user_role.id_role = roles.id_role 
     WHERE users.name = ? " 

作爲測試,一組包含此數據表:

用戶:

users table content

角色:

roles table content

USER_ROLE

user-role table content

用於接收用戶名jlumietu的結果應該是這樣的:

authorities-by-username-query result

最後,我有一些情況下,我已經延長org.springframework.security.authentication.dao.DaoAuthenticationProvider但我認爲這是做這種處理的最簡單的方法