Spring Boot整合JWT实现接口访问认证

最近项目组需要对外开发相关API接口,需要对外系统进行授权认证。实现流程是先给第三方系统分配appId和appSecret,第三方系统调用我getToken接口获取token,然后将token填入Authorization请求头用于访问相关API接口。

参考文章:https://blog.csdn.net/ltl112358/article/details/79507148

具体实现方式如下:

1.引入jjwt依赖

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.6.0</version>
        </dependency>

2.编写Filter

用于保护受限的API接口。

package com.laoxu.easyblog.framework;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class ApiFilter extends GenericFilterBean {

    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
            throws IOException, ServletException {

        // Change the req and res to HttpServletRequest and HttpServletResponse
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;

        // Get authorization from Http request
        final String authHeader = request.getHeader("authorization");

        // If the Http request is OPTIONS then just return the status code 200
        // which is HttpServletResponse.SC_OK in this code
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);

            chain.doFilter(req, res);
        }
        // Except OPTIONS, other request should be checked by JWT
        else {

            // Check the authorization, check if the token is started by "Bearer "
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                throw new ServletException("Missing or invalid Authorization header");
            }

            // Then get the JWT token from authorization
            final String token = authHeader.substring(7);

            try {
                // Use JWT parser to check if the signature is valid with the Key "secretkey"
                final Claims claims = Jwts.parser().setSigningKey("laoxu").parseClaimsJws(token).getBody();

                // Add the claim to request header
                request.setAttribute("claims", claims);
            } catch (final SignatureException e) {
                throw new ServletException("Invalid token");
            }

            chain.doFilter(req, res);
        }
    }
}
package com.laoxu.easyblog.config;

import com.laoxu.easyblog.framework.ApiFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description: 对指定api接口进行访问认证
 * @Author laoxu
 * @Date 2019/5/10 21:17
 **/
@Configuration
public class ApiAuthConfig {
    @Bean
    public FilterRegistrationBean apiFilter() {
        final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new ApiFilter());
        registrationBean.addUrlPatterns("/api/user/*");

        return registrationBean;
    }
}

3.编写API接口

package com.laoxu.easyblog.controller;

import com.laoxu.easyblog.framework.Result;
import com.laoxu.easyblog.framework.ResultUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @Description:
 * @Author laoxu
 * @Date 2019/5/10 22:04
 **/
@RestController
@RequestMapping("/api")
public class TokenController {
    @PostMapping("/getToken")
    public Result<String> login(@RequestParam("appId") String appId, @RequestParam("appSecret") String appSecret) {
        if(!("app123".equals(appId) && "123".equals(appSecret))){
            return ResultUtil.fail("授权失败");
        }

        // Create Twt token
        String jwtToken = Jwts.builder().setSubject(appId).claim("roles", "member").setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "laoxu").compact();

        return ResultUtil.ok(jwtToken);
    }

}
package com.laoxu.easyblog.controller;

import com.laoxu.easyblog.framework.Result;
import com.laoxu.easyblog.framework.ResultUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Description:
 * @Author laoxu
 * @Date 2019/5/10 22:04
 **/
@RestController
@RequestMapping("/api/user")
public class ApiController {
    @RequestMapping("/getUser")
    public Result<String> loginSuccess() {
        return ResultUtil.ok("zhangsan");
    }

}

 

4.测试

4.1 直接访问受限接口

4.2 获取token

4.3 携带token再次访问受限接口

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值