一、简介
Spring Security是和Spring Boot齐名的项目,是一个安全框架,引用官网的描述:“Spring Security is a powerful and highly customizable authentication and access-control framework”。
基本上所有的安全框架都有两个主要目标:认证(Authentication)和授权(Authorization)
学习Spring Security需要记住以下两个类:
WebSecurityConfigurerAdapter:自定义Security策略
AuthenticationManagerBuilder:自定义认证策略
二、Spring Security的使用
第一步:导入Spring Security依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
第二步:参照官方文档,创建config目录并编写配置类WebSecurityConfig,该配置类继承了上边的WebSecurityConfigurerAdapter类,具体代码如下:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Bean
UserDetailsService customUserService(){
return new CustomUserServiceImpl();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService())
//启动MD5加密
.passwordEncoder(new PasswordEncoder() {
MD5Util md5Util = new MD5Util();
@Override
public String encode(CharSequence rawPassword) {
return md5Util.encode((String) rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(md5Util.encode((String)rawPassword));
}
});
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/index","/aboutme","/archives","/categories","/friendlylink","/tags","/update")
.permitAll()
.antMatchers("/editor","/user").hasAnyRole("USER")
.antMatchers("/ali","/mylove").hasAnyRole("ADMIN")
.antMatchers("/superadmin","/myheart","/today","/yesterday").hasAnyRole("SUPERADMIN")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/")
.and()
.headers().frameOptions().sameOrigin()
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/");
http.csrf().disable();//关闭csrf功能
http.rememberme();//开启记住我功能,cookie
}
}