2016-02-03 106 views
0

我有這樣的情況。Spring Boot MongoDB連接bean

我使用Spring 1.3.2開機,我已經在我的電腦安裝 MongoDB的我已經加入依賴

org.springframework.boot:spring-boot-starter-data-mongodb 

當我運行我的Web應用程序,數據庫連接會自動開始工作。

我沒有配置一個東西。

現在我想連接的Spring Security這樣的:

@Override 
protected void configure(AuthenticationManagerBuilder auth) 
                                                   throws Exception { 
  auth 
    .jdbcAuthentication() 
      .dataSource(dataSource); 
} 

我的問題是春季啓動數據源是什麼默認的bean的名字,我可以重寫呢?

回答

2

如果你打算使用Mongodb爲您的用戶資料存儲,即用戶名密碼,等等,那麼你不能使用jdbcAuthentication()。相反,你可以爲了使用UserDetailsService達到相同的:

@Configuration 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @Autowired private MongoTemplate template; 

    @Override 
    @Autowired 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
       .userDetailsService((String username) -> { 
        User user = template.findOne(Query.query(Criteria.where("username").is(username)), User.class, "users"); 

        if (user == null) throw new UsernameNotFoundException("Invalid User"); 

        return new UserDetails(...); 
       }); 
    } 
} 

在prceeding樣品,我假設你有一個users集合與username場。如果對於給定的用戶名確實存在一個用戶,則應該返回對應於該用戶的UserDetails的實現。否則,你應該拋出一個UsernameNotFoundException

您還可以處理用戶身份驗證的其他選項,但jdbcAuthentication()是假表,因爲你使用的是NoSQL數據存儲用於存儲用戶的細節和JDBC是處理所有與talkings關係數據庫的抽象。