HttpSecurity, WebSecurity and AuthenticationManagerBuilder

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

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

2条回答
  •  抹茶落季
    2020-11-29 16:26

    configure(AuthenticationManagerBuilder) is used to establish an authentication mechanism by allowing AuthenticationProviders to be added easily: e.g. The following defines the in-memory authentication with the in-built 'user' and 'admin' logins.

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

    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.

    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().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.

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

    You can refer to the following link for more information Spring Security Java Config Preview: Web Security

提交回复
热议问题