9.从零搭建WebApi接口开发框架-根据token控制接口请求

生成中接口的请求必须加token进行权限校验,比如校验是否登录获取的token,校验该用户是否具体该接口访问权限等等。
这里以判断用户是否登录做例子进行讲解。

配置SpringContextUtil

项目中如果静态类根据beanId来获取对象,需要提前注入SpringContextUtil。

@SpringBootApplication
public class WebApiStartApplication {
    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(WebApiStartApplication.class, args);
        SpringContextUtil.setApplicationContext(applicationContext);
    }
}

启动类中先注入aplicationConotext

SprintContextUtil

public class SpringContextUtil {
    /**
     * 上下文对象
     */
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    /**
     *
     * @param beanId bean的id
     * @return 该类的实例
     */
    public static Object getBean(String beanId) {
        return applicationContext.getBean(beanId);
    }
}

增加拦截器CheckLoginInterceptor

public class CheckLoginInterceptor implements HandlerInterceptor {

    /**
     * 操作前先判断是否登录,未登录提示未登录
     *
     * @param request  request
     * @param response response
     * @param handler  handler
     * @return 处理是否成功
     * @throws Exception 异常
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (StringUtil.isNullOrEmpty(request.getHeader("Authorization")) || TokenUtil.getToken(request) == null) {
            //状态设置为未授权
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            StringUtil.out(response, JsonUtil.toStr(new JsonResult(false, GlobalReturnCode.NO_AUTH)));
            return false;
        } else {
            return true;
        }
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}

这里是拦截器,在preHandler里面获取header中的Authorization属性,如果该属性不为空,且可以通过redis查到,则具备权限。

增加拦截器配置CheckLoginConfig

@Configuration
public class CheckLoginConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //校验是否登录拦截器
        registry.addInterceptor(new CheckLoginInterceptor())
                //消息相关
                .addPathPatterns("/news/*");
        super.addInterceptors(registry);
    }
}

这里面以url的通配符来作为拦截器的格式,这里只加入/news/*相关的,其余的比如登录接口是不需要校验的。

测试未登录
直接输入接口,进行访问,会提示如下错误:


未登录.png

请求header增加Authorization


校验成功.png

源码下载

本例子详细源码

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,087评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,932评论 25 709
  • 1. 微服务架构介绍 1.1 什么是微服务架构? 形像一点来说,微服务架构就像搭积木,每个微服务都是一个零件,并使...
    静修佛缘阅读 6,708评论 0 39
  • 做人,适时把自己“归零”,就会心胸开阔。 人生,难免会有成功与失败、顺境与逆境。顺境时,把自己适时“归零”,可以戒...
    TWE阅读 627评论 0 1
  • 这可能是今年季后赛最精彩的系列赛了吧,直至目前,绿军和奇才分别在自己主场拿下三场比赛,可见两队实力相近以及主场优势...
    zoneball阅读 163评论 0 0