Spring Security的三個configure方法


參考自:java – HttpSecurity,WebSecurity和AuthenticationManagerBuilder

Spring Security通過繼承WebSecurityConfigurationAdapter這個類,可以選擇實現該類中的三個重載的configure方法,雖然可以下載代碼文檔,但是稍微有點……

看看這三個方法:

void configure(AuthenticationManagerBuilder auth) throws Exception

void configure(HttpSecurity http) throws Exception


void configure(WebSecurity web) throws Exception

再來看段重寫的代碼:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService; // 該類實現UserDetailsServer接口,重寫loadUserByUsername方法,從數據庫獲取用戶名,密碼,角色

    @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(charSequence.toString());
            }
        });
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login")
                .defaultSuccessUrl("/").permitAll()
                .and()
                .logout().permitAll();
        http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("/css/**", "/js/**");
    }
}

configure(AuthenticationManagerBuilder)用於通過允許AuthenticationProvider容易地添加來建立認證機制。

也就是說用來記錄賬號,密碼,角色信息。

下方代碼不從數據庫讀取,直接手動賦予

AuthenticationManagerBuilder allows 
    public void configure(AuthenticationManagerBuilder auth) {
        auth
            .inMemoryAuthentication()
            .withUser("user")
            .password("password")
            .roles("USER")
        .and()
            .withUser("admin")
            .password("password")
            .roles("ADMIN","USER");
}

configure(HttpSecurity)允許基於選擇匹配在資源級配置基於網絡的安全性。以下示例將以/ admin /開頭的網址限制為具有ADMIN角色的用戶,並聲明任何其他網址需要成功驗證。

也就是對角色的權限——所能訪問的路徑做出限制

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeUrls()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated()
}

configure(WebSecurity)用於影響全局安全性(配置資源,設置調試模式,通過實現自定義防火牆定義拒絕請求)的配置設置。

一般用於配置全局的某些通用事物,例如靜態資源等

public void configure(WebSecurity web) throws Exception {
    web
        .ignoring()
        .antMatchers("/resources/**");
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM