04 sentinel authorization rules

Authorization rules

Authorization rules can judge and control the source of the requester.

Authorization rules

Basic rules

Authorization rules can control the source of the caller in two ways: white list and blacklist.

  • White list: callers whose source is in the white list are allowed to access

  • Blacklist: callers whose origin is in the blacklist are not allowed to access

Click authorization in the left menu to see the authorization rules:

  • Resource Name: the protected resource, for example, / order/{orderId}

  • Flow control application: it is the list of sources,

    • If the white list is checked, the sources in the list are allowed to access.
    • If the blacklist is checked, the sources in the list are prohibited from accessing.

If we allow the request to go from the gateway to the order service and do not allow the browser to access the order service, then the source name of the gateway should be filled in the white list.

How to get origin

Sentinel obtains the source of the request through the parseOrigin of the requestorigparser interface.

public interface RequestOriginParser {
    /**
     * Get the origin from the request object. The method of obtaining is customized
     */
    String parseOrigin(HttpServletRequest request);
}

The function of this method is to get the origin value of the requester from the request object and return it.

By default, no matter where the requester comes from, the return value of sentinel is always default, that is, the source of all requests is considered to be the same value default.

Therefore, we need to customize the implementation of this interface to allow different requests to return different origin s.

Example - implement RequestOriginParser to return origin

Add the following code to the service Caller:

@Component
public class HeaderOriginParser implements RequestOriginParser {
    @Override
    public String parseOrigin(HttpServletRequest request) {
        // 1. Get request header
        String origin = request.getHeader("origin");
        // 2. Non empty judgment
        if (StringUtils.isEmpty(origin)) {
            origin = "blank";
        }
        return origin;
    }
}

Example - adding a request header to a gateway

Since the way to obtain the request origin is to obtain the origin value from the requests header, we must make all requests routed from the gateway to the microservice carry the origin header.

This needs to be implemented using GatewayFilter, AddRequestHeaderGatewayFilter.

Modify the application. In the gateway service YML, add a defaultFilter:

spring:
  cloud:
    gateway:
      default-filters:
        - AddRequestHeader=origin,gateway
      routes:
       # ... slightly

In this way, all requests routed from the gateway will carry the origin header with the value of gateway. Requests from other places to microservices do not have this header.

Example - configure authorization rules

Release the request whose origin value is gateway.

Now, let's skip the gateway and access the service:

Access via gateway:

Custom exception results

By default, exceptions will be thrown to the caller when current limiting, degradation and authorization interception occur. Abnormal results are flow limiting. This is not friendly enough. We can't know whether to limit current, downgrade or authorize interception.

Exception type

If you want to customize the return result of exceptions, you need to implement the BlockExceptionHandler interface:

public interface BlockExceptionHandler {
    /**
     * Exception thrown when processing requests that are restricted, degraded, or intercepted by authorization: BlockException
     */
    void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception;
}

This method has three parameters:

  • HttpServletRequest request: request object
  • Httpservletresponse: response object
  • BlockException e: exception thrown when intercepted by sentinel

BlockException here contains several different subclasses:

abnormalexplain
FlowExceptionAbnormal current limit
ParamFlowExceptionAbnormality of hot spot parameter current limiting
DegradeExceptionDegradation exception
AuthorityExceptionAuthorization rule exception
SystemBlockExceptionSystem rule exception

Custom exception handling

Customize Sentinel exception handling class on the service Caller:

@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String msg = "Unknown exception";
        int status = 429;

        if (e instanceof FlowException) {
            msg = "The request is restricted";
        } else if (e instanceof ParamFlowException) {
            msg = "The request is limited by hotspot parameters";
        } else if (e instanceof DegradeException) {
            msg = "The request has been downgraded";
        } else if (e instanceof AuthorityException) {
            msg = "No access";
            status = 401;
        }

        response.setContentType("application/json;charset=utf-8");
        response.setStatus(status);
        response.getWriter().println("{\"msg\": " + msg + ", \"status\": " + status + "}");
    }
}

Keywords: Java http

Added by smarthouseguy on Sun, 20 Feb 2022 11:19:52 +0200