【SpringBoot篇】登录校验 — JWT令牌
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
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.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
@RestController
public class AuthController {
// 假设已经有了 AuthenticationManager 的实现
private final AuthenticationManager authenticationManager;
public AuthController(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@PostMapping("/login")
public void login(@RequestBody LoginRequest request, HttpServletResponse response) throws AuthenticationException {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getUsername(),
request.getPassword()
)
);
// 生成令牌
String token = Jwts.builder()
.setSubject(authentication.getName())
.setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000)) // 1 hour
.signWith(SignatureAlgorithm.HS512, "YourSecretKey")
.compact();
// 将令牌添加到响应头
response.addHeader("Authorization", "Bearer " + token);
}
// 登录请求的数据模型
static class LoginRequest {
private String username;
private String password;
// getters and setters
}
}
这个简单的例子展示了如何在Spring Boot应用中使用JWT生成令牌并将其添加到HTTP响应头中。在实际应用中,你需要有一个有效的AuthenticationManager
实现,并且要确保密钥是安全的。
评论已关闭