2016년 9월 2일 금요일

Returnning fail response in zuul filter

You can return the fail response by using zuul filter like below.

- TokenCheckFilter.java

package org.blog.test.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class TokenCheckFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 8;
    }

    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String tokenHeader = ctx.getRequest().getHeader("X-IOT-TOKEN");
        if (tokenHeader == null) {
            return true;
        }
        return false;
    }

    public Object run() {
        sendFailedResponse("fail", 401);
        return null;
    }

    private void sendFailedResponse(String body, int code) {
        log.debug("Reporting error (" + code + "): " + body);
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.setResponseStatusCode(code);
        if (ctx.getResponseBody() == null) {
            ctx.setResponseBody(body);
            ctx.setSendZuulResponse(false);
        }
    }

}

댓글 없음 :

댓글 쓰기