1. 创建Springboot项目,引入SpringSecurity依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. 为了方便,替换SpringSecurity默认的用户名和生成的密码,使用自定义账号密码:
# 设置账号为 root
spring.security.user.name=root
# 设置密码为 root
spring.security.user.password=root
3. 创建两个Controller,一个可以放行,一个会被拦截
这里 “/index” 作为 公共资源
,可以访问,“/hello” 为 受限资源
,不可以访问。
IndexController:
/**
* 该类映射的网址是公共资源,不受security保护,任何人都可以访问
*/
@RestController
public class IndexController {
@RequestMapping("/index")
public String index() {
return "hello index";
}
}
HelloController:
/**
* 该类是私有资源,需要进行认证授权后才可以访问
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello spring security";
}
}
4. 创建一个类,继承 WebSecurityConfigurerAdapter
类,继承这个类后,就可以在 configure(HttpSecurity http)
方法中自定义认证规则了。
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class MyWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() // 开启请求的权限管理
.mvcMatchers("/index").permitAll() // 放行 "/index" 请求
//.mvcMatchers("/hello").authenticated() 指定 "/hello" 请求需要认证
.anyRequest().authenticated() // 除了放行的请求,所有请求都需要认证
.and()
.formLogin() // 进行表单认证
//.loginPage(""); // 更换登录界面
// http.formLogin(); 也可以单独写表单认证,不过更建议链式调用
}
}
注意:
- 要先放行,后认证;
- 注意
@Configuration
注解,声明该类是一个配置类。
5. 效果
访问 “/index” 可以正常访问:
而访问 “/hello” 则会跳转到 SpringSecurity 自带的登录页面:
输入自定义密码后可以正常访问: