SpringSecurity快速入门
Spring Security 是一个提供身份验证、授权和针对常见攻击的保护的框架。凭借对命令式和反应式应用程序的一流支持,它是保护基于 Spring 的应用程序的事实上的标准。
01 环境搭建
- 在pom.xml中加入依赖
- 导入静态资源
welcome.html
|views
|level1
1.html
2.html
3.html
|level2
1.html
2.html
3.html
|level3
1.html
2.html
3.html
Login.html
- controller跳转!
@Controller
public class RouterController {
@RequestMapping({
"/","/index"})
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;
}
}
此时环境就搭建好了
02 认证和授权
此时静态资源是所有人都可以访问的,我们要再次基础上通过spring security增加认证和授权功能
此时我们要编写 Spring Security 配置类,在config包下新建一个SecurityConfig.java
我们先建立一个基础的配置类
package com.king.config;
/**
* 开启WebSecurity模式
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 用于授权
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/***").hasRole("vip")
.antMatchers("/level2/***").hasAnyRole("vip","svip")
.antMatchers("/level3/***").hasAnyRole("vip1","svip","ssvip");
// 开启自动配置的登录功能
// /login 请求来到登录页
// /login?error 重定向到这里表示登录失败
http.formLogin();
}
/**
* 用于认证
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("vip").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("svip").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")