需求:某些请求需要进行认证,某些请求需要具备特定权限的用户才能访问……
-
对每个请求进行细粒度的安全性控制的关键是重载configure(HttpSecurity http)方法
(1) 示例 SecurityConfig.java
@Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { ... @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .regexMatchers("/.*").authenticated() .antMatchers("/spitter/me").authenticated() .antMatchers(HttpMethod.POST, "/spittles").authenticated() .anyRequest().permitAll(); } }
(2) 调用 authorizeRequests()方法,接下来进行细节上的配置
(3) 细节配置包括两个部分:路径匹配 和 保护路径的方法
(4) 其中,路径匹配包括3种:regexMatchers()方法使用正则匹配; antMatchers()方法使用Ant风格的通配符;anyRequests()代表任何请求
regexMatchers()和antMatchers()的参数数量都是可以1至多个,代表可以匹配多种路径;并且各自具有包括了HttpMethod的重载函数,可以设置POST/GET时进行匹配
(5) 保护路径的方法包括13种 P268
示例中的authenticated()方法代表认证过的用户才能访问,访问必须要登录(即数据库或内存中包含了这个用户,详见"选择查询用户详细信息的服务.md");
permitAll()代表无条件允许访问;
还有hasRole()方法代表如果用户具备某种给定角色的话,就允许访问;
...
(6) 这些规则会按照给定的顺序发挥作用,所以anyRequest()要放在最后面(类似于catch、switch语句)
-
使用Spring EL表达式进行安全保护
(1) 保护路径的13种方法(P268)只能是一维的,即无法让antMatchers("xxx")匹配的某个请求路径既满足 hasRole("xxx")又满足anthenticated()
(2) 这个问题的解决办法是:使用13种方法中的access(String)方法 + Spring EL
(3) 示例 SecurityConfig.java
@Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { ... @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/spitter/me").access("hasRole('ROLE_SPITTER') and hasIpAddress('192.168.1.2)") .anyRequest().permitAll(); } } access()方法需要的是String参数,可以填充SpringEL表达式
(4) 和SpringSecurity相关的SpringEL有11个,它们可以叠加使用在access()方法中 P270
-
强制通道的安全性
(1) 需求:有的网页需要强制使用https方法,有的则不需要
(2) 示例 SecurityConfig.java
@Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { ... @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .regexMatchers("/.*").authenticated() .antMatchers("/spitter/me").authenticated() .antMatchers(HttpMethod.POST, "/spittles").authenticated() .anyRequest().permitAll() .and(). .requiresChannel() .antMatchers("spitter/form").requiresSecure() .anyRequest().requiresInsecure(); } }
(3) 说明
使用 and()方法对不同的配置进行连接;
添加 requiresChannel()进行通道的配置;
配置方法和authorizeRequests类似:requiresSecure()代表匹配的路径强制使用https,requiresInsecure()代表匹配的路径强制使用http;
这些规则会按照给定的顺序发挥作用,所以anyRequest()要放在最后面
-
防止跨站请求伪造 P272
没看懂...
chapter09_保护Web应用_3_拦截请求
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 前言 本章内容: ▪️Spring Security介绍 ▪️使用Servlet规范中的Filter保护Web应用...
- 一直以来,Spring系列给人的感觉都是快速,简洁,好理解,易操作.但Security是一个特例,这个框架相比而言...
- Spring Security 是一个基于 Spring AOP 和 Servlet 过滤器的安全框架,它提供了安...
- 安全性是绝大多数应用的一个重要切面。Spring Security是一个安全框架,它基于Spring AOP和Se...
- 案例环境 JDK 1.8 Tomcat 8 spring 4.0.0.RELEASE spring-securit...