如何在Java Spring上分配jwt令牌以生成身份验证

时间:2019-04-30 16:03:44

标签: java spring spring-boot jwt jwt-auth

如何解码令牌并分配为字符串以匹配对象?

示例: 用户使用电话号码登录,解码后将生成一个jwt令牌:

{
  "sub": "+440000010010" //can be any phone number
}

然后我需要获取此电话号码并与匹配的字段phoneNumber进行比较,然后它将生成有效的身份验证。

我的代码错误显示为不兼容的类型java.lang.string

我的令牌句柄生成并验证令牌

public String generate(String username) {

        Claims claims = Jwts.claims().setSubject(username);
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

        return Jwts.builder()
                .setIssuedAt(new Date())
                .setExpiration(expiryDate)
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    public JwtUserDetails validate (String token) {
        JwtUserDetails jwtUserDetails = null;
        try {
            Claims body = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
            jwtUserDetails = new JwtUserDetails(body.getSubject(), token);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jwtUserDetails;
    }

     public boolean validateToken(String token) {
            try {
                Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);
                return true;
            } catch (SignatureException ex) {
                logger.error("Invalid JWT signature");
            } catch (MalformedJwtException ex) {
                logger.error("Invalid JWT token");
            } catch (ExpiredJwtException ex) {
                logger.error("Expired JWT token");
            } catch (UnsupportedJwtException ex) {
                logger.error("Unsupported JWT token");
            } catch (IllegalArgumentException ex) {
                logger.error("JWT claims string is empty.");
            }
            return false;
        }

我的过滤器是

@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String jwt = getJwtFromRequest(request);

            if (StringUtils.hasText(jwt) && jwtTokenHandler.validateToken(jwt)) {

                String phoneNumber = jwtTokenHandler.validate(jwt) ;

                UserDetails userDetails = customUserDetailsService.loadUserPhone(username);

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authentication);
         }


        } catch (Exception ex) {
            logger.error("Could not set user authentication in security context", ex);
        }

        filterChain.doFilter(request, response);
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7, bearerToken.length());
        }
        return null;
    }

我的整个代码都是在测试时生成并验证令牌,但是当我尝试匹配值时出现此错误,那么有人有想法吗?我仍然需要Java Spring。

0 个答案:

没有答案