官方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