2015-10-13 95 views
0

驗證我已經實現這種方式我的用戶從我的數據庫連接和檢索:春季安全:使用數據庫

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
DataSource dataSource; 

@Autowired 
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { 

    auth.jdbcAuthentication().dataSource(dataSource) 
    .usersByUsernameQuery(
     "select username,password, enabled from users where username=?") 
    .authoritiesByUsernameQuery(
     "select username, role from user_roles where username=?"); 
} 

所以,我有我的用戶與他們的角色。 在此示例代碼中,user_roles列將爲「ROLE_USER」或「ROLE_ADMIN」。 我想改變這個字段的布爾值,其中ROLE_ADMIN爲0,ROLE_USER爲1。

由於約束條件,我無法保留我的user_roles。

我該怎麼做?

+0

映射0到「ROLE_USER」和1「ROLE_ADMIN」請不要忘記當初的管理也是一個用戶。 –

+0

是否有一個Authorities標籤可以同時獲得ROLE_ADMIN和ROLE_USER授權? –

+0

您可以檢查PreAuthorize或Secured註釋中的AND條件。 –

回答

0

您可以適應您的查詢與CASE operator

.authoritiesByUsernameQuery(
"select username, case when role=1 then 'ROLE_USER' else 'ROLE_ADMIN' as role from user_roles where username=?") 
+0

不工作:/但這是一個很好的方式來搜索我猜。 您是否知道我如何在線測試這些請求? 仍然不知道爲什麼我在做「WHERE login =?」 –

+0

什麼意思是「不起作用」? (在你的代碼中沒有* login =?*)我沒有看到*在線測試數據庫查詢* – ben75