SpringSecurity
简介
spring Security 是针对spring项目的安全框架,也是springBoot底层安全模块默认的技术选型,他可以实现强大的web安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理
记住几个类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder: 自定义认证策略
- @EnableWebSecurity: 开启WebSecurity模式
导入security
<!--导入security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
controller层
package com.google.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@CrossOrigin(origins = "http://localhost:8081",maxAge = 3600)//解决跨域问题
@Controller
public class SecurityController {
@RequestMapping("/")
public String usertext() {
String username = "罗";
return "redirect:http://localhost:8081/";
}
@RequestMapping("/{level}/{id}")
@ResponseBody
public String level(@PathVariable String level , @PathVariable int id) {
String username = level+"/"+id+"页面";
return username;
}
}
认证
//认证
@Override //重写configure(HttpSecurity http)方法,它是链式编程
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//这里的根地址都是http://localhost:8080/
.antMatchers(" /").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限,默认跳入登录页面
http.formLogin();
}
用户授权
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
.and()
.withUser("xiao").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2");
}