spring security简单使用
初识spring security
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理.它的两个主要目标就是实现认证和授权
入门案例简介
判断用户是否登录,如果未登录则只能访问登录页面;如果已登录则根据他是否有权限访问请求的资源。
项目结构
测试
- 创建springboot工程,添加web,thymleaf,spring security模块,工程创建后的依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<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>
- 编写controller
@Controller
public class TestController {
//首页
@RequestMapping({"/","/index","index.html"})
public String index(){
return "index";
}
//登录
@RequestMapping("/toLogin")
public String toLogin(){
return "views/login" ;
}
//请求资源
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
编写Spring Security配置类
编写security配置类,可以在配置类定义认证,授权,登录页面等。
package com.xsw.springbootsecurityquickstart.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
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//定制授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页全部可以访问,访问其他功能也需要对应的权限
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("user")
.antMatchers("/level2/**").hasRole("vip")
.antMatchers("/level3/**").hasRole("admin")
.and()
.formLogin();
}
//定制认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//可以从内存中,也可以从数据库中
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
//分别给张三,李四,王五分配user,vip,admin的权限
.withUser("张三").password(new BCryptPasswordEncoder().encode("12345")).roles("user")
.and()
.withUser("李四").password(new BCryptPasswordEncoder().encode("12345")).roles("vip")
.and()
.withUser("王五").password(new BCryptPasswordEncoder().encode("12345")).roles("admin") ;
}
}
测试
测试:分别登录不同的角色,每个角色只能访问自己认证下的规则!