1、Spring Security是为基于Spring的应用程序提供声明式安全保护的安全性框架,它提供了完整的安全性解决方案,能够在web请求级别和方法调用级别处理身份证验证和授权。因为基于Spring框架,所以Spring Security充分利用了依赖注入和面向切面的技术。
2、web请求级别:使用Servlet规范中的过滤器(Filter)保护Web请求并限制URL级别的访问。 方法调用级别:使用Spring AOP保护方法调用,确保具有适当权限的用户才能访问安全保护的方法
3、新建一个Spring项目,pom里添加springsecurity的依赖。<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>————————————————
4、创建Spring Security的配置类package com.spring.security.springsecurity.con熠硒勘唏fig; import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration————————————————
5、@EnableWebSecurit鲻戟缒男y //启用Web安全功能public class SecurityConfig extends WebSecur足毂忍珩ityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() //访问"/"和"/home"路径的请求都允许 .antMatchers("/", "/home","/staff","/staff/*") .permitAll() //而其他的请求都需要认证 .anyRequest() .authenticated() .and() //修改Spring Security默认的登陆界面 .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); }————————————————
6、@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception{ //基于内存来存储用户信息 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("USER").and() .withUser("admin").password(new BCryptPasswordEncoder().encode("456")).roles("USER","ADMIN"); }}————————————————