io.jsonwebtoken.SignatureException:JWT 签名与本地计算的签名不匹配

Posted

技术标签:

【中文标题】io.jsonwebtoken.SignatureException:JWT 签名与本地计算的签名不匹配【英文标题】:io.jsonwebtoken.SignatureException: JWT signature does not match locally computed signature 【发布时间】:2021-03-26 03:17:50 【问题描述】:

我在休息服务上使用 Spring Boot 和 Spring Security 以及 JWT。我使用了以下链接中的代码: https://www.javainuse.com/spring/boot-jwt-mysql 它工作正常,但是当我们使用它的令牌进行身份验证时......我们面临以下错误:

。 JWT 有效性不能被断言,也不应该被信任。 在 io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:354) ~[jjwt-0.9.1.jar:0.9.1] 在 io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:481) ~[jjwt-0.9.1.jar:0.9.1] 在 io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:541) ~[jjwt-0.9.1.jar:0.9.1] 在 com.isan.config.JwtTokenUtil.getAllClaimsFromToken(JwtTokenUtil.java:46) ~[classes/:na] 在 com.isan.config.JwtTokenUtil.getClaimFromToken(JwtTokenUtil.java:41) ~[classes/:na] 在 com.isan.config.JwtTokenUtil.getUsernameFromToken(JwtTokenUtil.java:32) ~[classes/:na] 在 com.isan.config.JwtRequestFilter.doFilterInternal(JwtRequestFilter.java:44) ~[classes/:na] 在 org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.1.jar:5.3.1] 在 org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.1.jar:5.4.1] 在 org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.4.1.jar:5.4.1] 在 org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.4.1.jar:5.4.1]

这些是代码:

1-WebSecurityConfig 类:

    @Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter 

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private UserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
        // configure AuthenticationManager so that it knows from where to load
        // user for matching credentials
        // Use BCryptPasswordEncoder
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
    

    @Bean
    public PasswordEncoder passwordEncoder() 
        return new BCryptPasswordEncoder();
    

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception 
        return super.authenticationManagerBean();
    

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception 
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/authenticate", "/register").permitAll().
                // all other requests need to be authenticated
                anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    

2-JwtTokenUtil 类:

@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.getBytes()).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());
    

    //while creating the token -
    //1. Define  claims of the token, like Issuer, Expiration, Subject, and the ID
    //2. Sign the JWT using the HS512 algorithm and secret key.
    //3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1)
    //   compaction of the JWT to a URL-safe string 
    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.getBytes()).compact();
    

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

3-JwtRequestFilter 类:

@Component
public class JwtRequestFilter extends OncePerRequestFilter 

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException 

        final String requestTokenHeader = request.getHeader("Authorization");

        String username = null;
        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get
        // only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) 
            jwtToken = requestTokenHeader.substring(7);
            try 
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
             catch (IllegalArgumentException e) 
                System.out.println("Unable to get JWT Token");
             catch (ExpiredJwtException e) 
                System.out.println("JWT Token has expired");
            
         else 
            logger.warn("JWT Token does not begin with Bearer String");
        

        // Once we get the token validate it.
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) 

            UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);

            // if token is valid configure Spring Security to manually set
            // authentication
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) 

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // After setting the Authentication in the context, we specify
                // that the current user is authenticated. So it passes the
                // Spring Security Configurations successfully.
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            
        
        chain.doFilter(request, response);
    


4-JwtAuthenticationEntryPoint 类:

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable 

    private static final long serialVersionUID = -7858869558953243875L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException 

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    

5-JwtAuthenticationController 类:

@RestController
@CrossOrigin
public class JwtAuthenticationController 

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception 

        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());

        final UserDetails userDetails = userDetailsService
                .loadUserByUsername(authenticationRequest.getUsername());

        final String token = jwtTokenUtil.generateToken(userDetails);

        return ResponseEntity.ok(new JwtResponse(token));
    
    
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseEntity<?> saveUser(@RequestBody UserDTO user) throws Exception 
        return ResponseEntity.ok(userDetailsService.save(user));
    

    private void authenticate(String username, String password) throws Exception 
        try 
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
         catch (DisabledException e) 
            throw new Exception("USER_DISABLED", e);
         catch (BadCredentialsException e) 
            throw new Exception("INVALID_CREDENTIALS", e);
        
    

6-JwtUserDetailsS​​ervice 类:

@Service
public class JwtUserDetailsService implements UserDetailsService 
    
    @Autowired
    private UserDao userDao;

    @Autowired
    private PasswordEncoder bcryptEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 
        DAOUser user = userDao.findByUsername(username);
        if (user == null) 
            throw new UsernameNotFoundException("User not found with username: " + username);
        
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                new ArrayList<>());
    
    
    public DAOUser save(UserDTO user) 
        DAOUser newUser = new DAOUser();
        newUser.setUsername(user.getUsername());
        newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
        return userDao.save(newUser);
    

7- application.properties

jwt.secret=javainuse
spring.datasource.url=jdbc:mysql://localhost/bootdb?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=asdasdasd
spring.datasource.platform=mysql
spring.jpa.hibernate.ddl-auto=create-drop

8-pom.xml

<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.javainuse</groupId>
  <artifactId>spring-boot-jwt</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.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-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        
    </dependencies>

</project>

9-token 示例:

eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzYW0iLCJleHAiOjE2MDgwNjM1NTUsImlhdCI6MTYwODA0NTU1NX0.X77D8mceGbBWRCWUOwhL-5iwpZQqFAITmQqOW_s48vGDkkWdMFg1dm_Gackri8evPVzkF6lt2tXvHCbOlpe86w

10 秘密示例:

javainuse

【问题讨论】:

验证时密钥/密码错误? 感谢您的回答,但当我调试代码时,密钥/秘密是相同的! 好的。我添加代码。感谢您的帮助。 【参考方案1】:

在 JwtTokenUtil 类中,只需更改以下方法:

private Claims getAllClaimsFromToken(String token) 
        return Jwts.parser().setSigningKey(secret.getBytes(Charset.forName("UTF-8"))).parseClaimsJws(token.replace("", "").replace("","")).getBody();
    

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.getBytes(Charset.forName("UTF-8"))).compact();
    

【讨论】:

以上是关于io.jsonwebtoken.SignatureException:JWT 签名与本地计算的签名不匹配的主要内容,如果未能解决你的问题,请参考以下文章