簡體   English   中英

Spring Security:數據庫身份驗證

[英]Spring Security : Authentication with Database

我已經實現了從數據庫連接和檢索用戶的方法:

 @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。

我該怎么辦?

您可以使用CASE運算符調整查詢以將0映射到“ ROLE_USER”,將1映射到“ ROLE_ADMIN”

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM