HttpSecurity, WebSecurity and AuthenticationManagerBuilder

前端 未结 2 2076
有刺的猬
有刺的猬 2020-11-29 16:06

Could anyone explain when to override configure(HttpSecurity), configure(WebSecurity) and configure(AuthenticationManagerBuilder)?

2条回答
  •  不知归路
    2020-11-29 16:23

    General use of WebSecurity ignoring() method omits Spring Security and none of Spring Security’s features will be available. WebSecurity is based above HttpSecurity.

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/resources/**")
            .antMatchers("/publics/**");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/publics/**").hasRole("USER") // no effect
            .anyRequest().authenticated();
    }
    

    WebSecurity in the above example lets Spring ignore /resources/** and /publics/**. Therefore the .antMatchers("/publics/**").hasRole("USER") in HttpSecurity is unconsidered.

    This will omit the request pattern from the security filter chain entirely. Note that anything matching this path will then have no authentication or authorization services applied and will be freely accessible.

    configure(HttpSecurity) allows configuration of web-based security at a resource level, based on a selection match - e.g. The example below restricts the URLs that start with /admin/ to users that have ADMIN role, and declares that any other URLs need to be successfully authenticated.

    configure(WebSecurity) is used for configuration settings that impact global security (ignore resources, set debug mode, reject requests by implementing a custom firewall definition). For example, the following method would cause any request that starts with /resources/ to be ignored for authentication purposes.

    AuthenticationManagerBuilder
    extends AbstractConfiguredSecurityBuilder
    implements ProviderManagerBuilder
    

    SecurityBuilder used to create an AuthenticationManager. Allows for easily building in memory authentication, LDAP authentication, JDBC based authentication, adding UserDetailsService, and adding AuthenticationProvider's.

    @Override
         protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); 
            auth.userDetailsService(customUserDetailService).passwordEncoder(new BCryptPasswordEncoder());
         }
    

提交回复
热议问题