Search in sources :

Example 6 with Secured

use of com.alibaba.nacos.auth.annotation.Secured in project nacos by alibaba.

the class AuthFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (!authConfigs.isAuthEnabled()) {
        chain.doFilter(request, response);
        return;
    }
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    if (authConfigs.isEnableUserAgentAuthWhite()) {
        String userAgent = WebUtils.getUserAgent(req);
        if (StringUtils.startsWith(userAgent, Constants.NACOS_SERVER_HEADER)) {
            chain.doFilter(request, response);
            return;
        }
    } else if (StringUtils.isNotBlank(authConfigs.getServerIdentityKey()) && StringUtils.isNotBlank(authConfigs.getServerIdentityValue())) {
        String serverIdentity = req.getHeader(authConfigs.getServerIdentityKey());
        if (StringUtils.isNotBlank(serverIdentity)) {
            if (authConfigs.getServerIdentityValue().equals(serverIdentity)) {
                chain.doFilter(request, response);
                return;
            }
            Loggers.AUTH.warn("Invalid server identity value for {} from {}", authConfigs.getServerIdentityKey(), req.getRemoteHost());
        }
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid server identity key or value, Please make sure set `nacos.core.auth.server.identity.key`" + " and `nacos.core.auth.server.identity.value`, or open `nacos.core.auth.enable.userAgentAuthWhite`");
        return;
    }
    try {
        Method method = methodsCache.getMethod(req);
        if (method == null) {
            chain.doFilter(request, response);
            return;
        }
        if (method.isAnnotationPresent(Secured.class) && authConfigs.isAuthEnabled()) {
            if (Loggers.AUTH.isDebugEnabled()) {
                Loggers.AUTH.debug("auth start, request: {} {}", req.getMethod(), req.getRequestURI());
            }
            Secured secured = method.getAnnotation(Secured.class);
            if (!protocolAuthService.enableAuth(secured)) {
                chain.doFilter(request, response);
                return;
            }
            Resource resource = protocolAuthService.parseResource(req, secured);
            IdentityContext identityContext = protocolAuthService.parseIdentity(req);
            boolean result = protocolAuthService.validateIdentity(identityContext, resource);
            if (!result) {
                // TODO Get reason of failure
                throw new AccessException("Validate Identity failed.");
            }
            injectIdentityId(req, identityContext);
            String action = secured.action().toString();
            result = protocolAuthService.validateAuthority(identityContext, new Permission(resource, action));
            if (!result) {
                // TODO Get reason of failure
                throw new AccessException("Validate Authority failed.");
            }
        }
        chain.doFilter(request, response);
    } catch (AccessException e) {
        if (Loggers.AUTH.isDebugEnabled()) {
            Loggers.AUTH.debug("access denied, request: {} {}, reason: {}", req.getMethod(), req.getRequestURI(), e.getErrMsg());
        }
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getErrMsg());
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ExceptionUtil.getAllExceptionMsg(e));
    } catch (Exception e) {
        Loggers.AUTH.warn("[AUTH-FILTER] Server failed: ", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server failed, " + e.getMessage());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessException(com.alibaba.nacos.plugin.auth.exception.AccessException) Secured(com.alibaba.nacos.auth.annotation.Secured) Resource(com.alibaba.nacos.plugin.auth.api.Resource) Permission(com.alibaba.nacos.plugin.auth.api.Permission) HttpServletResponse(javax.servlet.http.HttpServletResponse) IdentityContext(com.alibaba.nacos.plugin.auth.api.IdentityContext) Method(java.lang.reflect.Method) ServletException(javax.servlet.ServletException) AccessException(com.alibaba.nacos.plugin.auth.exception.AccessException) IOException(java.io.IOException)

Example 7 with Secured

use of com.alibaba.nacos.auth.annotation.Secured in project nacos by alibaba.

the class RemoteRequestAuthFilter method filter.

@Override
public Response filter(Request request, RequestMeta meta, Class handlerClazz) throws NacosException {
    try {
        Method method = getHandleMethod(handlerClazz);
        if (method.isAnnotationPresent(Secured.class) && authConfigs.isAuthEnabled()) {
            if (Loggers.AUTH.isDebugEnabled()) {
                Loggers.AUTH.debug("auth start, request: {}", request.getClass().getSimpleName());
            }
            Secured secured = method.getAnnotation(Secured.class);
            if (!protocolAuthService.enableAuth(secured)) {
                return null;
            }
            String clientIp = meta.getClientIp();
            request.putHeader(Constants.Identity.X_REAL_IP, clientIp);
            Resource resource = protocolAuthService.parseResource(request, secured);
            IdentityContext identityContext = protocolAuthService.parseIdentity(request);
            boolean result = protocolAuthService.validateIdentity(identityContext, resource);
            if (!result) {
                // TODO Get reason of failure
                throw new AccessException("Validate Identity failed.");
            }
            String action = secured.action().toString();
            result = protocolAuthService.validateAuthority(identityContext, new Permission(resource, action));
            if (!result) {
                // TODO Get reason of failure
                throw new AccessException("Validate Authority failed.");
            }
        }
    } catch (AccessException e) {
        if (Loggers.AUTH.isDebugEnabled()) {
            Loggers.AUTH.debug("access denied, request: {}, reason: {}", request.getClass().getSimpleName(), e.getErrMsg());
        }
        Response defaultResponseInstance = getDefaultResponseInstance(handlerClazz);
        defaultResponseInstance.setErrorInfo(NacosException.NO_RIGHT, e.getErrMsg());
        return defaultResponseInstance;
    } catch (Exception e) {
        Response defaultResponseInstance = getDefaultResponseInstance(handlerClazz);
        defaultResponseInstance.setErrorInfo(NacosException.SERVER_ERROR, ExceptionUtil.getAllExceptionMsg(e));
        return defaultResponseInstance;
    }
    return null;
}
Also used : Response(com.alibaba.nacos.api.remote.response.Response) AccessException(com.alibaba.nacos.plugin.auth.exception.AccessException) Secured(com.alibaba.nacos.auth.annotation.Secured) Resource(com.alibaba.nacos.plugin.auth.api.Resource) Permission(com.alibaba.nacos.plugin.auth.api.Permission) IdentityContext(com.alibaba.nacos.plugin.auth.api.IdentityContext) Method(java.lang.reflect.Method) AccessException(com.alibaba.nacos.plugin.auth.exception.AccessException) NacosException(com.alibaba.nacos.api.exception.NacosException)

Example 8 with Secured

use of com.alibaba.nacos.auth.annotation.Secured in project nacos by alibaba.

the class ClusterController method update.

/**
 * Update cluster.
 *
 * @param request http request
 * @return 'ok' if success
 * @throws Exception if failed
 */
@PutMapping
@Secured(action = ActionTypes.WRITE)
public String update(HttpServletRequest request) throws Exception {
    final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
    final String clusterName = WebUtils.required(request, CommonParams.CLUSTER_NAME);
    final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
    ClusterMetadata clusterMetadata = new ClusterMetadata();
    clusterMetadata.setHealthyCheckPort(NumberUtils.toInt(WebUtils.required(request, "checkPort")));
    clusterMetadata.setUseInstancePortForCheck(ConvertUtils.toBoolean(WebUtils.required(request, "useInstancePort4Check")));
    AbstractHealthChecker healthChecker = HealthCheckerFactory.deserialize(WebUtils.required(request, "healthChecker"));
    clusterMetadata.setHealthChecker(healthChecker);
    clusterMetadata.setHealthyCheckType(healthChecker.getType());
    clusterMetadata.setExtendData(UtilsAndCommons.parseMetadata(WebUtils.optional(request, "metadata", StringUtils.EMPTY)));
    judgeClusterOperator().updateClusterMetadata(namespaceId, serviceName, clusterName, clusterMetadata);
    return "ok";
}
Also used : ClusterMetadata(com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata) AbstractHealthChecker(com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker) Secured(com.alibaba.nacos.auth.annotation.Secured) PutMapping(org.springframework.web.bind.annotation.PutMapping)

Example 9 with Secured

use of com.alibaba.nacos.auth.annotation.Secured in project nacos by alibaba.

the class InstanceController method detail.

/**
 * Get detail information of specified instance.
 *
 * @param request http request
 * @return detail information of instance
 * @throws Exception any error during get
 */
@GetMapping
@Secured(action = ActionTypes.READ)
public ObjectNode detail(HttpServletRequest request) throws Exception {
    String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
    String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
    NamingUtils.checkServiceNameFormat(serviceName);
    String cluster = WebUtils.optional(request, CommonParams.CLUSTER_NAME, UtilsAndCommons.DEFAULT_CLUSTER_NAME);
    String ip = WebUtils.required(request, "ip");
    int port = Integer.parseInt(WebUtils.required(request, "port"));
    com.alibaba.nacos.api.naming.pojo.Instance instance = getInstanceOperator().getInstance(namespaceId, serviceName, cluster, ip, port);
    ObjectNode result = JacksonUtils.createEmptyJsonNode();
    result.put("service", serviceName);
    result.put("ip", ip);
    result.put("port", port);
    result.put("clusterName", cluster);
    result.put("weight", instance.getWeight());
    result.put("healthy", instance.isHealthy());
    result.put("instanceId", instance.getInstanceId());
    result.set(METADATA, JacksonUtils.transferToJsonNode(instance.getMetadata()));
    return result;
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Instance(com.alibaba.nacos.api.naming.pojo.Instance) GetMapping(org.springframework.web.bind.annotation.GetMapping) Secured(com.alibaba.nacos.auth.annotation.Secured)

Example 10 with Secured

use of com.alibaba.nacos.auth.annotation.Secured in project nacos by alibaba.

the class InstanceController method patch.

/**
 * Patch instance.
 *
 * @param request http request
 * @return 'ok' if success
 * @throws Exception any error during patch
 */
@CanDistro
@PatchMapping
@Secured(action = ActionTypes.WRITE)
public String patch(HttpServletRequest request) throws Exception {
    String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
    NamingUtils.checkServiceNameFormat(serviceName);
    String ip = WebUtils.required(request, "ip");
    String port = WebUtils.required(request, "port");
    String cluster = WebUtils.optional(request, CommonParams.CLUSTER_NAME, StringUtils.EMPTY);
    if (StringUtils.isBlank(cluster)) {
        cluster = WebUtils.optional(request, "cluster", UtilsAndCommons.DEFAULT_CLUSTER_NAME);
    }
    InstancePatchObject patchObject = new InstancePatchObject(cluster, ip, Integer.parseInt(port));
    String metadata = WebUtils.optional(request, METADATA, StringUtils.EMPTY);
    if (StringUtils.isNotBlank(metadata)) {
        patchObject.setMetadata(UtilsAndCommons.parseMetadata(metadata));
    }
    String app = WebUtils.optional(request, "app", StringUtils.EMPTY);
    if (StringUtils.isNotBlank(app)) {
        patchObject.setApp(app);
    }
    String weight = WebUtils.optional(request, "weight", StringUtils.EMPTY);
    if (StringUtils.isNotBlank(weight)) {
        patchObject.setWeight(Double.parseDouble(weight));
    }
    String healthy = WebUtils.optional(request, "healthy", StringUtils.EMPTY);
    if (StringUtils.isNotBlank(healthy)) {
        patchObject.setHealthy(ConvertUtils.toBoolean(healthy));
    }
    String enabledString = WebUtils.optional(request, "enabled", StringUtils.EMPTY);
    if (StringUtils.isNotBlank(enabledString)) {
        patchObject.setEnabled(ConvertUtils.toBoolean(enabledString));
    }
    String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
    getInstanceOperator().patchInstance(namespaceId, serviceName, patchObject);
    return "ok";
}
Also used : InstancePatchObject(com.alibaba.nacos.naming.core.InstancePatchObject) Secured(com.alibaba.nacos.auth.annotation.Secured) CanDistro(com.alibaba.nacos.naming.web.CanDistro) PatchMapping(org.springframework.web.bind.annotation.PatchMapping)

Aggregations

Secured (com.alibaba.nacos.auth.annotation.Secured)104 Resource (com.alibaba.nacos.plugin.auth.api.Resource)34 Test (org.junit.Test)32 GetMapping (org.springframework.web.bind.annotation.GetMapping)20 CanDistro (com.alibaba.nacos.naming.web.CanDistro)17 Instance (com.alibaba.nacos.api.naming.pojo.Instance)16 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)15 PostMapping (org.springframework.web.bind.annotation.PostMapping)13 PutMapping (org.springframework.web.bind.annotation.PutMapping)13 DeleteMapping (org.springframework.web.bind.annotation.DeleteMapping)12 ConfigDataChangeEvent (com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent)10 Timestamp (java.sql.Timestamp)10 NacosException (com.alibaba.nacos.api.exception.NacosException)8 AbstractNamingRequest (com.alibaba.nacos.api.naming.remote.request.AbstractNamingRequest)8 Request (com.alibaba.nacos.api.remote.request.Request)8 ConfigInfo (com.alibaba.nacos.config.server.model.ConfigInfo)8 ServiceMetadata (com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata)7 ConfigBatchListenRequest (com.alibaba.nacos.api.config.remote.request.ConfigBatchListenRequest)6 HashMap (java.util.HashMap)6 ConfigAllInfo (com.alibaba.nacos.config.server.model.ConfigAllInfo)5