java:JWT的简单例子

【pom.xml】

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.3.12.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>2.3.12.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.19.1</version>
</dependency>

【JwtTest.java】

package com.chz.myJWT.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

public class JwtTest {

    public static final String SECRET = "I_am_chz";

    public static String createJwtToken()
    {
        HashMap<String, Object> headers = new HashMap<>();

        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.MINUTE, 30);       // 过期时间,60s


        String jwtToken = JWT.create()
                // 第一部分Header
                .withHeader(headers)
                // 第二部分Payload
                .withClaim("userId", 20)
                .withClaim("userName", "chz")
                .withExpiresAt(expires.getTime())
                // 第三部分Signature
                .sign(Algorithm.HMAC256(SECRET));
        return jwtToken;
    }

    public static DecodedJWT parseJwtToken(String jwtToken)
    {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(jwtToken);
        return decodedJWT;
    }

    public static void main(String[] args)
    {
        String jwtToken = createJwtToken();
        System.out.println("jwtToken: " + jwtToken);


        DecodedJWT decodedJWT = parseJwtToken(jwtToken);
        System.out.println("userId: " + decodedJWT.getClaim("userId").asInt());
        System.out.println("userName: " + decodedJWT.getClaim("userName").asString());
        System.out.println("expiresAt: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(decodedJWT.getExpiresAt()));
    }
}

运行【JwtTest】
在这里插入图片描述

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的使用Spring Boot和JWT示例: 首先,添加以下依赖项到你的pom.xml文件中: ```xml <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> ``` 接下来,配置JWT的一些属性,例如密钥,过期时间等: ```java @Configuration public class JwtConfig { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private int expiration; public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public int getExpiration() { return expiration; } public void setExpiration(int expiration) { this.expiration = expiration; } } ``` 创建一个过滤器来处理JWT: ```java public class JwtTokenFilter extends OncePerRequestFilter { @Autowired private JwtConfig jwtConfig; @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { try { String jwt = parseJwt(httpServletRequest); if (jwt != null && validateJwtToken(jwt)) { Authentication authentication = getAuthentication(jwt); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception e) { logger.error("Cannot set user authentication: {}", e); } filterChain.doFilter(httpServletRequest, httpServletResponse); } private String parseJwt(HttpServletRequest request) { String headerAuth = request.getHeader("Authorization"); if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) { return headerAuth.substring(7, headerAuth.length()); } return null; } private boolean validateJwtToken(String jwt) { try { Jwts.parser().setSigningKey(jwtConfig.getSecret()).parseClaimsJws(jwt); return true; } catch (SignatureException e) { logger.error("Invalid JWT signature: {}", e.getMessage()); } catch (MalformedJwtException e) { logger.error("Invalid JWT token: {}", e.getMessage()); } catch (ExpiredJwtException e) { logger.error("JWT token is expired: {}", e.getMessage()); } catch (UnsupportedJwtException e) { logger.error("JWT token is unsupported: {}", e.getMessage()); } catch (IllegalArgumentException e) { logger.error("JWT claims string is empty: {}", e.getMessage()); } return false; } private Authentication getAuthentication(String jwt) { Claims claims = Jwts.parser() .setSigningKey(jwtConfig.getSecret()) .parseClaimsJws(jwt) .getBody(); String username = claims.getSubject(); List<String> roles = (List<String>) claims.get("roles"); List<GrantedAuthority> authorities = roles.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); return new UsernamePasswordAuthenticationToken(username, null, authorities); } } ``` 接下来,创建一个JWT生成器: ```java @Service public class JwtUtils { @Autowired private JwtConfig jwtConfig; public String generateJwtToken(Authentication authentication) { UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); return Jwts.builder() .setSubject((userPrincipal.getUsername())) .setIssuedAt(new Date()) .setExpiration(new Date((new Date()).getTime() + jwtConfig.getExpiration() * 1000)) .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret()) .compact(); } } ``` 最后,将JWT过滤器添加到Spring Security配置中: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtTokenFilter jwtTokenFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 这样,你就可以在你的Spring Boot应用中使用JWT进行身份验证了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈鸿圳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值