SpringBoot集成token验证

下面我们说一下SpringBoot如何集成token验证

1、向pom文件引入依赖

 		<dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

2、工具类编写

package com.pro.work.sweet.utils;


import com.alibaba.fastjson.JSON;
import com.pro.work.sweet.entity.TokenInfo;
import com.pro.work.sweet.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class TokenUtil {
    @Autowired
    private RedisUtil redisUtil ;
    /**
     * 签名秘钥,可以换成 秘钥 注入
     */
    public static final String SECRET = "test";//注意:本参数需要长一点,不然后面剪切的时候很可能长度为0,就会报错
    /**
     * 签发地
     */
    public static final String issuer = "com.pro.work.sweet";
    /**
     * 过期时间
     */
    public static final long ttlMillis = 3600*1000*60;

    /**
     * 生成token
     *
     * @return
     */
    public static String createJwtToken(String subject,User user) {
        return createJwtToken( issuer, subject, ttlMillis,user);
    }
    public static String createJwtToken(User user) {
        return createJwtToken( issuer, "", ttlMillis,user);
    }

    /**
     * 生成Token
     * @param issuer  该JWT的签发者,是否使用是可选的
     * @param subject  该JWT所面向的用户,是否使用是可选的;
     * @param ttlMillis 签发时间 (有效时间,过期会报错)
     * @return token String
     */
    public static String createJwtToken(String issuer, String subject, long ttlMillis,User user) {

        // 签名算法 ,将对token进行签名
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        // 生成签发时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 通过秘钥签名JWT
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        String str=signatureAlgorithm.getJcaName();
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, str);

        // 让我们设置JWT声明
        if(null != user){
            JwtBuilder builder = Jwts.builder().setId(user.getIntId())
                    .setIssuedAt(now)
                    .setSubject(subject)
                    .setIssuer(issuer)
                    .signWith(signatureAlgorithm, signingKey);
            // if it has been specified, let's add the expiration
            if (ttlMillis >= 0) {
                //过期时间
                long expMillis = nowMillis + ttlMillis;
                Date exp = new Date(expMillis);
                builder.setExpiration(exp);
            }

            // 构建JWT并将其序列化为一个紧凑的url安全字符串
            return builder.compact();
        }else{
            return null ;
        }
    }

    /**
     * Token解析方法
     * @param jwt Token
     * @return
     */
    public static Claims parseJWT(String jwt) {
        // 如果这行代码不是签名的JWS(如预期),那么它将抛出异常
        Claims claims  = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
                    .parseClaimsJws(jwt).getBody();
        return claims;
    }

    @SneakyThrows
    public void checkTokenIsLev(String token){
        Claims claims = parseJWT(token) ;
        if(!token.equals(JSON.parseObject(String.valueOf(redisUtil.get(claims.getId())), TokenInfo.class).getToken())){
            throw new Exception("您已离线,请重新登录") ;
        }
    }

}

我的 token工具类主要是契合redis进行登录验证,所以契合了user这个对象进来,大家使用的时候如果不必要的话可以去掉,并不难

下面是我写的controller验证类,需要的可以看一下,不过我建议还是按自己的逻辑写好一些

package com.pro.work.sweet.controller;

import com.alibaba.fastjson.JSON;
import com.pro.work.sweet.entity.TokenInfo;
import com.pro.work.sweet.entity.User;
import com.pro.work.sweet.service.UserService;
import com.pro.work.sweet.utils.RedisUtil;
import com.pro.work.sweet.utils.ResponseMessage;
import com.pro.work.sweet.utils.TokenUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/token")
public class TokenController {
    @Autowired
    private UserService userService ;
    @Autowired
    private RedisUtil redisUtil ;
    @SneakyThrows
    @PostMapping("/login")
    public ResponseMessage loginAndSetToken(@RequestBody User user){
        User loginUser = userService.login(user) ;
        TokenInfo tokenInfo = new TokenInfo() ;
        try {
            tokenInfo.setToken(TokenUtil.createJwtToken(loginUser));
        }catch (Exception e){
            throw new Exception("生成token失败,请重新登录") ;
        }
        tokenInfo.setUser(loginUser);
        // 向redis中存储用户信息和对应的Token
        redisUtil.set(loginUser.getIntId(),JSON.toJSONString(tokenInfo),3600*1000*60) ;
        return ResponseMessage.success(tokenInfo) ;
    }

    @SneakyThrows
    @PostMapping("/checkToken")
    public ResponseMessage checkToken(@RequestBody TokenInfo tokenInfo){
        TokenInfo tokenInfoForRedis = JSON.parseObject(String.valueOf(redisUtil.get(TokenUtil.parseJWT(tokenInfo.getToken()).getId())),TokenInfo.class) ;
        TokenInfo tokens = new TokenInfo() ;
        if(tokenInfoForRedis != null){
            tokens.setUser(tokenInfoForRedis.getUser());
            tokens.setToken(tokenInfo.getToken());
            return ResponseMessage.success(tokens) ;
        }else{
            throw new Exception("您已离线,请重新登录") ;
        }
    }
}

至此,后台的token集成完毕

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的 SpringBoot 集成 token 的 Java 代码示例: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Bean public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception { return new JwtAuthenticationFilter(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } @Bean(BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .and() .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/auth/**") .permitAll() .anyRequest() .authenticated(); // 添加 JWT filter http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); } } ``` 这段代码使用了 Spring Security 和 JWT 实现了 token 认证。其中,`JwtAuthenticationFilter` 是一个自定义的过滤器,用于解析和验证 JWT token。在 `configure` 方法中,我们配置了哪些请求需要认证,哪些请求不需要认证。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值