网上已有一些对于SpringSecurity的分析解读,写的很好,看过之后受益良多!
比如:
https://www.cnkirito.moe/categories/Spring-Security/
http://www.spring4all.com/article/428
有兴趣可以先研读下
这里的博客主要是参考他人文章,顺便记录下自己的理解,仅此
以前学习过Spring Security的XML配置形式,现在基本都使用Java Config形式了,这点的变化还是蛮大的
XML形式:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这里主要是注册一个过滤器DelegatingFilterProxy类,映射的name为springSecurityFilterChain,直观。
暂不分析
Java Config形式:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//...
}
可以看到,声明一个配置类,主要特点有:
1:@EnableWebSecurity注解
2:继承WebSecurityConfigurerAdapter类
3:重写config方法
4:HttpSecurity类的使用
由于被@Configuration修饰,不出意外,应该会在Spring启动的时候加载。看下@EnableWebSecurity注解的定义:
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
SpringWebMvcImportSelector.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
}
是一个多重注解,加载了WebSecurityConfiguration.class,SpringWebMvcImportSelector.class和@EnableGlobalAuthentication注解,继续跟进后者:
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import(AuthenticationConfiguration.class)
@Configuration
public @interface EnableGlobalAuthentication {
}
发现其又加载AuthenticationConfiguration.class
综上可知,主要是加载了三个类:
<1>SpringWebMvcImportSelector的作用是判断当前的环境是否包含springmvc,因为spring security可以在非spring环境下使用,为了避免DispatcherServlet的重复配置,所以使用了这个注解来区分。
<2> WebSecurityConfiguration顾名思义,是用来配置web安全的,下面的小节会详细介绍。
<3>AuthenticationConfiguration权限配置相关类
而重点就是后两者!
下面启动Spring,跟踪下源码,查看它如何加载的