2015-10-13 86 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