springboot整合token认证
时间: 2023-07-27 21:03:24 浏览: 58
Spring Boot提供了多种方式来实现Token认证,下面是一种基本的实现方式:
首先,在pom.xml文件中添加Spring Security和JWT依赖:
```xml
<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>
```
接下来,创建一个JWTUtil类,用于生成和解析Token:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class JWTUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
public String generateToken(String username) {
Date now = new Date();
Date expireDate = new Date(now.getTime() + expiration * 1000);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsernameFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
}
public boolean validateToken(String token, String username) {
String tokenUsername = getUsernameFromToken(token);
return tokenUsername.equals(username) && !isTokenExpired(token);
}
private boolean isTokenExpired(String token) {
Date expirationDate = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getExpiration();
return expirationDate.before(new Date());
}
}
```
然后,创建一个JwtAuthenticationFilter类,用于处理Token认证:
```java
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final JWTUtil jwtUtil;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil) {
super(new AntPathRequestMatcher("/api/login", "POST"));
setAuthenticationManager(authenticationManager);
this.jwtUtil = jwtUtil;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String username = request.getParameter("username");
String password = request.getParameter("password");
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(username, password)
);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
String username = ((UserDetails) authResult.getPrincipal()).getUsername();
String token = jwtUtil.generateToken(username);
response.addHeader("Authorization", "Bearer " + token);
}
}
```
最后,在SecurityConfig中配置认证:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private final PasswordEncoder passwordEncoder;
private final JWTUtil jwtUtil;
@Autowired
public SecurityConfig(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder, JWTUtil jwtUtil) {
this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder;
this.jwtUtil = jwtUtil;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/login").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtUtil));
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
```
以上即为使用Spring Boot整合Token认证的基本步骤。首先,在JWTUtil类中实现Token的生成和解析逻辑,然后通过JwtAuthenticationFilter处理请求中的Token,最后在SecurityConfig中配置认证规则。