spring boot增加JWT验证并在springdoc中自动添加token
在Spring Boot中增加JWT验证并在SpringDoc中自动添加token,你可以使用Spring Security和SpringDoc的集成。以下是一个简化的解决方案:
- 添加依赖:
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- SpringDoc -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.6</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
- 配置Security和JWT:
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
@Service
public class JwtTokenService {
public String generateToken(Authentication authentication) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
return Jwts.builder()
.signWith(SignatureAlgorithm.HS512, "YourSecretKey")
.setExpiration(new Date(System.currentTimeMillis() + 864000000))
.claim("username", userDetails.getUsername())
.compact();
}
}
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private final JwtTokenService jwtTokenService;
public JwtAuthenticationSuccessHandler(JwtTokenService jwtTokenService) {
this.jwtTokenService = jwtTokenService;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String token = jwtTokenService.generateToken(authentication);
response.addHeader("Authorization", "Bearer " + token);
response.setStatus(HttpServletResp
评论已关闭