Restful API Interface Security Design

Posted by OM2 on Sat, 28 Mar 2020 09:05:09 +0100

1.API Interface Design Specification

https://github.com/mishe/blog/issues/129

2. Security Design

  • a. Whitelist restrictions

Accept only the request response from a specific system, the caller's IP address needs to be reported in the system, otherwise it cannot be invoked

  • b. Validation of legitimate identity

Basic Authentication: This is done by placing the username and password directly in the Header, using Authorization: Basic Zm9vOmJhcg==, which is the simplest but least secure.

TOKEN authentication: This method is also used in HTTP headers, using Authorization: Bearer <token>, the most widely used TOKEN is JWT, with a signed TOKEN.

Json web token (JWT) is a JSON-based open standard ((RFC 7519)) implemented to deliver declarations between network application environments. The token is designed to be compact and secure, especially for single sign-on (SSO) scenarios in distributed sites.

Similar to JWT, only if the token information is saved in redis after successful login, token validity can be set, or token invalidation can be proactively invalidated, etc., and returned to the user.

Other authentication interfaces must enter token information in the header and validate it.

@Aspect
@Component
public class SecurityAspect {

    @Resource(name = "redisTokenManager")
    private TokenManager tokenManager;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void controllerAspect() {

    }
    /**
     * Execute when client request is received
     * 
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("controllerAspect()")
    public Object execute(ProceedingJoinPoint pjp) throws Throwable {
	// Target method from tangent point
	MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
	Method method = methodSignature.getMethod();
	/**
	 * Verify Token
	 */
	if (method.isAnnotationPresent(TokenSecurity.class)) {
	    // Get the current token from the request header
	    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
		    .getRequest();
	    String token = request.getHeader(Constant.DEFAULT_TOKEN_NAME);
	    if (StringUtils.isEmpty(token)) {
		throw new TokenException("Client X-Token Parameter cannot be empty,And from Header Intermediate Incoming,If you are not logged in,Please login first to get Token");
	    }
	    // Check token validity
	    if (!tokenManager.checkToken(token)) {
		String message = String.format("Token [%s] illegal", token);
		throw new TokenException(message);
	    }
	}

	// Call target method
	return pjp.proceed();
    }
}




OAuth2.0: This approach has the highest level of security, -but it is also the most complex.If it's not a large API platform or needs to be used by third-party APP s, there's no need to be as complex as that.

  • c. Flow control can use the corresponding RateLimiter module function in Guava, or can be designed by itself with Redis efficient response mechanism. Set the upper limit of interface call with caller id+interface name KEY, and update the data increment in real time on a daily basis.

Flow Limiting Control: Request frequency restriction mainly used for services to avoid service crashing or application runaway problems due to oversized call backups due to service throughput.Single-machine version current limiting and distributed current limiting are currently available.In short, with flow-limiting control, we can control the granularity at the method level to receive up to XXX calls in XXX seconds.

Concurrency control: Similar to flow-limiting control, concurrency control emphasizes concurrency amount more.This function ensures the concurrency control of the service at any time.Concurrent control is currently available in both single-machine and distributed versions.In short, with concurrency control, we can control granularity at the method level to a service for up to XXX requests being invoked at the same time.

Reference: https://github.com/cpthack/java-rate-limiter

Topics: Programming github JSON Redis network