SpringSecrity的简单使用
SpringSecrity
什么是secrity
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架
核心:
- 认证
- 授权
入门secrity
1.pom
thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- ...security ... -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- thymeleaf+security -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
-
java
package com.example.controller.config; 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; @EnableWebSecurity//2启用EnableWebSecurity public class myConfig extends WebSecurityConfigurerAdapter {//1继承WebSecurityConfigurerAdapter //拦截 @Override//3重载里面的方法 configure(HttpSecurity http) protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/").permitAll()//authorizeRequests授权,antMatchers那个页面 permitAll所有 .antMatchers("/level1/**").hasRole("vip1")//设置在level1下所有的文件需要有vip1的权限才能访问 .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); //没有权限访问时跳到登录页面 http.formLogin().loginPage("tologin");//当用户没有权限,而要进入需要登录http.formLogin() secrity默认的登录页面//自定义的登录loginPage("tologin") http.logout().logoutSuccessUrl("/index");//用户退出logout()//当用户退出成功时跳到index页面logoutSuccessUrl //http.csrf().disable();//关闭csrf跨站请求伪造 http.rememberMe();//记住我功能 } //授权 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//密码的加密、、加密方式为.passwordEncoder(new BCryptPasswordEncoder()——》BCryptPasswordEncoder //没有链接数据库所以使用假数据正常是从数据库查出来的 .withUser("root").password(new BCryptPasswordEncoder().encode("23423423")).roles("vip1")//withUser用户——password密码 //给这个用户为root密码为23423423授予vip1的权限 .and() .withUser("11").password(new BCryptPasswordEncoder().encode("23423423")).roles("vip1","vip2"); } }
secrity基于springboot开发的,在项目中使用springboot来配置secrity更加方便