JWT使用SpringBoot完成Token验证

这篇博客详细介绍了如何利用SpringBoot结合JWT技术进行Token验证。内容涵盖Entity、Dao、Service、Controller的创建和配置,以及拦截器的实现,确保在数据库验证Token的有效性。此外,还提到了pom.xml配置文件的重要作用。
摘要由CSDN通过智能技术生成

Entity、Dao、Service、Controller、application.yml、pom.xml

Entity

在这里插入图片描述

Dao

在这里插入图片描述

Service

在这里插入图片描述

实现接口Impl
在这里插入图片描述

package com.guoxinn.demo.Service.ServiceImpl;

import com.guoxinn.demo.Entity.User;
import com.guoxinn.demo.Service.UserService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
   
    @Override
    public boolean login(User user) {
   
        String username = user.getUsername();
        String password = user.getPassword();
        if(username.equals("king") && password.equals("123")){
   
            return true;
        }
        return false;
    }
    @Override
    public List<User> getList() {
   
        User user1= new User("king1","12345");
        User user2 = new User("king2","12345");
        User user3 = new User("king3","12345");
        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        return list;
    }
}

Controller

在这里插入图片描述

package com.guoxinn.demo.Controller;

import com.guoxinn.demo.Entity.User;
import com.guoxinn.demo.Interce.TokenUtil;
import com.guoxinn.demo.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
Spring Boot可以使用JWT(JSON Web Token)实现Token验证JWT是一种基于JSON的开放标准,用于在各方之间安全地传输信息。它由三部分组成:头部、载荷和签名。 在Spring Boot中,可以使用Spring Security和jjwt库来实现JWT Token验证。首先需要添加依赖: ``` <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> ``` 然后在Spring Security的配置类中添加JWT Token验证的配置: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Autowired private JwtRequestFilter jwtRequestFilter; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // configure AuthenticationManagerBuilder } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable() .authorizeRequests().antMatchers("/authenticate").permitAll(). anyRequest().authenticated().and(). exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 其中,JwtAuthenticationEntryPoint是一个自定义的认证入口,用于处理未经授权的请求;JwtRequestFilter是一个自定义的过滤器,用于从请求中提取JWT Token并进行验证。 最后,需要实现一个JwtTokenUtil类,用于生成和验证JWT Token: ``` @Component public class JwtTokenUtil { private String secret = "mySecret"; public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return doGenerateToken(claims, userDetails.getUsername()); } private String doGenerateToken(Map<String, Object> claims, String subject) { long expirationTime = 1000 * 60 * 60 * 10; // 10 hours Date now = new Date(); Date expirationDate = new Date(now.getTime() + expirationTime); return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(now) .setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact(); } public boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } private boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } private Date getExpirationDateFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getExpiration(); } private String getUsernameFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject(); } } ``` 这个类中,generateToken方法用于生成JWT Token,validateToken方法用于验证JWT Token是否有效。在生成JWT Token时,需要设置过期时间和签名算法。在验证JWT Token时,需要验证签名和过期时间。 这样就可以使用Spring Boot实现JWT Token验证了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值