Springboot集成Shiro和JWT

SpringBoot 2*版本

pom.xml 依赖

<!--shiro + jwt-->
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring</artifactId>
  <version>1.4.1</version>
</dependency>
<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>3.8.2</version>
</dependency>

配置类 Config_Shiro

/**
 * shiro配置,不要用shiro的缓存,会和spring冲突
 */
@Configuration
public class Config_Shiro {

    /**
     * 1.自定义的Realm
     */
    @Bean
    public ShiroRealm MyRealm() {
        return new ShiroRealm();
    }

    /**
     * 2.配置Shiro过滤器管理
     */
    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        //添加自己的过滤器
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JWTFilter());
        factoryBean.setFilters(filterMap);
        
        //设置无权限时跳转的url
        //factoryBean.setUnauthorizedUrl("/unauthorized/无权限");

        Map<String, String> filterRuleMap = new HashMap<>();
        //所有的请求通过我们自己的JWT-Filter
        filterRuleMap.put("/**", "jwt");

        //放行不需要校验的接口
        filterRuleMap.put("/swagger.**", "anon");
        filterRuleMap.put("/v3.**", "anon");
        filterRuleMap.put(".**_notify_url", "anon");
        factoryBean.setFilterChainDefinitionMap(filterRuleMap);
        return factoryBean;
    }

    /**
     * 3.注入securityManager
     */
    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置自定Realm
        securityManager.setRealm(MyRealm());
        //关闭Shiro自带的session
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        return securityManager;
    }


    /**
     * 添加注解支持
     */
    @Bean
    @DependsOn({"lifecycleBeanPostProcessor"})
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

    /**
     * shiroConfig中@Value加载失败的解决方案
     * lifecycleBeanPostProcessor是负责生命周期的,初始化和销毁的类
     */
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
}

JWT和过滤器等工具

  1. ShirRealm
/**
 * 自定义校验类
 */
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private IUmsMemberService memberService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 权限验证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        String userName = JWTUtil.getUsername(principalCollection.toString());
//        Member member = service_login.GetMember(userName);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    /**
     * 默认使用此方法进行用户正确与否验证,错误抛出异常即可
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        String userName = JWTUtil.getUsername(token);
        String LoginType = JWTUtil.getLoginType(token);
        String password = null;
        
        if (LoginType != null && LoginType.equals("user")) {
            password = memberService.GetByNameMember(userName).getPassword();
            if (password == null) {
                throw new AuthenticationException("用户不存在");
            }
        }
        
        if (userName != null) {
            if (JWTUtil.verify(token, userName, password)) {
                return new SimpleAuthenticationInfo(token, token, getName());
            } else {
                throw new MyException(900, "用户密码错误");  //自定义的异常类
            }
        } else {
            throw new AuthenticationException("token认证失败");
        }
    }
}
  1. JWTUtil

public class JWTUtil {

    //一天过期
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    /**
     * 生成token; loginType为登录类型
     */
    public static String sign(String username, String password, String loginType) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(password);
        return JWT.create()
                .withClaim("username", username)
                .withClaim("loginType", loginType)
                .withExpiresAt(date).sign(algorithm);
    }

    /**
     * 验证token
     */
    static boolean verify(String token, String username, String password) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(password);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 根据token解密出用户名
     */
    static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 根据token解密出登录类型
     */
    static String getLoginType(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("loginType").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
  1. JWTToken
public class JWTToken implements AuthenticationToken {

    private String token;

    JWTToken(String token) {
        this.token = token;
    }

    @Override
    public Object getPrincipal() {
        return token;
    }

    @Override
    public Object getCredentials() {
        return token;
    }
}
  1. MD5Util 登录时用到
public class MD5Util {
    /**
     * 加盐加密2次
     */
    public static String MD5Pwd(String username, String pwd) {

        return new SimpleHash(
                "MD5",
                pwd,
                ByteSource.Util.bytes(username + "salt"),
                2).toHex();
    }
}
  1. JWTFilter 过滤器
@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {

    private static String LOGIN_SIGN = "Authorization";
    private int code;

    /**
     * 1.跨域处理,过滤器之前处理前置增强
     */
    protected 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"));
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 2.preHandle 过滤器之前处理前置增强
     * 返回true则允许访问,否则跳转到onAccessDenied
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        String servletPath = ((HttpServletRequest) request).getServletPath();
        log.info("请求路径:"+servletPath);

        //验证是否是有token
        if (isLoginAttempt(request, response)) {
            try {
                //进行shiro的校验
                executeLogin(request, response);
            } catch (Exception e) {
                code = Integer.parseInt(e.getMessage());
                return false;
            }
        }
        return true;
    }

    /**
     * 3.不允许访问之后执行此方法
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        ((HttpServletResponse) response).setStatus(code);
        //如果返回true表示需要继续处理; 如果返回false表示该拦截器实例已经处理了,将直接返回即可
        return false;
    }

    /**
     * 4.在拦截器链执行完成后执行
     * 下一个是方法是afterCompletion; 完成处理/后置最终处理
     */
    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        super.postHandle(request, response);
    }


    /**
     * 验证是否是有token
     * 有:已经登录过,需要再验证token有效性
     * 没有:用户想登录,而且请求是白名单中的login请求,放行
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader("Authorization");
        return authorization != null;
    }
    /**
     * 如果有token,就去验证token,或者已经登录了
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String header = httpServletRequest.getHeader(LOGIN_SIGN);
        JWTToken token = new JWTToken(header);
        //提交给Realm进行验证, 如没有抛出异常, 则代表验证成功返回true
        getSubject(request, response).login(token);
        return true;
    }
}

controller

    @RequestMapping(value = "/Login" ,method = RequestMethod.POST)
    public ResponseCon<?> login(String username, String password, Integer login_type) {
        //根据用户名读取用户信息
        UmsMember member = memberService.GetByNameMember(username);
        if (member != null) {
        
            //把前端传来的密码用md5工具加密,也可以在前端加密
            password = MD5Util.MD5Pwd(username, password);
            
            //与数据库中加密字符串对比一下,一样则密码正确
            if (member.getPassword().equals(password)) {
                //生成token,返回给前端保存
                member.setToken(JWTUtil.sign(username, password, "user"));
                ...
                return new ResponseCon<>(200, "success", member);
            }
        }
        return new ResponseCon<>(401, "error", "用户名或密码错误");
    }

自测…

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值