I have implemented JWT token security in spring boot code. how will I get jwt token anywhere in my code? need to save audit

Viewed 233

I have implemented jwt security token in spring boot by refering jwt security impemented videos. So after login I get generated jwt token, For further end points to hit I need to pass jwt token from request header then re request will get authorize at dofilter() method in JwtAuthenticationTokenFilter class as shown below.

public class JwtAuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String username = null;
        String authToken = null;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String header = httpRequest.getHeader(this.tokenHeader);
        if (header != null && header.startsWith("Bearer ")) {
            authToken = header.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
            } catch (IllegalArgumentException e) {
                System.out.println("Unable to get JWT Token");
            } catch (ExpiredJwtException e) {
                System.out.println("JWT Token has expired");
            }
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        chain.doFilter(request, response);
    }
}

But I need to get that jwt token anywhere i want in my code to get some data from token. for example look below code

public static AuditDetails createAudit() {
        AuditDetails auditDetails = new AuditDetails();
        **auditDetails.setCreateUser(token.getUsername());**
        auditDetails.setCreateTime(new Date()); 
        return auditDetails;
    }

so basically i need to get username from token to same audit details, but how am i suppose get token in that code or anywhere in the code?

1 Answers

The token is sent to your app via the header (tokenHeader)

Edit
If you do not want to use the content of your HttpServletRequest anywhere, you can use as per session, a value holder that you can Inject (autowire) in every service to utilize the submitted token. You can try the following

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyHolder {
    private String authToken;

    public String getAuthToken() {
        return authToken;
    }

    public void setAuthToken(String authToken) {
        this.authToken = authToken;
    }
}

Change the token value in your JwtAuthenticationTokenFilter

    @Autowired MyHolder myHolder;
    
    // ...

    String authToken = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String header = httpRequest.getHeader(this.tokenHeader);
    if (header != null && header.startsWith("Bearer ")) {
        authToken = header.substring(7); // Here is your token
        
        // UPDATE THE TOKEN VALUE IN YOUR HOLDER HERE
        myHolder.setAuthToken(authToken);

        // ... 
    }

Access the token anywhere in your app by autowiring the MyHolder class

@Autowired MyHolder myHolder;

// ...
var token = myHolder.getAuthToken();
Related