|
| 1 | +package com.sba.recordingserver.security; |
| 2 | + |
| 3 | +import lombok.extern.slf4j.Slf4j; |
| 4 | +import org.springframework.beans.factory.annotation.Autowired; |
| 5 | +import org.springframework.security.authentication.AbstractAuthenticationToken; |
| 6 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 7 | +import org.springframework.security.core.authority.AuthorityUtils; |
| 8 | +import org.springframework.security.core.context.SecurityContext; |
| 9 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 10 | +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; |
| 11 | +import org.springframework.stereotype.Component; |
| 12 | +import org.springframework.util.StringUtils; |
| 13 | +import org.springframework.web.filter.OncePerRequestFilter; |
| 14 | + |
| 15 | +import javax.servlet.FilterChain; |
| 16 | +import javax.servlet.ServletException; |
| 17 | +import javax.servlet.http.HttpServletRequest; |
| 18 | +import javax.servlet.http.HttpServletResponse; |
| 19 | +import java.io.IOException; |
| 20 | + |
| 21 | +@Slf4j |
| 22 | +@Component |
| 23 | +public class JwtAuthenticationFilter extends OncePerRequestFilter { |
| 24 | + @Autowired |
| 25 | + private TokenProvider tokenProvider; |
| 26 | + @Override |
| 27 | + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { |
| 28 | + try { |
| 29 | + String token = parseBearerToken(request); |
| 30 | + System.out.println("parsing"); |
| 31 | + if(token != null && !token.equalsIgnoreCase(null)) { |
| 32 | + String userId = tokenProvider.validateAndGetUserId(token); |
| 33 | + System.out.println(userId); |
| 34 | + AbstractAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userId,null, AuthorityUtils.NO_AUTHORITIES); |
| 35 | + authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); |
| 36 | + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); |
| 37 | + securityContext.setAuthentication(authenticationToken); |
| 38 | + SecurityContextHolder.setContext(securityContext); |
| 39 | + } |
| 40 | + } catch(Exception e) { |
| 41 | + e.printStackTrace(); |
| 42 | + } |
| 43 | + filterChain.doFilter(request,response); |
| 44 | + } |
| 45 | + |
| 46 | + private String parseBearerToken(HttpServletRequest request) { |
| 47 | + String bearerToken = request.getHeader("Authorization"); |
| 48 | + if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer")) { |
| 49 | + return bearerToken.substring(7); |
| 50 | + } |
| 51 | + else |
| 52 | + return null; |
| 53 | + } |
| 54 | +} |
0 commit comments