JWT的Spring Boot会话管理



在这种情况下你能帮我吗?我正在开发一个移动应用程序,其中会话不在春季启动服务器端维护。因此,我使用JWT,客户在每次请求时都会发送JWT。

客户端应用程序正在逐页(逐请求(向服务器发送数据和令牌。服务器需要临时存储此数据,并等待响应数据到达。它必须将所有数据存储在数据库中,否则什么都不存储。

通常,对于传统的web应用程序,这可以通过会话实现。我在会话中尝试过,但没有得到维护。但是,当来自Postman的请求时,会话将得到维护。客户端应用程序在8000端口上运行,而服务器在8443 SSL端口上运行。有一点是明确的,服务器认为来自同一客户端的每个请求都是匿名的,尽管它确实会在每个请求中接收一个令牌。

SecurityConfigurer.java

@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter{
@Autowired
private MyUserDetailsService userDetailsService;

@Autowired
private JwtRequestFilter jwtRequestFilter;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors().and()
.authorizeRequests().antMatchers("/authenticate").permitAll()
.anyRequest().authenticated()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}


@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
// TODO Auto-generated method stub
return super.authenticationManagerBean();
}

}



JwtRequestFilter.java

@Component
public class JwtRequestFilter extends OncePerRequestFilter {
@Autowired
private MyUserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age",
"3600");

filterChain.doFilter(request, response);
}
}

QuizController.java

@CrossOrigin("*")
@RestController
public class QuizController {
@Autowired
private QuizRepository service;
@Autowired
private QuizSummaryRespository summaryService;
@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private MyUserDetailsService userDetailsService;

@Autowired
private JwtUtil jwtTokenUtil;
@SuppressWarnings("unchecked")
@ResponseBody
@PostMapping("/quiz")
public ResponseEntity<?> saveQuiz(Quiz quiz, @RequestParam String status, @RequestParam long time,
HttpServletRequest request, HttpServletResponse response, @RequestHeader Map<String, String> headers) {

Map<String, String> map = new HashMap<>();
List<Quiz> myQuizzes = (List<Quiz>) request.getSession().getAttribute("code"); //This line always return null list
if (quiz.getCode().equals("")) {
quiz.setCode(Utility.generateCode());
myQuizzes = new ArrayList<>();
}
myQuizzes.add(quiz);
request.getSession().setAttribute("code", myQuizzes);
map.put("code", quiz.getCode());
return ResponseEntity.ok(map);
}
}

好的,我可以想出几种方法来解决这个问题。

第一种方法

在前端中,将以前的所有响应存储在sessionStorage或localStorage中,并在完成后立即发送。

第二种方法

在第一次请求期间,在后端存储具有唯一id的响应,并向客户端发送唯一id。在随后的每个请求中,客户端都需要发送带有订单和响应的唯一id。完成后,获取所有响应并按顺序合并它们。您可以在这里使用任何类型的存储,数据库、缓存或纯数组。满足您需求的任何东西。

相关内容

  • 没有找到相关文章

最新更新