SpringBoot 使用AOP校验用户

没啥用,写来玩的
需求:

系统有两种用户类型

  1. 管理员
  2. 普通用户

因为系统简单没有使用权限框架来进行校验拦截

建立一个SpringBoot项目
添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

pojo

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer userType;
}

用户类型枚举

@AllArgsConstructor
@Getter
public enum UserTypeEnum {
    ADMIN(1,"管理员"),
    USER(2,"普通用户");
    private Integer typeCode;
    private String  msg;
}

权限注解

// 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AdminOnly {
}

AuthService

@Component
public class AuthService {
    public void checkUser(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        User user =  (User) request.getSession().getAttribute("user");
        if(!user.getUserType().equals(UserTypeEnum.ADMIN.getTypeCode())){
            throw new DemoException(401,"权限不足");
        }
    }
}

aop切面

@Aspect
@Component
@Slf4j
public class AuthAspect {
    @Autowired
    private AuthService authService;
    @Pointcut("@annotation(AdminOnly)")
    public void adminOnly(){

        log.info("执行 adminOnly()");
    }

    @Before("adminOnly()")
    public void check(){
        log.info("Before 执行 check()");
        authService.checkUser();
    }
}

自定义异常

public class DemoException  extends RuntimeException{
    private Integer code;

    public DemoException( Integer code,String message) {
        super(message);
        this.code = code;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
}

全局统一异常处理

@ControllerAdvice
public class DemoExceptionHandler {
   @ExceptionHandler(Exception.class)
   @ResponseBody
    public Map<String,Object> demoExceptionHandler(Exception e){
       Map<String,Object> map =  new HashMap<>();
       if(e instanceof DemoException){
           DemoException demoException = (DemoException) e;
           map.put("code",demoException.getCode());
           map.put("msg",demoException.getMessage());
       }else {
           map.put("code",-1);
           map.put("msg",e.getMessage());
       }
       return map;
   }
}

Controler

@RestController
@Slf4j
public class UserController {
    // 初始化模拟数据
    public static List<User> userList = new ArrayList<>();
    static {
        userList.add(new User(1, "admin", "12345",1));
        userList.add(new User(2, "zhangsan", "zhangsan",2));
        userList.add(new User(3, "jojo", "jojo",2));
    }

    @GetMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpServletRequest request){
        //验证用户名密码
        Optional<User> first = userList.stream().filter(u -> u.getUsername().equals(username) && u.getPassword().equals(password)).findFirst();
        if(!first.isPresent()){
            return "用户名或者密码错误";
        }
        User user = first.get();
        request.getSession().setAttribute("user",user);

        return "登录成功";
    }

    @GetMapping("/index")
    public String index(){
        return "index";
    }

    @GetMapping("/user/list")
    @AdminOnly
    public String list(){
        return "访问成功,说明你拥有权限";
    }
}
  • 普通用户登录后访问带@AdminOnly的url
    在这里插入图片描述
  • 管理员登录后访问带@AdminOnly的url
    在这里插入图片描述

总结:感觉还是定义拦截器或者权限框架实用

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页