簡體   English   中英

實現自定義Spring Security身份驗證方法

[英]Implement Custom Spring Security Authentication Method

我正在構建一個帶有用戶登錄機制的Spring MVC Web應用程序。 我已經使用spring-boot來設置我的應用程序。 要使用數據庫對用戶進行身份驗證,我遵循以下教程:

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

在這里,使用spring的內置身份驗證過程。 通過指定

auth.jdbcAuthentication().dataSource(datasource);

Spring安全性檢查用戶和授權表並驗證用戶身份。

我想覆蓋此默認行為,因為我沒有(不需要)身份驗證表。 另外,我的用戶表中的列比標准的三列(用戶名,密碼和已啟用)多得多。

如何覆蓋默認實現?

另外,在用戶登錄后,如何獲取有關該用戶的信息?

謝謝!

您可以創建自定義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。

暫無
暫無

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

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