前言
目的:
通过注解完成权限控制。
源码下载:Spring-Boot-Shiro-master.zip
效果:

操作
代码一览

maven引用
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.3.2</version></dependency><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.2.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>1.5.8.RELEASE</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.4</version></dependency>
基础代码
ShiroUserBean
@Data@Builder@NoArgsConstructor@AllArgsConstructor@FieldNameConstantspublic class ShiroUserBean {private String username;private String password;private String role;private String permission;}
JWTUtil
import com.auth0.jwt.JWT;import com.auth0.jwt.JWTVerifier;import com.auth0.jwt.algorithms.Algorithm;import com.auth0.jwt.exceptions.JWTDecodeException;import com.auth0.jwt.interfaces.DecodedJWT;import org.inlighting.database.ShiroUserBean;import java.io.UnsupportedEncodingException;import java.util.Date;public class JWTUtil {private static String SECRET = "123SDFEEdfdeFDRE";/*** 过期时间1000 60 秒 60 分钟 24 小时 5 天*/private static final long EXPIRE_TIME = 1000*60*60*24*5;/*** 校验token是否正确,是否过期* @param token 密钥* @return 是否正确*/public static boolean verify(String token) {try {Algorithm algorithm = Algorithm.HMAC256(SECRET);JWTVerifier verifier = JWT.require(algorithm).build();DecodedJWT jwt = verifier.verify(token);return true;} catch (Exception exception) {return false;}}/*** 获得token中的信息* @return ShiroUserBean*/public static ShiroUserBean getUserBean(String token) {try {DecodedJWT jwt = JWT.decode(token);ShiroUserBean shiroUserBean = new ShiroUserBean();shiroUserBean.setUsername(jwt.getClaim(ShiroUserBean.Fields.username).asString());shiroUserBean.setRole(jwt.getClaim(ShiroUserBean.Fields.role).asString());shiroUserBean.setPermission(jwt.getClaim(ShiroUserBean.Fields.permission).asString());return shiroUserBean;} catch (JWTDecodeException e) {return null;}}/*** 生成签名,5min后过期* @param shiroUserBean 用户名* @return 加密的token*/public static String sign(ShiroUserBean shiroUserBean) {try {Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);Algorithm algorithm = Algorithm.HMAC256(SECRET);// 附带username信息return JWT.create().withClaim(ShiroUserBean.Fields.username, shiroUserBean.getUsername()).withClaim(ShiroUserBean.Fields.role, shiroUserBean.getRole()).withClaim(ShiroUserBean.Fields.permission, shiroUserBean.getPermission()).withExpiresAt(date).sign(algorithm);} catch (UnsupportedEncodingException e) {return null;}}}
UnauthorizedException
public class UnauthorizedException extends RuntimeException {public UnauthorizedException(String msg) {super(msg);}public UnauthorizedException() {super();}}
shiro配置
直接复制接口,基本上不变
JWTToken
import org.apache.shiro.authc.AuthenticationToken;public class JWTToken implements AuthenticationToken {// 密钥private String token;public JWTToken(String token) {this.token = token;}@Overridepublic Object getPrincipal() {return token;}@Overridepublic Object getCredentials() {return token;}}
JWTFilter
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.RequestMethod;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class JWTFilter extends BasicHttpAuthenticationFilter {private Logger LOGGER = LoggerFactory.getLogger(this.getClass());/*** 判断用户是否想要登入。* 检测header里面是否包含Authorization字段即可*/@Overrideprotected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {HttpServletRequest req = (HttpServletRequest) request;String authorization = req.getHeader("Authorization");return authorization != null;}/****/@Overrideprotected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {HttpServletRequest httpServletRequest = (HttpServletRequest) request;String authorization = httpServletRequest.getHeader("Authorization");JWTToken token = new JWTToken(authorization);// 提交给realm进行登入,如果错误他会抛出异常并被捕获getSubject(request, response).login(token);// 如果没有抛出异常则代表登入成功,返回truereturn true;}/*** 这里我们详细说明下为什么最终返回的都是true,即允许访问* 例如我们提供一个地址 GET /article* 登入用户和游客看到的内容是不同的* 如果在这里返回了false,请求会被直接拦截,用户看不到任何东西* 所以我们在这里返回true,Controller中可以通过 subject.isAuthenticated() 来判断用户是否登入* 如果有些资源只有登入用户才能访问,我们只需要在方法上面加上 @RequiresAuthentication 注解即可* 但是这样做有一个缺点,就是不能够对GET,POST等请求进行分别过滤鉴权(因为我们重写了官方的方法),但实际上对应用影响不大*/@Overrideprotected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {if (isLoginAttempt(request, response)) {try {executeLogin(request, response);} catch (Exception e) {response401(request, response);}}return true;}/*** 对跨域提供支持*/@Overrideprotected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {HttpServletRequest httpServletRequest = (HttpServletRequest) request;HttpServletResponse httpServletResponse = (HttpServletResponse) response;httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));// 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {httpServletResponse.setStatus(HttpStatus.OK.value());return false;}return super.preHandle(request, response);}/*** 将非法请求跳转到 /401*/private void response401(ServletRequest req, ServletResponse resp) {try {HttpServletResponse httpServletResponse = (HttpServletResponse) resp;httpServletResponse.sendRedirect("/401");} catch (IOException e) {LOGGER.error(e.getMessage());}}}
ShiroConfig
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;import org.apache.shiro.mgt.DefaultSubjectDAO;import org.apache.shiro.spring.LifecycleBeanPostProcessor;import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;import org.apache.shiro.spring.web.ShiroFilterFactoryBean;import org.apache.shiro.web.mgt.DefaultWebSecurityManager;import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.DependsOn;import javax.servlet.Filter;import java.util.HashMap;import java.util.Map;@Configurationpublic class ShiroConfig {@Bean("securityManager")public DefaultWebSecurityManager getManager(MyRealm realm) {DefaultWebSecurityManager manager = new DefaultWebSecurityManager();// 使用自己的realmmanager.setRealm(realm);/** 关闭shiro自带的session,详情见文档* http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29*/DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();defaultSessionStorageEvaluator.setSessionStorageEnabled(false);subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);manager.setSubjectDAO(subjectDAO);return manager;}@Bean("shiroFilter")public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager) {ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();// 添加自己的过滤器并且取名为jwtMap<String, Filter> filterMap = new HashMap<>();filterMap.put("jwt", new JWTFilter());factoryBean.setFilters(filterMap);factoryBean.setSecurityManager(securityManager);factoryBean.setUnauthorizedUrl("/401");/** 自定义url规则* http://shiro.apache.org/web.html#urls-*/Map<String, String> filterRuleMap = new HashMap<>();// 所有请求通过我们自己的JWT FilterfilterRuleMap.put("/**", "jwt");// 访问401和404页面不通过我们的FilterfilterRuleMap.put("/401", "anon");factoryBean.setFilterChainDefinitionMap(filterRuleMap);return factoryBean;}/*** 下面的代码是添加注解支持*/@Bean@DependsOn("lifecycleBeanPostProcessor")public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();// 强制使用cglib,防止重复代理和可能引起代理出错的问题// https://zhuanlan.zhihu.com/p/29161098defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);return defaultAdvisorAutoProxyCreator;}@Beanpublic LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {return new LifecycleBeanPostProcessor();}@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();advisor.setSecurityManager(securityManager);return advisor;}}
MyRealm
import org.apache.log4j.LogManager;import org.apache.log4j.Logger;import org.apache.shiro.authc.*;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;import org.inlighting.database.ShiroUserBean;import org.inlighting.database.UserService;import org.inlighting.util.JWTUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.Arrays;import java.util.HashSet;@Servicepublic class MyRealm extends AuthorizingRealm {private static final Logger LOGGER = LogManager.getLogger(MyRealm.class);private UserService userService;@Autowiredpublic void setUserService(UserService userService) {this.userService = userService;}/*** 必须重写此方法,不然Shiro会报错*/@Overridepublic boolean supports(AuthenticationToken token) {return token != null;}/*** 只有当需要检测用户权限的时候才会调用此方法,例如checkRole,checkPermission之类的*/@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {ShiroUserBean shiroUserBean = JWTUtil.getUserBean(principals.toString());SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();simpleAuthorizationInfo.addRoles(new HashSet<>(Arrays.asList(shiroUserBean.getRole().split(","))));simpleAuthorizationInfo.addStringPermissions(new HashSet<>(Arrays.asList(shiroUserBean.getPermission().split(","))));return simpleAuthorizationInfo;}/*** 校验是否需要登录*/@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {String token = (String) auth.getCredentials();if (! JWTUtil.verify(token)) {throw new AuthenticationException("need login");}return new SimpleAuthenticationInfo(token, token, "my_realm");}}
测试
import org.apache.log4j.LogManager;import org.apache.log4j.Logger;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authz.annotation.*;import org.apache.shiro.subject.Subject;import org.inlighting.bean.Result;import org.inlighting.database.ShiroUserBean;import org.inlighting.database.UserService;import org.inlighting.exception.UnauthorizedException;import org.inlighting.util.JWTUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.*;@RestControllerpublic class WebController {private static final Logger LOGGER = LogManager.getLogger(WebController.class);private UserService userService;@Autowiredpublic void setService(UserService userService) {this.userService = userService;}@PostMapping("/login")public Result login(@RequestParam("username") String username,@RequestParam("password") String password) {ShiroUserBean shiroUserBean = userService.getUser(username);if (shiroUserBean.getPassword().equals(password)) {return Result.success(200, "Login success", JWTUtil.sign(shiroUserBean));} else {throw new UnauthorizedException();}}@GetMapping("/article")public Result article() {Subject subject = SecurityUtils.getSubject();if (subject.isAuthenticated()) {return Result.success(200, "You are already logged in", null);} else {return Result.success(200, "You are guest", null);}}@GetMapping("/require_auth")@RequiresAuthenticationpublic Result requireAuth() {return Result.success(200, "You are authenticated", null);}@GetMapping("/require_role")@RequiresRoles("admin")public Result requireRole() {return Result.success(200, "You are visiting require_role", null);}@GetMapping("/require_permission")@RequiresPermissions(logical = Logical.AND, value = {"view", "edit"})public Result requirePermission() {return Result.success(200, "You are visiting permission require edit,view", null);}@RequestMapping(path = "/401")@ResponseStatus(HttpStatus.UNAUTHORIZED)public Result unauthorized() {return Result.error(401, "Unauthorized", null);}}
