springboot2.7.6与springsecurity和JWT整合方案
发布人:shili8
发布时间:2025-02-21 23:20
阅读次数:0
**Spring Boot2.7.6 与 Spring Security 和 JWT 整合方案**
在本文中,我们将介绍如何使用 Spring Boot2.7.6、Spring Security 和 JWT 进行整合。我们将一步步地讲解整个过程,包括配置、编码和测试。
**1.依赖项**
首先,我们需要在 `pom.xml` 文件中添加以下依赖项:
xml<dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- JWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-generator</artifactId> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies>
**2. 配置**
接下来,我们需要配置 Spring Security 和 JWT。我们可以在 `application.properties` 文件中添加以下内容:
propertiesspring.security.user.name= adminspring.security.user.password= passwordjwt.secret= secretKeyjwt.expiration=86400 //24小时
**3. 编码**
现在,我们需要编写 Java代码来实现 Spring Security 和 JWT 的整合。我们可以在 `SecurityConfig.java` 文件中添加以下内容:
javaimport org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override protected void configure(HttpSecurity throws Exception {
/> .antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/login")
.defaultSuccessUrl("/")
.and()
.csrf().disable();
}
}
**4. JWT**
接下来,我们需要实现 JWT 的生成和验证。我们可以在 `JwtUtil.java` 文件中添加以下内容:
javaimport io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
public class JwtUtil {
private static final String SECRET = "secretKey";
public static String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() +86400000))
.signWith(SignatureAlgorithm.HS256, SECRET)
.compact();
}
public static Claims getClaimsFromToken(String token) {
try {
return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
} catch (JwtException e) {
return null;
}
}
public static boolean validateToken(String token, String username) {
Claims claims = getClaimsFromToken(token);
if (claims != null && claims.getSubject().equals(username)) {
return true;
}
return false;
}
}
**5. 测试**
最后,我们需要测试我们的 Spring Security 和 JWT 的整合。我们可以在 `LoginController.java` 文件中添加以下内容:
javaimport org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class LoginController {
@Autowired private JwtUtil jwtUtil;
@PostMapping("/login")
public String login(@RequestBody LoginRequest request) {
Authentication authentication = new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());
SecurityContextHolder.getContext().setAuthentication(authentication);
return jwtUtil.generateToken(request.getUsername());
}
}
**6. 测试用例**
我们可以在 `LoginControllerTest.java` 文件中添加以下内容:
javaimport org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class LoginControllerTest {
@Autowired private LoginController loginController;
@Test public void testLogin() {
LoginRequest request = new LoginRequest("admin", "password");
String token = loginController.login(request);
System.out.println(token);
}
}
通过以上步骤,我们可以实现 Spring Boot2.7.6 与 Spring Security 和 JWT 的整合。

