黑马十次方项目day06-17之问答模块进行token验证

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33229669/article/details/87453265


在问答模块中,如果要添加问题,那么需要user的权限,才能进行添加

相关代码的复制

在tensquare_qa问答模块中,复制InterceptorConfig和JwtInterceptor到该工程中.
这两个类的内容,在上面的章节中有提到.
并且在yml中,添加jwt的验证信息

jwt:
  config:
    key: itcast    # 设置token的盐为 itcast

在QaApplication 中,把JwtUtil类放入容器中

 /**
     * 把jwt对象注入容器中
     * @return
     */
    @Bean
    public JwtUtil jwtUtil(){
        return new JwtUtil();
    }

ProblemController

在ProblemController重新编写add,添加问题的方法.
首先在pom.xml中,添加lang3的包

      <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-lang3</artifactId>
      </dependency>

内容如下

/**
	 * 增加
	 * @param problem
	 */
	@RequestMapping(method=RequestMethod.POST)
	public Result add(@RequestBody Problem problem  ){
	    String token = (String) request.getAttribute("claims_user");
        if (StringUtils.isBlank(token)) {
            return new Result(false,StatusCode.ACCESSERROR,"权限不足");
        }
		problemService.add(problem);
		return new Result(true,StatusCode.OK,"增加成功");
	}

测试

启动tensquare_user和tensquare_qa工程.
首先执行user的登录,获取token如下
eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDg5ODY2NDEwOTgyNzcyNzM2Iiwic3ViIjoiMTMwNzEyNTY0MzUiLCJpYXQiOjE1NTAzMDIyNDcsInJvbGVzIjoidXNlciIsImV4cCI6MTU1MDMwNTg0N30.6N1Oo_muRyHdtAhMIxBbi6m1PNJ6DBIzShH5un69eLc
其次进行问题的添加操作
在postman中,发送如下的post请求
http://localhost:9003/problem
请求体中的json内容如下

带上token信息如下

响应数据如下. 代表添加成功

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/87453265