# SpringBootJWTShiro **Repository Path**: mrzhouy/SpringBootJWTShiro ## Basic Information - **Project Name**: SpringBootJWTShiro - **Description**: springBoot + JWT + Shiro + 自定义注解 @CurrentUser 注入当前用户 - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 3 - **Forks**: 0 - **Created**: 2018-09-10 - **Last Updated**: 2021-01-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SpringBootJWTShiro #### 项目介绍 springBoot + JWT + Shiro + 自定义注解 @CurrentUser 注入当前用户 ### 构建简易的数据源 为了缩减教程的代码,我使用`HashMap`本地模拟了一个数据库,结构如下 | username | password | role | permission | | -------- | -------- | ----- | ---------- | | smith | smith123 | user | view | | danny | danny123 | admin | view,edit | 这是一个最简单的用户权限表,如果想更加进一步了解,自行百度RBAC。 ### 自定义注解 @CurrentUser 注入当前用户 ```java package com.zhou.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 在Controller的方法参数中使用此注解,该方法在映射时会注入当前登录的User对象 */ @Target(ElementType.PARAMETER) // 可用在方法的参数上 @Retention(RetentionPolicy.RUNTIME) // 运行时有效 public @interface CurrentUser { } ``` ```java package com.zhou.shiro; import com.zhou.annotation.CurrentUser; import com.zhou.database.UserBean; import com.zhou.exception.UnauthorizedException; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.multipart.support.MissingServletRequestPartException; /** * 增加方法注入,将含有 @CurrentUser 注解的方法参数注入当前登录用户 */ public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterType().isAssignableFrom(UserBean.class) && parameter.hasParameterAnnotation(CurrentUser.class); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { UserBean user = (UserBean) webRequest.getAttribute("currentUser", RequestAttributes.SCOPE_REQUEST); if (user == null) { throw new UnauthorizedException("获取用户信息失败"); } return user; } } ``` ```java @GetMapping("/article") public ResponseBean article(@CurrentUser UserBean currentUser) { Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { return new ResponseBean(200, "You are already logged in", currentUser); } else { return new ResponseBean(200, "You are guest", currentUser); } } ```