Search in sources :

Example 1 with Permission

use of com.alibaba.nacos.plugin.auth.api.Permission 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 2 with Permission

use of com.alibaba.nacos.plugin.auth.api.Permission 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 3 with Permission

use of com.alibaba.nacos.plugin.auth.api.Permission in project nacos by alibaba.

the class Permission_ITCase method createDeleteQueryPermission.

@Test
public void createDeleteQueryPermission() {
    login();
    // Create a user:
    ResponseEntity<String> response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", "username3").appendParam("password", "password1").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Create role:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", "role1").appendParam("username", "username3").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Create permission:
    response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("resource", "public:*:*").appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Create another permission:
    response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("resource", "test1:*:*").appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query permission:
    response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("pageNo", "1").appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
    System.out.println(response);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    Page<Permission> permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
    });
    Assert.assertNotNull(permissionPage);
    Assert.assertNotNull(permissionPage.getPageItems());
    boolean found1 = false, found2 = false;
    for (Permission permission : permissionPage.getPageItems()) {
        if (permission.getResource().equals("public:*:*") && permission.getAction().equals("rw")) {
            found1 = true;
        }
        if (permission.getResource().equals("test1:*:*") && permission.getAction().equals("r")) {
            found2 = true;
        }
        if (found1 && found2) {
            break;
        }
    }
    Assert.assertTrue(found1);
    Assert.assertTrue(found2);
    // Delete permission:
    response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("resource", "public:*:*").appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query permission:
    response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("pageNo", "1").appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
    });
    Assert.assertNotNull(permissionPage);
    Assert.assertNotNull(permissionPage.getPageItems());
    found1 = false;
    found2 = false;
    for (Permission permission : permissionPage.getPageItems()) {
        if (permission.getResource().equals("public:*:*") && permission.getAction().equals("rw")) {
            found1 = true;
        }
        if (permission.getResource().equals("test1:*:*") && permission.getAction().equals("r")) {
            found2 = true;
        }
    }
    Assert.assertFalse(found1);
    Assert.assertTrue(found2);
    // Delete permission:
    response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("resource", "test1:*:*").appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query permission:
    response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("pageNo", "1").appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
    });
    Assert.assertNotNull(permissionPage);
    Assert.assertNotNull(permissionPage.getPageItems());
    found1 = false;
    found2 = false;
    for (Permission permission : permissionPage.getPageItems()) {
        if (permission.getResource().equals("public:*:*") && permission.getAction().equals("rw")) {
            found1 = true;
        }
        if (permission.getResource().equals("test1:*:*") && permission.getAction().equals("r")) {
            found2 = true;
        }
    }
    Assert.assertFalse(found1);
    Assert.assertFalse(found2);
}
Also used : Permission(com.alibaba.nacos.plugin.auth.api.Permission) Page(com.alibaba.nacos.config.server.model.Page) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HttpClient4Test(com.alibaba.nacos.test.base.HttpClient4Test) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

Permission (com.alibaba.nacos.plugin.auth.api.Permission)3 Secured (com.alibaba.nacos.auth.annotation.Secured)2 IdentityContext (com.alibaba.nacos.plugin.auth.api.IdentityContext)2 Resource (com.alibaba.nacos.plugin.auth.api.Resource)2 AccessException (com.alibaba.nacos.plugin.auth.exception.AccessException)2 Method (java.lang.reflect.Method)2 NacosException (com.alibaba.nacos.api.exception.NacosException)1 Response (com.alibaba.nacos.api.remote.response.Response)1 Page (com.alibaba.nacos.config.server.model.Page)1 HttpClient4Test (com.alibaba.nacos.test.base.HttpClient4Test)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 IOException (java.io.IOException)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Test (org.junit.Test)1 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)1