2014-10-09 64 views
0

我正在構建一個具有用戶登錄機制的Spring MVC Web應用程序。我使用了spring-boot來設置我的應用程序。爲了驗證與數據庫中的用戶,我也跟着下面的教程:實現自定義Spring安全驗證方法

http://justinrodenbostel.com/2014/05/30/part-5-integrating-spring-security-with-spring-boot-web/

在此,使用Spring的內置認證程序。通過指定

auth.jdbcAuthentication().dataSource(datasource); 

Spring安全檢查用戶和權限表並驗證用戶。

我想覆蓋這個默認行爲,因爲我沒有(不需要)認證表。此外,我的用戶表有比標準三列更多的列,即用戶名,密碼和啓用。

如何覆蓋默認實現?

此外,用戶登錄後,如何獲取有關用戶的信息?

謝謝!

+0

有很多這樣的例子,搜索UserDetailsS​​ervice。 – holmis83 2014-10-09 18:54:27

+0

看看這個頁面,它可以幫助你理解需要做什麼,因爲它有一個體面的例子http://igorristic.blogspot.com.au/2014/09/spring-mvc-and-security-basic-setup .html – Aeseir 2014-10-10 00:23:19

回答

1

您可以創建自定義AuthenticationProvider或使用DaoAuthenticationProvider與您的自定義UserDetailsService實施。

這裏是第二個解決方案的Spring Java配置類的一個示例:

@Configuration 
@EnableWebMvcSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private UserService userService; 

    // ... 

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

    @Bean 
    public AuthenticationProvider authenticationProvider() { 
     DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); 
     authenticationProvider.setPasswordEncoder(new ShaPasswordEncoder()); 
     authenticationProvider.setUserDetailsService(userService); 
     return authenticationProvider; 
    } 

} 

你實現UserDetailsService界面將包含具體到項目的網域,通過他們的用戶名檢索用戶的邏輯。

如果您需要更詳細的示例,請在下面留言,我會更新答案,但這應該會給您一個總體思路。

另外我建議閱讀上述Spring類和接口的JavaDocs。

+0

很好的答案;只有批評者認爲不推薦MD5和SHA作爲哈希函數,而是使用Blowfish哈希(bCryptPasswordEncoder),因爲它可以隨着計算能力變得更便宜(因此破解密碼變得更容易)而適應。詳情:https://codahale.com/how-to-safely-store-a-password/ – 2017-04-06 14:41:44