1、在pom文件中引入<!-- Spring Security -->
<!-- 添加Spring Security依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
引入之后,记得刷新加载!!!
2、自定义配置类,将Spring Security应用于项目中
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
@Configuration
@EnableWebSecurity //开启SpringSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //权限应用于方法级别
public class SecurityConfig extends WebSecurityConfigurerAdapter {
String[] urls = {
"/test/test01",
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(urls).permitAll() // 放行的接口
.anyRequest() .authenticated()//所有请求都需要认证
.and()
.formLogin() //启用表单认证
.and()
.httpBasic();
}
}
该配置类中接口为/test/test01的接口会被放行;
3、在controlle的包中书写对应的访问方法
package com.example.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/test01")
public String test01(){
return "1111";
}
@GetMapping("/test02")
public String test02(){
return "2222";
}
}
之启动该项目,项目启动时,记得不要清除控制台的日志;
SpringSecurity的默认用户名是User,密码会通过控制台打印出来;
4、访问接口
访问/test/test01时,不需要验证,直接进入
访问/test/test02时,需要验证,输入用户名,密码进入
输入用户名user,密码:ed451932-944f-4cfb-8bb2-06767c444564
登录成功