Kerby82
Kerby82

Reputation: 5146

Add authenticated user id by filter to java servlet

I have an authentication filter that authorize REST call by JWT Token. I already implemented the authentication through JWT and the JWT validation by a Filter. How can I pass the user id coming from the JWT to the servlet in the filter process?

Upvotes: 0

Views: 952

Answers (1)

egerardus
egerardus

Reputation: 11486

Usually this is done with an HttpServletRequestWrapper. It's an object that allows you to add or override methods on the standard HttpServletRequest.

Within your filter, wrap the original HttpServletRequest with your own RequestWrapper and then send your RequestWrapper to the servlet instead of the original HttpServletRequest.

For example, here's a simple RequestWrapper to pass an authenticated userId:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class AuthenticatedRequest extends HttpServletRequestWrapper {

    private int userId;

    public AuthenticatedRequest(HttpServletRequest req, int userId) {
        super(req);
        this.userId = userId;
    }

    public int getUserId() {
        return userId;
    }

}

Wrap the original request in your authentication filter before forwarding to your servlet chain:

// in filter class
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
    throws ServletException {

    int userId;

    // do something to get your authentication data (userId)
    // ...
    // wrap the original request with the "AuthenticatedRequest" 
    AuthenticatedRequest authRequest = new AuthenticatedRequest(req, userId);

    // forward the AuthenticatedRequest to the servlet
    chain.doFilter(authRequest, res);

}

The Servlet can then use your new wrapped request methods to access the auth data:

// in servlet class
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException
{
    // this request object is actually your own AuthenticatedRequest wrapper
    int userId = req.getUserId();

This and this cover some more implementation details.

Upvotes: 2

Related Questions