Spring Security实现用户认证四:使用JWT与Redis实现无状态认证
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private final JwtTokenUtil jwtTokenUtil;
private final StringRedisTemplate stringRedisTemplate;
public JwtAuthenticationSuccessHandler(JwtTokenUtil jwtTokenUtil, StringRedisTemplate stringRedisTemplate) {
this.jwtTokenUtil = jwtTokenUtil;
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String username = authentication.getName();
String token = jwtTokenUtil.generateToken(username);
Map<String, String> tokens = new HashMap<>();
tokens.put("token", token);
// 将token存储到Redis,用于注销操作
stringRedisTemplate.opsForValue().set(username, token);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JSON.toJSONString(tokens));
}
}
这个代码实例修复了之前的错误,并且遵守了最佳实践。它使用了StringRedisTemplate
来存储生成的JWT token,并且正确地设置了响应的内容类型和编码。同时,它使用了JSON.toJSONString
来序列化返回的JSON数据,确保了返回的数据格式正确。
评论已关闭