# 一、使用说明 1.引入依赖 ```xml org.lingniu oauth2-login-sdk 1.0-SNAPSHOT ``` 2.添加配置 ```yaml spring: security: oauth2: resourceserver: jwt: # 资源服务器 认证公钥地址 jwk-set-uri: http://localhost:8000/oauth2/jwks client: registration: portal: # 统一登录颁发的client_id client-id: xxx # 统一登录颁发的秘钥 client-secret: xxx # 当前对接客户端名称 随便填 client-name: xxx # 认证类型 使用授权码类型 authorization-grant-type: authorization_code # 认证地址 redirect-uri: http://106.14.217.120/portal-ui/callback # 权限范围 scope: - openid - profile # 返回权限 - perms provider: idp provider: idp: # sso登录地址 authorization-uri: http://106.14.217.120/idp-ui/sso # token 获取接口 token-uri: http://localhost:8082/oauth2/token # 用户信息接口 user-info-uri: http://localhost:8082/userinfo # 认证公钥地址 jwk-set-uri: http://localhost:8082/oauth2/jwks # 用户信息属性 user-name-attribute: sub ``` 3. 启动项目 # 二 、 权限配置 如果不做额外配置,接入成功后默认所有接口都是登录成功后即可访问,如果需要对接口进行更精确精细化的权限控制,提供了如下注解 - @PreAuthorize:方法执行前进行权限检查 - @PostAuthorize:方法执行后进行权限检查 - @Secured:类似于 @PreAuthorize - security提供了许多默认表达式 ![img.png](img.png) 结合SpEl表达是进行复杂配置 ```java @Service public class HelloService { @PreAuthorize("principal.username.equals('admin')") public String hello() { return "hello"; } @PreAuthorize("principal.username.equals(#abc)") public String admin(String abc) { return "admin"; } @Secured({"ROLE_user"}) public String user() { return "user"; } @PreAuthorize("#age>98") public String getAge(Integer age) { return String.valueOf(age); } @PostAuthorize("returnObject == null || returnObject.id%2==0") public User findUserById(Long id) { // 根据id查找用户,无论用户是否存在,id是偶数的用户才能获取到结果 // 实现根据id查找用户的逻辑... return userRepository.findById(id).orElse(null); } @GetMapping("/testPermission1") @PreAuthorize("@ss.hasPermission('def')") public String testPermission1() { return "testPermission1 有权访问"; } @GetMapping("/testPermission2") @PreAuthorize("@ss.hasPermission(#code)") public String testPermission2(String code) { return "testPermission2 有权访问"; } } ```