Authorize requests using tokens stored in database

47 Views Asked by At

I am try to implement authentication filter in spring project. I have tokens stored for customers in database. Currently the authorization happens separately in each API. Here is the current version of the api:

@CrossOrigin
@RequestMapping(value="/thirdParty", method=RequestMethod.GET)
private void getThirdPartyOffers(HttpServletRequest request, HttpServletResponse response){
    response.setHeader("Access-Control-Allow-Origin", "*");

    String authToken = request.getHeader(AUTHORIZATION);
    if (null != authToken) {
      Customer customer = getCustomer(authToken, sessionFactory);
      if (null != customer) {
            JsonObject responseObject = new JsonObject();
            Integer cityId=-1;
            
            if(customer.getDeliveryAddress()!=null &&customer.getDeliveryAddress().getCity()!=null){
                cityId=customer.getDeliveryAddress().getCity().getId();
            }else if(customer.getLocality()!=null){
                cityId= customer.getLocality().getCity().getId(); 
            }else if(customer.getArea()!=null){
                cityId= customer.getArea().getCity().getId();
            }
            
            JsonArray offers = promotionOfferUtils.getThirdPartyOfferList(customer, cityId);
            responseObject.add("offers", offers);
            responseObject.addProperty(ERROR, false);
            sendResponse(response,HttpServletResponse.SC_OK,responseObject);
            return;
      }else{
          sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR,
                  AUTHORIZATION_FAILED);
      }
    }else {
        sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR,
                AUTHORIZATION_FAILED);
    }
}

The final api should be like this:

    @CrossOrigin
@RequestMapping(value = "/thirdParty", method = RequestMethod.GET)
private void getThirdPartyOffers(HttpServletRequest request, HttpServletResponse response) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    String customerId = response.getHeader("customerId");
    Customer customer = getCustomer(sessionFactory, customerId);

    JsonObject responseObject = new JsonObject();
    Integer cityId = -1;

    if (customer.getDeliveryAddress() != null && customer.getDeliveryAddress().getCity() != null) {
        cityId = customer.getDeliveryAddress().getCity().getId();
    } else if (customer.getLocality() != null) {
        cityId = customer.getLocality().getCity().getId();
    } else if (customer.getArea() != null) {
        cityId = customer.getArea().getCity().getId();
    }

    JsonArray offers = promotionOfferUtils.getThirdPartyOfferList(customer, cityId);
    responseObject.add("offers", offers);
    responseObject.addProperty(ERROR, false);
    sendResponse(response, HttpServletResponse.SC_OK, responseObject);
    return;

}

I am now trying to authenticate using a filter.Here I have created the required filter.

 @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // invoked when a matching request sent to the server
    // used to intercept the request and transform the response

     
     HttpServletRequest httpRequest = (HttpServletRequest) request;
     HttpServletResponse httpResponse = (HttpServletResponse) response;
     
     httpResponse.setHeader("Access-Control-Allow-Headers", "origin, content-type, Authorization, accept, x-requested-with, IS_UPDATED");
     httpResponse.setHeader("Access-Control-Max-Age", "60"); // seconds to cache preflight request --> less OPTIONS traffic
     httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
     httpResponse.setHeader("Access-Control-Allow-Origin", "*");

    Customer customer;
     try
     {
         if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {

             httpResponse.setStatus(HttpServletResponse.SC_OK);
             return;
         } else {
            String url = ((HttpServletRequest) request).getRequestURL().toString();
            String endUrlPath = url.split("/").length > 1 ? url.split("/")[url.split("/").length - 1] : "";
            if (!endUrlPath.equalsIgnoreCase("login") && !endUrlPath.equalsIgnoreCase("forgotPasswordSendOtp") &&
                    !endUrlPath.equalsIgnoreCase("changePasswordInForgotPassword") && !endUrlPath.equalsIgnoreCase("verifyUserOTP")) {
                String authToken = httpRequest.getHeader("Authorization");

                customer = getCustomer(authToken,sessionFactory);
                if (customer == null) {
                    httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                httpResponse.addHeader("customerId", Integer.toString(customer.getId()));       
                
            }
        }

     } catch (Exception ex) {
         httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
         return;
    }

    chain.doFilter(request, response);// invokes next filter in the chain
   
}

The problem now is that the sessionFactory object is null at this point and I am unable to access database to get the customer. I am unable to figure out how to get access to sessionFactory when the startup is incomplete?

0

There are 0 best solutions below