简体   繁体   中英

Simple REST endpoints authentication

I am learning how secure my endpoints, but everything i searched for contains pretty complicated examples, that didn't really answerd my question, and for now, just for the sake of this example project, i was looking for something simple.

My current solution is to make endpoints return like this:

return authenticate(request.headers) ? cityService.getCity() : utils.unauthenticatedResponse();

Where authenticate(request.headers) checks for token in header. The thing i want to improve is to have that authenticate method run before every request to my endpoints (aside from login and register), so i can just return cityService.getCity(), and i won't have to make that check every time.

Will appreciate every answers, but please make it easy yo understand, since i am just a beginner.

Since you need to run the authenticate method before every request, you need to implement a Filter . It's pretty straightforward and you can get the steps and template to implement a filter here .

Every request to an endpoint will first pass through the filter (this is configurable), where you can have the authenticate method and then allow it further accordingly.

For starters, you can implement a filter like below:

@Component
public class AuthFilter implements Filter {

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

        HttpServletRequest req = (HttpServletRequest) request;
        if(authenticate(req.getHeaders)){
            chain.doFilter(request, response);
        } else {
            //else logic, ie throw some exception in case authenticate returns false
        }
    }

}

The advantages that this provides are :

  • You can implement multiple filters
  • You can provide Order/priority to filters
  • You can configure which endpoints need to pass through the filter and which ones do not.

You can use ContainerRequestFilter (if you are using Spring/Tomcat)

Every request coming to the server will go through this filter, so you can implement your code in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM