添加controller,访问 http://localhost:8099/api/greeting ,页面打印:Hello world
package com.example.security.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/greeting")
public String greeting(){
return "Hello world";
}
}
pom.xml引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
再访问 http://localhost:8099/api/greeting ,出现认证登录页。
通过控制台输出内容复制密码:用户名为user
Using generated security password: cbd4c0e1-28c2-49a4-9176-6883cdef7acb
配置授权:
package com.example.security.config;
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;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests(req-> req.mvcMatchers("/api/greeting").hasRole("ADMIN"));
}
}
再访问 http://localhost:8099/api/greeting ,登录后也不能访问,出现403,因为没有ADMIN
权限。
默认配置如下(不认证权限):
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests((requests) -> {
((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)requests.anyRequest()).authenticated();
});
http.formLogin();
http.httpBasic();
// http.authorizeRequests(req-> req.mvcMatchers("/api/greeting").hasRole("ADMIN"));
}
postman之类工具访问通过Basic Auth:
添加post请求的api
@PostMapping("/addUser")
public String addUser(){
return "Add User";
}
访问出现403,因为post请求有csrf验证,临时关闭disable(前后端分离情况下通过token获取密串解决)
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests((requests) -> {
((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)requests.anyRequest()).authenticated();
});
http.formLogin();
http.httpBasic();
http.csrf(csrf->csrf.disable());
// http.authorizeRequests(req-> req.mvcMatchers("/api/greeting").hasRole("ADMIN"));
}
默认密码
server:
port: 8099
spring:
security:
user:
name: user
password: 12345678
roles: USER,ADMIN
debug模式
@EnableWebSecurity(debug = true)
定时登录页:
csrf、rememberMe放到cookie或者session