use of org.apache.ranger.view.VXResponse in project ranger by apache.
the class RangerAuthSuccessHandler method onAuthenticationSuccess.
/*
* (non-Javadoc)
*
* @see org.springframework.security.web.authentication.
* SavedRequestAwareAuthenticationSuccessHandler
* #onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.Authentication)
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
RangerSessionFixationProtectionStrategy rangerSessionFixationProtectionStrategy = new RangerSessionFixationProtectionStrategy();
rangerSessionFixationProtectionStrategy.onAuthentication(authentication, request, response);
WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
String remoteAddress = details != null ? details.getRemoteAddress() : "";
String sessionId = details != null ? details.getSessionId() : "";
boolean isValidUser = sessionMgr.isValidXAUser(authentication.getName());
String rangerAuthenticationMethod = PropertiesUtil.getProperty("ranger.authentication.method", "NONE");
if (!isValidUser && !"NONE".equalsIgnoreCase(rangerAuthenticationMethod)) {
xUserMgr.createServiceConfigUser(authentication.getName());
isValidUser = sessionMgr.isValidXAUser(authentication.getName());
}
response.setContentType("application/json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("X-Frame-Options", "DENY");
VXResponse vXResponse = new VXResponse();
if (!isValidUser) {
sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_USER_NOT_FOUND, XXAuthSession.AUTH_TYPE_PASSWORD, authentication.getName(), remoteAddress, sessionId);
authentication.setAuthenticated(false);
vXResponse.setStatusCode(HttpServletResponse.SC_PRECONDITION_FAILED);
vXResponse.setMsgDesc("Auth Succeeded but user is not synced yet for " + authentication.getName());
response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
// response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
logger.info("Auth Succeeded but user is not synced yet for " + authentication.getName());
} else {
String ajaxRequestHeader = request.getHeader("X-Requested-With");
if (logger.isDebugEnabled()) {
logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
}
if (ajaxRequestHeader != null && "XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) {
// if (logger.isDebugEnabled()) {
// logger.debug("Forwarding AJAX login request success to "
// + ajaxLoginSuccessPage + " for user "
// + authentication.getName());
// }
// request.getRequestDispatcher(ajaxLoginSuccessPage).forward(request,
// response);
String jsonResp = "";
try {
vXResponse.setStatusCode(HttpServletResponse.SC_OK);
vXResponse.setMsgDesc("Login Successful");
response.setStatus(HttpServletResponse.SC_OK);
jsonResp = jsonUtil.writeObjectAsString(vXResponse);
response.getWriter().write(jsonResp);
} catch (IOException e) {
logger.info("Error while writing JSON in HttpServletResponse");
}
if (logger.isDebugEnabled()) {
logger.debug("Sending login success response : " + jsonResp);
}
clearAuthenticationAttributes(request);
} else {
String jsonResp = "";
try {
vXResponse.setStatusCode(HttpServletResponse.SC_OK);
vXResponse.setMsgDesc("Login Successful");
response.setStatus(HttpServletResponse.SC_OK);
jsonResp = jsonUtil.writeObjectAsString(vXResponse);
response.getWriter().write(jsonResp);
} catch (IOException e) {
logger.info("Error while writing JSON in HttpServletResponse");
}
if (logger.isDebugEnabled()) {
logger.debug("Sending login success response : " + jsonResp);
}
// super.onAuthenticationSuccess(request, response,
// authentication);
}
}
}
use of org.apache.ranger.view.VXResponse in project ranger by apache.
the class RangerAuthenticationEntryPoint method commence.
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
String ajaxRequestHeader = request.getHeader("X-Requested-With");
response.setHeader("X-Frame-Options", "DENY");
if (logger.isDebugEnabled()) {
logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
}
String requestURL = (request.getRequestURL() != null) ? request.getRequestURL().toString() : "";
String servletPath = PropertiesUtil.getProperty("ranger.servlet.mapping.url.pattern", "service");
String reqServletPath = configUtil.getWebAppRootURL() + "/" + servletPath;
if ("XMLHttpRequest".equals(ajaxRequestHeader)) {
try {
VXResponse vXResponse = new VXResponse();
vXResponse.setStatusCode(SC_AUTHENTICATION_TIMEOUT);
vXResponse.setMsgDesc("Session Timeout");
response.setStatus(SC_AUTHENTICATION_TIMEOUT);
response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
} catch (IOException e) {
logger.info("Error while writing JSON in HttpServletResponse");
}
return;
} else {
try {
VXResponse vXResponse = new VXResponse();
vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
vXResponse.setMsgDesc("Authentication Failed");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
} catch (IOException e) {
logger.info("Error while writing JSON in HttpServletResponse");
}
}
if (ajaxRequestHeader != null && "XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) {
if (logger.isDebugEnabled()) {
logger.debug("commence() AJAX request. Authentication required. Returning " + ajaxReturnCode + ". URL=" + request.getRequestURI());
}
response.sendError(ajaxReturnCode, "");
} else if (!(requestURL.startsWith(reqServletPath))) {
if (requestURL.contains(RangerSSOAuthenticationFilter.LOCAL_LOGIN_URL)) {
if (request.getSession() != null) {
request.getSession().setAttribute("locallogin", "true");
request.getServletContext().setAttribute(request.getSession().getId(), "locallogin");
}
}
super.commence(request, response, authException);
}
}
use of org.apache.ranger.view.VXResponse in project ranger by apache.
the class ServiceREST method validateConfig.
@POST
@Path("/services/validateConfig")
@Produces({ "application/json", "application/xml" })
@PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.VALIDATE_CONFIG + "\")")
public VXResponse validateConfig(RangerService service) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.validateConfig(" + service + ")");
}
VXResponse ret = new VXResponse();
RangerPerfTracer perf = null;
try {
if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.validateConfig(serviceName=" + service.getName() + ")");
}
ret = serviceMgr.validateConfig(service, svcStore);
} catch (WebApplicationException excp) {
throw excp;
} catch (Throwable excp) {
LOG.error("validateConfig(" + service + ") failed", excp);
throw restErrorUtil.createRESTException(excp.getMessage());
} finally {
RangerPerfTracer.log(perf);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== ServiceREST.validateConfig(" + service + "): " + ret);
}
return ret;
}
use of org.apache.ranger.view.VXResponse in project ranger by apache.
the class ServiceREST method grantAccess.
@POST
@Path("/services/grant/{serviceName}")
@Produces({ "application/json", "application/xml" })
public RESTResponse grantAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest grantRequest, @Context HttpServletRequest request) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.grantAccess(" + serviceName + ", " + grantRequest + ")");
}
RESTResponse ret = new RESTResponse();
RangerPerfTracer perf = null;
if (grantRequest != null) {
if (serviceUtil.isValidateHttpsAuthentication(serviceName, request)) {
try {
if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.grantAccess(serviceName=" + serviceName + ")");
}
validateGrantRevokeRequest(grantRequest);
String userName = grantRequest.getGrantor();
Set<String> userGroups = CollectionUtils.isNotEmpty(grantRequest.getGrantorGroups()) ? grantRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName);
RangerAccessResource resource = new RangerAccessResourceImpl(StringUtil.toStringObjectMap(grantRequest.getResource()));
VXUser vxUser = xUserService.getXUserByUserName(userName);
if (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) {
VXResponse vXResponse = new VXResponse();
vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
vXResponse.setMsgDesc("Operation" + " denied. LoggedInUser=" + vxUser.getId() + " ,isn't permitted to perform the action.");
throw restErrorUtil.generateRESTException(vXResponse);
}
boolean isAdmin = hasAdminAccess(serviceName, userName, userGroups, resource);
if (!isAdmin) {
throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to grant access");
}
RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, userName);
if (policy != null) {
boolean policyUpdated = false;
policyUpdated = ServiceRESTUtil.processGrantRequest(policy, grantRequest);
if (policyUpdated) {
svcStore.updatePolicy(policy);
} else {
LOG.error("processGrantRequest processing failed");
throw new Exception("processGrantRequest processing failed");
}
} else {
policy = new RangerPolicy();
policy.setService(serviceName);
// TODO: better policy name
policy.setName("grant-" + System.currentTimeMillis());
policy.setDescription("created by grant");
policy.setIsAuditEnabled(grantRequest.getEnableAudit());
policy.setCreatedBy(userName);
Map<String, RangerPolicyResource> policyResources = new HashMap<String, RangerPolicyResource>();
Set<String> resourceNames = resource.getKeys();
if (!CollectionUtils.isEmpty(resourceNames)) {
for (String resourceName : resourceNames) {
RangerPolicyResource policyResource = new RangerPolicyResource((String) resource.getValue(resourceName));
policyResource.setIsRecursive(grantRequest.getIsRecursive());
policyResources.put(resourceName, policyResource);
}
}
policy.setResources(policyResources);
RangerPolicyItem policyItem = new RangerPolicyItem();
policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin());
policyItem.getUsers().addAll(grantRequest.getUsers());
policyItem.getGroups().addAll(grantRequest.getGroups());
for (String accessType : grantRequest.getAccessTypes()) {
policyItem.getAccesses().add(new RangerPolicyItemAccess(accessType, Boolean.TRUE));
}
policy.getPolicyItems().add(policyItem);
svcStore.createPolicy(policy);
}
} catch (WebApplicationException excp) {
throw excp;
} catch (Throwable excp) {
LOG.error("grantAccess(" + serviceName + ", " + grantRequest + ") failed", excp);
throw restErrorUtil.createRESTException(excp.getMessage());
} finally {
RangerPerfTracer.log(perf);
}
ret.setStatusCode(RESTResponse.STATUS_SUCCESS);
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== ServiceREST.grantAccess(" + serviceName + ", " + grantRequest + "): " + ret);
}
return ret;
}
use of org.apache.ranger.view.VXResponse in project ranger by apache.
the class RangerBizUtil method hasPermission.
/**
* return response object if users is having permission on given resource
*
* @param vXResource
* @param permission
* @return
*/
public VXResponse hasPermission(VXResource vXResource, int permission) {
VXResponse vXResponse = new VXResponse();
if (!enableResourceAccessControl) {
logger.debug("Resource Access Control is disabled !!!");
return vXResponse;
}
if (vXResource == null) {
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
vXResponse.setMsgDesc("Please provide valid policy.");
return vXResponse;
}
String resourceNames = vXResource.getName();
if (stringUtil.isEmpty(resourceNames)) {
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
vXResponse.setMsgDesc("Please provide valid policy.");
return vXResponse;
}
if (isAdmin()) {
return vXResponse;
}
Long xUserId = getXUserId();
Long assetId = vXResource.getAssetId();
List<XXResource> xResourceList = daoManager.getXXResource().findByAssetIdAndResourceStatus(assetId, AppConstants.STATUS_ENABLED);
XXAsset xAsset = daoManager.getXXAsset().getById(assetId);
int assetType = xAsset.getAssetType();
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
vXResponse.setMsgDesc("Permission Denied !");
if (assetType == AppConstants.ASSET_HIVE) {
String[] requestResNameList = resourceNames.split(",");
if (stringUtil.isEmpty(vXResource.getUdfs())) {
int reqTableType = vXResource.getTableType();
int reqColumnType = vXResource.getColumnType();
for (String resourceName : requestResNameList) {
boolean matchFound = matchHivePolicy(resourceName, xResourceList, xUserId, permission, reqTableType, reqColumnType, false);
if (!matchFound) {
vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
return vXResponse;
}
}
} else {
for (String resourceName : requestResNameList) {
boolean matchFound = matchHivePolicy(resourceName, xResourceList, xUserId, permission);
if (!matchFound) {
vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
return vXResponse;
}
}
}
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
return vXResponse;
} else if (assetType == AppConstants.ASSET_HBASE) {
String[] requestResNameList = resourceNames.split(",");
for (String resourceName : requestResNameList) {
boolean matchFound = matchHbasePolicy(resourceName, xResourceList, vXResponse, xUserId, permission);
if (!matchFound) {
vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
return vXResponse;
}
}
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
return vXResponse;
} else if (assetType == AppConstants.ASSET_HDFS) {
String[] requestResNameList = resourceNames.split(",");
for (String resourceName : requestResNameList) {
boolean matchFound = matchHdfsPolicy(resourceName, xResourceList, xUserId, permission);
if (!matchFound) {
vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
return vXResponse;
}
}
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
return vXResponse;
} else if (assetType == AppConstants.ASSET_KNOX) {
String[] requestResNameList = resourceNames.split(",");
for (String resourceName : requestResNameList) {
boolean matchFound = matchKnoxPolicy(resourceName, xResourceList, xUserId, permission);
if (!matchFound) {
vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
return vXResponse;
}
}
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
return vXResponse;
} else if (assetType == AppConstants.ASSET_STORM) {
String[] requestResNameList = resourceNames.split(",");
for (String resourceName : requestResNameList) {
boolean matchFound = matchStormPolicy(resourceName, xResourceList, xUserId, permission);
if (!matchFound) {
vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
return vXResponse;
}
}
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
return vXResponse;
}
return vXResponse;
}
Aggregations