Spring Security是企业中使用广泛的认证授权框架,它也是spring家族中的一员,特别是它和spring boot结合开发非常的简单,能够极大的提高我们的生产力
1 创建一个mavean工程:SpringSecurity02
2 pom中在上一个案例的基础上增加spring Security的依赖:
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-webartifactId>
<version>5.0.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-configartifactId>
<version>5.0.1.RELEASEversion>
dependency>
3 创建spring的配置类ApplicationConfig.java
@Configuration
@ComponentScan(basePackages = "cn.xh"
,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})
public class ApplicationConfig {
//在此配置除了Controller的其它bean,比如:数据库链接池、事务管理器、业务bean等。
}
4 创建springmvc的配置类:
(basePackages = ,includeFilters = {(type = FilterType.,value = .)}) WebConfig WebMvcConfigurer { InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = InternalResourceViewResolver(); viewResolver.setPrefix(); viewResolver.setSuffix(); viewResolver; } }
5 加载spring容器:
在init包下定义spring容器的初始化类SpringApplicationInitializer,此类实现WebApplicationInitializer接口,spring容器启动时加载WebApplicationInitializer接口的所有实现类:
SpringApplicationInitializer AbstractAnnotationConfigDispatcherServletInitializer { Class>[] getRootConfigClasses() { Class>[] { ApplicationConfig.}; } Class>[] getServletConfigClasses() { Class>[] { WebConfig.}; }
String[] getServletMappings() { String [] {}; } }
6 认证,Spring Security默认提供认证页面
7 在config包下创建spring Security的配置类WebSecurityConfig,配置的内容包括:用户信息、密码编码器、安全拦截机制:
@EnableWebSecurity
WebSecurityConfig WebSecurityConfigurerAdapter { UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager = InMemoryUserDetailsManager(); manager.createUser(User.().password().authorities().build()); manager.createUser(User.().password().authorities().build()); manager; } PasswordEncoder passwordEncoder() { NoOpPasswordEncoder.(); } configure(HttpSecurity http) Exception { http.authorizeRequests().antMatchers().authenticated().anyRequest().permitAll().and().formLogin().successForwardUrl(); } }
userDetailsService方法返回一个UserDetailsService对象,spring security从这里获取用户的信息,这里创建了两个用户zhangsan和lisi并设置了他们的密码和权限。
Configure方法配置了/r/**的资源经过认证后才能访问,支持form表单认证,认证成功后跳转到login‐success
8 加载 WebSecurityConfig:
修改SpringApplicationInitializer的getRootConfigClasses()方法,添加WebSecurityConfig.class:
Class>[] getRootConfigClasses() { Class>[] { ApplicationConfig.,WebSecurityConfig.}; }
9 Spring Security初始化:
如果当前环境没有使用spring或spring mvc,则需要将WebSecurityConfig传入超类,以获取配置并创建spring context
public class SpringSecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SpringSecurityApplicationInitializer() {
//super(WebSecurityConfig.class);
}
}
10 默认根路径请求:
在WebConfig.java中添加默认请求根路径跳转到/login,此url为spring security提供:
addViewControllers(ViewControllerRegistry registry) { registry.addViewController().setViewName(); }
11 在LoginController中定义/login-success:
LoginController { (value = ,produces = {}) String loginSuccess(){ ; } }
12 授权:
在LoginController中添加”/r/r1”或”/r/r2”
在spring security配置类:WebSecurityConfig.java中配置授权规则:
.antMatchers("/r/r1").hasAuthority("p1")
.antMatchers().hasAuthority()
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/r/r1").hasAuthority("p1")
.antMatchers("/r/r2").hasAuthority("p2")
.antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过
.anyRequest().permitAll()//除了/r/**,其它的请求可以访问
.and()
.formLogin()//允许表单登录
.successForwardUrl("/login-success");//自定义登录成功的页面地址
}