zoukankan      html  css  js  c++  java
  • Spring Security(十六):5.7 Multiple HttpSecurity

    We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. The key is to extend the WebSecurityConfigurerAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.

    我们可以配置多个HttpSecurity实例,就像我们可以有多个<http>块一样。关键是多次扩展WebSecurityConfigurerAdapter。例如,以下是具有以/ api /开头的URL的不同配置的示例。
     
    @EnableWebSecurity
    public class MultiHttpSecurityConfig {
    	@Bean
    	public UserDetailsService userDetailsService() throws Exception {
    		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    		manager.createUser(User.withUsername("user").password("password").roles("USER").build());
    		manager.createUser(User.withUsername("admin").password("password").roles("USER","ADMIN").build());
    		return manager;
    	}
    
    	@Configuration
    	@Order(1)                                                        1
    	public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
    		protected void configure(HttpSecurity http) throws Exception {
    			http
    				.antMatcher("/api/**")                               2
    				.authorizeRequests()
    					.anyRequest().hasRole("ADMIN")
    					.and()
    				.httpBasic();
    		}
    	}
    
    	@Configuration                                                   3
    	public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
    		@Override
    		protected void configure(HttpSecurity http) throws Exception {
    			http
    				.authorizeRequests()
    					.anyRequest().authenticated()
    					.and()
    				.formLogin();
    		}
    	}
    }

    Configure Authentication as normal

    正常配置身份验证

    1、Create an instance of WebSecurityConfigurerAdapter that contains @Order to specify which WebSecurityConfigurerAdapter should be considered first.

    创建包含@Order的WebSecurityConfigurerAdapter实例,以指定应首先考虑哪个WebSecurityConfigurerAdapter。

    2、The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/

    http.antMatcher声明此HttpSecurity仅适用于以/ api /开头的URL

    3、Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This configuration is considered after

    ApiWebSecurityConfigurationAdapter since it has an @Order value after 1 (no @Order defaults to last).

    创建WebSecurityConfigurerAdapter的另一个实例。如果URL不以/ api /开头,则将使用此配置。此配置在ApiWebSecurityConfigurationAdapter之后考虑,因为它在1之后具有@Order值(没有@Order默认为last)。
  • 相关阅读:
    Hibernate学习笔记(一)
    mysql内联接、左联接、右联接
    mysql表数据增删改查、子查询
    mysql建表时候的五种约束
    mysql数据库基本数据类型
    nginx uwsgi flask相关配置
    关于爬虫数据的解析器设计
    Redis 七月小说网的爬虫缓存设计
    MariaDB 数据库迁移
    React Relay 实现
  • 原文地址:https://www.cnblogs.com/shuaiandjun/p/10134326.html
Copyright © 2011-2022 走看看