1 2 3 4 5 6
| cn.weisw ├── config │ └── SecurityConfig.java ├── PermissionServer.java ├── test.java └── MainApplication.java
|
1.开启注解
因为注解默认不可用,所以在使用前需要开启注解
- @Secured:专门判断用户是否具有角色,可以写在方法或类上,参数以 ROLE_ 开头
- @PreAuthorize\PostAuthorize: PreAuthorize 访问的类或方法执行前判断权限,而 PostAuthorize 在执行之后,Post 基本不用;允许与 ROLE_ 开头。
1 2 3 4 5 6 7 8 9
| package cn.weisw.config;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { }
|
2.注册服务
使用@Service
注册ps
服务
1 2 3 4 5 6 7 8 9 10 11 12
| package cn.weisw;
import org.springframework.stereotype.Service;
@Service("ps") public class PermissionService {
public boolean hasPermi(String permission) { System.out.println(permission); return true; } }
|
3.接口中使用
使用ps
的服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package cn.weisw;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@RestController @RequestMapping("/") public class test {
@PreAuthorize("@ps.hasPermi('system')") @GetMapping("/aa") public void aa() { System.out.println(333); } }
|
4.开启服务
1 2 3 4 5 6 7 8 9 10 11
| package cn.weisw;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class MainApplication { public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } }
|
5.访问接口
使用spring-boot-starter-security
会打印下列日志,其中security password
作为默认用户user
的临时密码,是一个UUID字符串,访问接口时会进行登录校验,重定向至http://localhost:8080/login
,此时输入Username:user,Password:269411c9-f772-4b90-8a48-9786dd754487
登录后跳转至http://localhost:8080/aa
1 2 3
| Using generated security password: 269411c9-f772-4b90-8a48-9786dd754487
This generated password is for development use only. Your security configuration must be updated before running your application in production.
|
接口访问成功后,会先进行public boolean hasPermi(String permission)
进行校验,成功打印如下