|
1 | 1 | package com.example.polls.security;
|
2 | 2 |
|
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
3 | 5 | import org.springframework.beans.factory.annotation.Autowired;
|
4 | 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
5 | 7 | import org.springframework.security.core.context.SecurityContextHolder;
|
|
20 | 22 | public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
21 | 23 |
|
22 | 24 | @Autowired
|
23 |
| - JwtTokenProvider tokenProvider; |
| 25 | + private JwtTokenProvider tokenProvider; |
24 | 26 |
|
25 | 27 | @Autowired
|
26 |
| - CustomUserDetailsService customUserDetailsService; |
| 28 | + private CustomUserDetailsService customUserDetailsService; |
| 29 | + |
| 30 | + private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class); |
27 | 31 |
|
28 | 32 | @Override
|
29 | 33 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
30 |
| - String jwt = getJwtFromRequest(request); |
| 34 | + try { |
| 35 | + String jwt = getJwtFromRequest(request); |
31 | 36 |
|
32 |
| - if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { |
33 |
| - Long userId = tokenProvider.getUserIdFromJWT(jwt); |
| 37 | + if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { |
| 38 | + Long userId = tokenProvider.getUserIdFromJWT(jwt); |
34 | 39 |
|
35 |
| - UserDetails userDetails = customUserDetailsService.loadUserById(userId); |
36 |
| - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); |
37 |
| - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); |
| 40 | + UserDetails userDetails = customUserDetailsService.loadUserById(userId); |
| 41 | + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); |
| 42 | + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); |
38 | 43 |
|
39 |
| - SecurityContextHolder.getContext().setAuthentication(authentication); |
| 44 | + SecurityContextHolder.getContext().setAuthentication(authentication); |
| 45 | + } |
| 46 | + } catch (Exception ex) { |
| 47 | + logger.error("Could not set user authentication in security context", ex); |
40 | 48 | }
|
41 | 49 |
|
42 | 50 | filterChain.doFilter(request, response);
|
|
0 commit comments