1 | package finki.diplomska.tripplanner.security;
|
---|
2 |
|
---|
3 | import finki.diplomska.tripplanner.models.User;
|
---|
4 | import finki.diplomska.tripplanner.service.impl.CustomUserDetailsServiceImpl;
|
---|
5 | import org.springframework.beans.factory.annotation.Autowired;
|
---|
6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
---|
7 | import org.springframework.security.core.context.SecurityContextHolder;
|
---|
8 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
---|
9 | import org.springframework.util.StringUtils;
|
---|
10 | import org.springframework.web.filter.OncePerRequestFilter;
|
---|
11 |
|
---|
12 | import javax.servlet.FilterChain;
|
---|
13 | import javax.servlet.ServletException;
|
---|
14 | import javax.servlet.http.HttpServletRequest;
|
---|
15 | import javax.servlet.http.HttpServletResponse;
|
---|
16 | import java.io.IOException;
|
---|
17 | import java.util.Collections;
|
---|
18 |
|
---|
19 | public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
---|
20 | @Autowired
|
---|
21 | private JwtTokenProvider tokenProvider;
|
---|
22 |
|
---|
23 | @Autowired
|
---|
24 | private CustomUserDetailsServiceImpl customUserDetailsService;
|
---|
25 |
|
---|
26 | @Override
|
---|
27 | protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
|
---|
28 | FilterChain filterChain) throws ServletException, IOException {
|
---|
29 |
|
---|
30 | try {
|
---|
31 |
|
---|
32 | String jwt = getJWTFromRequest(httpServletRequest);
|
---|
33 |
|
---|
34 | if(StringUtils.hasText(jwt)&& tokenProvider.validateToken(jwt)){
|
---|
35 | Long userId = tokenProvider.getUserIdFromJWT(jwt);
|
---|
36 | User userDetails = customUserDetailsService.loadUserById(userId);
|
---|
37 |
|
---|
38 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
---|
39 | userDetails, null, Collections.emptyList());
|
---|
40 |
|
---|
41 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
|
---|
42 | SecurityContextHolder.getContext().setAuthentication(authentication);
|
---|
43 |
|
---|
44 | }
|
---|
45 |
|
---|
46 | }catch (Exception ex){
|
---|
47 | logger.error("Could not set user authentication in security context", ex);
|
---|
48 | }
|
---|
49 |
|
---|
50 |
|
---|
51 | filterChain.doFilter(httpServletRequest, httpServletResponse);
|
---|
52 |
|
---|
53 | }
|
---|
54 |
|
---|
55 |
|
---|
56 |
|
---|
57 | private String getJWTFromRequest(HttpServletRequest request){
|
---|
58 | String bearerToken = request.getHeader(SecurityConstants.HEADER_STRING);
|
---|
59 |
|
---|
60 | if(StringUtils.hasText(bearerToken)&&bearerToken.startsWith(SecurityConstants.TOKEN_PREFIX)){
|
---|
61 | return bearerToken.substring(7, bearerToken.length());
|
---|
62 | }
|
---|
63 |
|
---|
64 | return null;
|
---|
65 | }
|
---|
66 | }
|
---|