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());
}
}
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;
}
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";
}
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;
}
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";
}
Aggregations