一、项目开发
1.1、创建一个web项目,并且集成SpringSecurity
1.2、添加一个配置类
package com.example.demo01.configuration;
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 SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //表单登陆
.and()
.authorizeRequests() //认证配置
.anyRequest() //任何请求
.authenticated(); //都需要身份验证
}
}
1.3、添加一个测试方法
package com.example.demo01;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RequestMapping("/test")
@RestController
public class Demo01Application {
public static void main(String[] args) {
SpringApplication.run(Demo01Application.class, args);
}
@GetMapping("/hello")
public String helloWorld(){
return "Hello World !";
}
}
1.4、测试
项目运行起来之后,控制台会生成一个密码,我们用这个密码登陆,用户名默认是user
浏览器访问http://localhost:8080/test/hello,会自动跳转到登陆页面进行登陆
登陆成功后(用户通过认证),可以正常请求接口地址