当前位置: 首页 > 知识库问答 >
问题:

无法初始化类 io.jsonwebtoken.SignatureAlgorithm , java.lang.NoClassDefFoundError,

郑嘉悦
2023-03-14

在Spring启动应用程序中使用jjwt在REST API中进行基于令牌的身份验证。它在我的本地环境中工作得很好,但是当我在Tomcat中部署war时,它会给出异常-无法初始化类io.jsonwebtoken.Signature的算法。Signature的算法类在jar中,但它的给出java.lang.NoClassDefFoundError错误。

努力在Tomcat中部署它并开始工作。需要帮助来解决问题。快速帮助将不胜感激。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.abc.spring</groupId>
    <artifactId>spring-boot-mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>spring-boot-mongodb</name>
    <description>Spring Boot MongoDB Example</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.64</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcpkix-jdk14</artifactId>
            <version>1.48</version>
        </dependency>

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

        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <version>1.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <!-- JSON Web Token Support -->
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

JWT实用程序

    package com.abc.util;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.telstra.psbc.dto.User;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Component
public class JwtTokenUtil implements Serializable {
    private static final long serialVersionUID = -2550185165626007488L;
    public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;
    @Value("${jwt.secret}")
    private String secret;

//retrieve username from jwt token
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

//retrieve expiration date from jwt token
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    // for retrieveing any information from token we will need the secret key
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

//check if the token has expired
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

//generate token for user
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }

    public String generateTokenbyUser(User userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getName());
    }


    private String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

//validate token
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
}

JWT控制器

    package com.telstra.psbc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.telstra.psbc.dto.User;
import com.telstra.psbc.exception.WorkflowException;
import com.telstra.psbc.pojo.JwtResponse;
import com.telstra.psbc.repos.UserConfigRepository;
import com.telstra.psbc.repos.entity.UserToken;
import com.telstra.util.JwtTokenUtil;

@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping(value = "/")
public class JwtAuthenticationController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    UserConfigRepository userconfig;
    @Autowired
    private UserDetailsService userDetailsService;

    @RequestMapping(value = "/authenticate/{emailid}/{password}/", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@PathVariable String emailid, @PathVariable String password)
            throws Exception {
        // public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest
        // authenticationRequest) throws Exception {
        User user = userconfig.authUserPass(emailid, password);
        // authenticate(user.getName(), user.getPassword());
        final UserDetails userDetails = userDetailsService.loadUserByUsername(user.getName());
        // final String token = jwtTokenUtil.generateToken(userDetails);
        final String token = jwtTokenUtil.generateTokenbyUser(user);

        UserToken usertoken = new UserToken();
        usertoken.setUsername(user.getName());
        usertoken.setUserid(user.getUserId());
        usertoken.setToken("Bearer" + " " + token);
        usertoken.setPassword(user.getPassword());
        userconfig.saveUsertoken(usertoken);
        return ResponseEntity.ok(new JwtResponse(token));
    }

    @RequestMapping(value = "/profile/", method = RequestMethod.GET)
    public User getUserbytoken(@RequestHeader("Authorization") String token) throws Exception {
        UserToken usertoken = userconfig.getUserbytoken(token);
        User user = new User();
        if (usertoken != null) {
            user = userconfig.findUserById(usertoken.getUserid());
            return user;
        } else {
            throw new WorkflowException("401", "User Not Authorized", HttpStatus.UNAUTHORIZED);
        }
    }


}

原木-

共有1个答案

韩照
2023-03-14

我在类路径中手动添加了jjwt jar并且它有效。Tomcat无法从WEB-INF/lib中找到jar,因此必须在类路径中手动添加。

在类路径-文件(菜单)中添加jar的步骤

 类似资料:
  • 当我在iReport 5.1.0中预览JasperReports的报告时,它执行得很好。它包含一个饼图,当我需要从jsp文件运行它时,问题就来了。 烧烤-1.5-beta1.jar commons-beanutils-1.8.2.jar Commons-Collections-3.2.1.jar commons-digester-2.1.jar commons-javaflow-20060411.

  • 问题内容: 是我自己的一类。该类与主类位于同一JAR文件中。因此,这不应该是因为classpath中缺少任何JAR。 当我通过查阅JAR文件时,可以看到其中列出的内容。 顺便说一句:代码在我的本地计算机上运行良好。但是当我将其与某些脚本一起部署到Linux服务器上时无法工作。所以我认为这不是代码的问题。但是出于某种原因。部署过程很难跟踪。 可能是什么问题呢? 问题答案: 我最好的选择是这里有一个问

  • 问题内容: 我是EJB的新手。我的经理告诉我在测试服务器中部署ejb应用程序进行一些修改。该应用程序已经在我们的生产服务器中运行。但是,当我部署应用程序时,我遇到了异常。 我们正在使用Glassfish应用服务器 堆栈异常跟踪: 当我重新启动服务器时,我得到了这些: 在这里您也可以看到相同的问题 任何人都可以 请 帮我,为什么这个错误即将到来。 这是非常需要的。 谢谢 问题答案: 问题解决了。 实

  • 问题内容: 我在此添加了web.xml的源代码 Hibernate.cfg.xml。我的Web服务项目与Jersey + Hibernate一起使用。 这是HibernateUtil类 这是我添加了Hibernate最新的jar文件的错误。[ hibernate-core-4.3.7.Final.jar ] 请帮我解决这个问题谢谢 问题答案: 初始化失败时可能会发生这种错误。您已经提到您正在使用。

  • 我怎么才能修好这个? 谢了。 pom.xml 更新:通过使用较新版本的Hibernate修复了它。