官方git地址:https://gitee.com/itmuch/light-security/tree/master

引入maven

<dependency>
<groupId>com.itmuch.security</groupId>
<artifactId>light-security-spring-boot-starter</artifactId>
<version>1.0.1-RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

配置文件

server:
port: 8009
light-security:
# 权限规则配置:表示用{http-method}方法请求的{path}路径必须具备什么{expression}
spec-list:
- http-method: ANY
path: /login
expression: "anon()"
- http-method: ANY
path: /user
expression: "hasAnyRoles('user','admin')"
- http-method: ANY
path: /user-no-access
expression: "hasAllRoles('user','admin','xx')"
- http-method: GET
path: /error
expression: "anon()"
- http-method: ANY
path: /**
expression: "hasLogin()"
jwt:
# jwt sign算法
algorithm: hs512
# jwt secret
secret: {secret}
# jwt 有效时间
expiration-in-second: 1209600

代码示例

@RequestMapping
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestController {
private final UserOperator userOperator;
private final JwtOperator operator; /**
* 演示如何获取当前登录用户信息
* - 该路径需要具备user或admin权限才可访问,详见application.yml
*
* @return 用户信息
*/
@GetMapping("/user")
public User user() {
return userOperator.getUser();
} /**
* 模拟登录,颁发token
*
* @return token字符串
*/
@GetMapping("/login")
public String loginReturnToken() {
User user = User.builder()
.id(1)
.username("张三")
.roles(Arrays.asList("user", "admin"))
.build(); //也可以以下这种方式
User user = User.builder()
.id("用户ID")
.username("用户名")
.build(); return operator.generateToken(user);
}
}

然后前端访问的时候要携带请求头

格式为

Authorization:Bearer token

这里的token替换成上面颁发的token 注意Bearer和token之间有个空格

异常捕获处理

LightSecurityExceptionHandler.java
package com.ruoyi.exception;

import com.itmuch.lightsecurity.exception.LightSecurityException;
import com.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* @ClassName 全局异常处理
* @Author hupeng <610796224@qq.com>
* @Date 2019/6/27
**/
@Slf4j
@ControllerAdvice
public class LightSecurityExceptionHandler { /**
* Light Security相关异常
*
* @param exception 异常
* @return 发生异常时的返回
*/
@ExceptionHandler(value = {LightSecurityException.class})
@ResponseBody
public R error(HttpServletRequest request, LightSecurityException exception, HttpServletResponse response) {
log.error(exception.toString());
return R.error(4000, exception.getMessage()); } @ExceptionHandler(value = {Exception.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public R allError(Exception exception) {
log.error(exception.toString());
return R.error(4000,exception.getMessage());
} /**
* 处理所有接口数据验证异常
* @param e
* @returns
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
String[] str = e.getBindingResult().getAllErrors().get(0).getCodes()[1].split("\\.");
StringBuffer msg = new StringBuffer(str[1]+":");
msg.append(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return R.error(4001,msg.toString());
} /**
* 处理自定义异常
* @param e
* @return
*/
@ExceptionHandler(value = BadRequestException.class)
public R badRequestException(BadRequestException e) {
return R.error(4002,e.getMessage());
} /**
* 处理 EntityExist
* @param e
* @return
*/
@ExceptionHandler(value = EntityExistException.class)
public R entityExistException(EntityExistException e) {
return R.error(4003,e.getMessage());
}
}
R.java 参考:https://www.cnblogs.com/pxblog/p/13792038.html

最新文章

  1. Java内部DNS查询实现和参数设置
  2. chkconfig命令详解
  3. SQLPlus 在连接时通常有四种方式
  4. 性能优化九之UI卡顿分析
  5. GATT 服务器与客户端角色
  6. PLSQL_基础系列05_视图控制WITH CHECK OPTION(案例)
  7. ios专题 - 安全
  8. 正则表达式:根据逗号解析CSV并忽略引号内的逗号
  9. 【ASP.NET Web API教程】5.2 发送HTML表单数据:URL编码的表单数据
  10. hdu 逆袭指数
  11. 你会python不?当你听到这个问题要谨慎回答!!!
  12. 关于bootstrap框架美化的实例教程(python)
  13. 患者信息SQL v1
  14. 【ELK】之Kibana使用
  15. docker rmi 导致后面的命令不执行问题 Dockerfile设置时区问题
  16. HashMap分析
  17. 人人,金山西山居,腾讯互娱,微信,网易游戏offer及面经
  18. python连接mysql数据库封装
  19. CentOS 7 基础命令安装
  20. 【CC2530强化实训02】普通延时函数实现按键的长按与短按

热门文章

  1. NOI 2008 志愿者招募
  2. 混合(Pooling)样本测序研究
  3. Docker Error response from daemon,Docker 换镜像
  4. kafka的安装及使用
  5. 错误笔记: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable) E: Unable to lock the administration di
  6. 12 — springboot集成JPA — 更新完毕
  7. 零基础学习java------29---------网络日志数据session案例,runtime(导出jar程序)
  8. Linux学习 - 系统命令sudo权限
  9. react-native安卓运行报错:The number of method references in a .dex file cannot exceed 64K.
  10. ANTLR 相关术语