Search in sources :

Example 16 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class TestPublicAPIs method setup.

@Before
public void setup() throws Exception {
    RangerSecurityContext context = new RangerSecurityContext();
    context.setUserSession(new UserSessionBase());
    RangerContextHolder.setSecurityContext(context);
    UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
    currentUserSession.setUserAdmin(true);
}
Also used : RangerSecurityContext(org.apache.ranger.security.context.RangerSecurityContext) UserSessionBase(org.apache.ranger.common.UserSessionBase) Before(org.junit.Before)

Example 17 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class RangerPreAuthSecurityHandler method isAPIAccessible.

public boolean isAPIAccessible(String methodName) throws Exception {
    if (methodName == null) {
        return false;
    }
    UserSessionBase userSession = ContextUtil.getCurrentUserSession();
    if (userSession == null) {
        logger.warn("WARNING: UserSession found null. Some non-authorized user might be trying to access the API.");
        return false;
    }
    if (userSession.isUserAdmin()) {
        if (logger.isDebugEnabled()) {
            logger.debug("WARNING: Logged in user is System Admin, System Admin is allowed to access all the tabs except Key Manager." + "Reason for returning true is, In few cases system admin needs to have access on Key Manager tabs as well.");
        }
        return true;
    }
    Set<String> associatedTabs = rangerAPIMapping.getAssociatedTabsWithAPI(methodName);
    if (CollectionUtils.isEmpty(associatedTabs)) {
        return true;
    }
    if (associatedTabs.contains(RangerAPIMapping.TAB_PERMISSIONS) && userSession.isAuditUserAdmin()) {
        return true;
    }
    return isAPIAccessible(associatedTabs);
}
Also used : UserSessionBase(org.apache.ranger.common.UserSessionBase)

Example 18 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class RangerSSOAuthenticationFilter method doFilter.

/*
	 * doFilter of RangerSSOAuthenticationFilter is the first in the filter list so in this it check for the request
	 * if the request is from browser, doesn't contain local login and sso is enabled then it process the request against knox sso
	 * else if it's ssoenable and the request is with local login string then it show's the appropriate msg
	 * else if ssoenable is false then it contiunes with further filters as it was before sso
	 */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    String xForwardedURL = constructForwardableURL(httpRequest);
    if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
        synchronized (httpRequest.getServletContext()) {
            if (httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()) != null && "locallogin".equals(httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()).toString())) {
                httpRequest.getSession().setAttribute("locallogin", "true");
                httpRequest.getServletContext().removeAttribute(httpRequest.getRequestedSessionId());
            }
        }
    }
    RangerSecurityContext context = RangerContextHolder.getSecurityContext();
    UserSessionBase session = context != null ? context.getUserSession() : null;
    boolean ssoEnabled = session != null ? session.isSSOEnabled() : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false);
    String userAgent = httpRequest.getHeader("User-Agent");
    if (httpRequest.getSession() != null) {
        if (httpRequest.getSession().getAttribute("locallogin") != null) {
            servletRequest.setAttribute("ssoEnabled", false);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    }
    // If sso is enable and request is not for local login and is from browser then it will go inside and try for knox sso authentication
    if (ssoEnabled && !httpRequest.getRequestURI().contains(LOCAL_LOGIN_URL)) {
        // Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
        if (jwtProperties != null && !isAuthenticated()) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            String serializedJWT = getJWTFromCookie(httpRequest);
            // if we get the hadoop-jwt token from the cookies then will process it further
            if (serializedJWT != null) {
                SignedJWT jwtToken = null;
                try {
                    jwtToken = SignedJWT.parse(serializedJWT);
                    boolean valid = validateToken(jwtToken);
                    // if the public key provide is correct and also token is not expired the process token
                    if (valid) {
                        String userName = jwtToken.getJWTClaimsSet().getSubject();
                        LOG.info("SSO login user : " + userName);
                        String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
                        // if we get the userName from the token then log into ranger using the same user
                        if (userName != null && !userName.trim().isEmpty()) {
                            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
                            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
                            final UserDetails principal = new User(userName, "", grantedAuths);
                            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                            WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
                            authenticationProvider.setSsoEnabled(ssoEnabled);
                            Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
                            authentication = getGrantedAuthority(authentication);
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                        }
                        filterChain.doFilter(servletRequest, httpServletResponse);
                    } else // if the token is not valid then redirect to knox sso
                    {
                        if (isWebUserAgent(userAgent)) {
                            String ssourl = constructLoginURL(httpRequest, xForwardedURL);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("SSO URL = " + ssourl);
                            }
                            httpServletResponse.sendRedirect(ssourl);
                        } else {
                            filterChain.doFilter(servletRequest, httpServletResponse);
                        }
                    }
                } catch (ParseException e) {
                    LOG.warn("Unable to parse the JWT token", e);
                }
            } else // if the jwt token is not available then redirect it to knox sso
            {
                if (isWebUserAgent(userAgent)) {
                    String ssourl = constructLoginURL(httpRequest, xForwardedURL);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("SSO URL = " + ssourl);
                    }
                    httpServletResponse.sendRedirect(ssourl);
                } else {
                    filterChain.doFilter(servletRequest, httpServletResponse);
                }
            }
        } else // if property is not loaded or is already authenticated then proceed further with next filter
        {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    } else if (ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(LOCAL_LOGIN_URL) && isWebUserAgent(userAgent) && isAuthenticated()) {
        // If already there's an active session with sso and user want's to switch to local login(i.e without sso) then it won't be navigated to local login
        // In this scenario the user as to use separate browser
        String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(LOCAL_LOGIN_URL + "/", "");
        url = url.replace(LOCAL_LOGIN_URL, "");
        LOG.warn("There is an active session and if you want local login to ranger, try this on a separate browser");
        ((HttpServletResponse) servletResponse).sendRedirect(url);
    } else // if sso is not enable or the request is not from browser then proceed further with next filter
    {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
Also used : User(org.springframework.security.core.userdetails.User) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SignedJWT(com.nimbusds.jwt.SignedJWT) UserSessionBase(org.apache.ranger.common.UserSessionBase) RangerAuthenticationProvider(org.apache.ranger.security.handler.RangerAuthenticationProvider) HttpServletRequest(javax.servlet.http.HttpServletRequest) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) RangerSecurityContext(org.apache.ranger.security.context.RangerSecurityContext) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) ParseException(java.text.ParseException)

Example 19 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class AbstractBaseResourceService method mapBaseAttributesToViewBean.

protected void mapBaseAttributesToViewBean(T resource, V viewBean) {
    viewBean.setId(resource.getId());
    // TBD: Need to review this change later
    viewBean.setMObj(resource);
    viewBean.setCreateDate(resource.getCreateTime());
    viewBean.setUpdateDate(resource.getUpdateTime());
    Long ownerId = resource.getAddedByUserId();
    UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
    if (currentUserSession == null) {
        return;
    }
    if (ownerId != null) {
        XXPortalUser tUser = daoManager.getXXPortalUser().getById(resource.getAddedByUserId());
        if (tUser != null) {
            if (tUser.getPublicScreenName() != null && !tUser.getPublicScreenName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getPublicScreenName().trim())) {
                viewBean.setOwner(tUser.getPublicScreenName());
            } else {
                if (tUser.getFirstName() != null && !tUser.getFirstName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getFirstName().trim())) {
                    if (tUser.getLastName() != null && !tUser.getLastName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getLastName().trim())) {
                        viewBean.setOwner(tUser.getFirstName() + " " + tUser.getLastName());
                    } else {
                        viewBean.setOwner(tUser.getFirstName());
                    }
                } else {
                    viewBean.setOwner(tUser.getLoginId());
                }
            }
        }
    }
    if (resource.getUpdatedByUserId() != null) {
        XXPortalUser tUser = daoManager.getXXPortalUser().getById(resource.getUpdatedByUserId());
        if (tUser != null) {
            if (tUser.getPublicScreenName() != null && !tUser.getPublicScreenName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getPublicScreenName().trim())) {
                viewBean.setUpdatedBy(tUser.getPublicScreenName());
            } else {
                if (tUser.getFirstName() != null && !tUser.getFirstName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getFirstName().trim())) {
                    if (tUser.getLastName() != null && !tUser.getLastName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getLastName().trim())) {
                        viewBean.setUpdatedBy(tUser.getFirstName() + " " + tUser.getLastName());
                    } else {
                        viewBean.setUpdatedBy(tUser.getFirstName());
                    }
                } else {
                    viewBean.setUpdatedBy(tUser.getLoginId());
                }
            }
        }
    }
}
Also used : XXPortalUser(org.apache.ranger.entity.XXPortalUser) VXLong(org.apache.ranger.view.VXLong) UserSessionBase(org.apache.ranger.common.UserSessionBase)

Example 20 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class RangerBizUtil method createTrxLog.

public void createTrxLog(List<XXTrxLog> trxLogList) {
    if (trxLogList == null) {
        return;
    }
    UserSessionBase usb = ContextUtil.getCurrentUserSession();
    Long authSessionId = null;
    if (usb != null) {
        authSessionId = ContextUtil.getCurrentUserSession().getSessionId();
    }
    if (guidUtil != null) {
        Long trxId = guidUtil.genLong();
        for (XXTrxLog xTrxLog : trxLogList) {
            if (xTrxLog != null) {
                if ("Password".equalsIgnoreCase(StringUtil.trim(xTrxLog.getAttributeName()))) {
                    if (xTrxLog.getPreviousValue() != null && !xTrxLog.getPreviousValue().trim().isEmpty() && !"null".equalsIgnoreCase(xTrxLog.getPreviousValue().trim())) {
                        xTrxLog.setPreviousValue(AppConstants.Masked_String);
                    }
                    if (xTrxLog.getNewValue() != null && !xTrxLog.getNewValue().trim().isEmpty() && !"null".equalsIgnoreCase(xTrxLog.getNewValue().trim())) {
                        xTrxLog.setNewValue(AppConstants.Masked_String);
                    }
                }
                xTrxLog.setTransactionId(trxId.toString());
                if (authSessionId != null) {
                    xTrxLog.setSessionId("" + authSessionId);
                }
                xTrxLog.setSessionType("Spring Authenticated Session");
                xTrxLog.setRequestId(trxId.toString());
                daoManager.getXXTrxLog().create(xTrxLog);
            }
        }
    }
}
Also used : XXTrxLog(org.apache.ranger.entity.XXTrxLog) UserSessionBase(org.apache.ranger.common.UserSessionBase)

Aggregations

UserSessionBase (org.apache.ranger.common.UserSessionBase)69 RangerSecurityContext (org.apache.ranger.security.context.RangerSecurityContext)24 XXPortalUser (org.apache.ranger.entity.XXPortalUser)11 VXString (org.apache.ranger.view.VXString)11 XXUser (org.apache.ranger.entity.XXUser)8 ArrayList (java.util.ArrayList)6 XXPortalUserRole (org.apache.ranger.entity.XXPortalUserRole)6 XXService (org.apache.ranger.entity.XXService)5 VXResponse (org.apache.ranger.view.VXResponse)4 Test (org.junit.Test)4 Authentication (org.springframework.security.core.Authentication)4 HashSet (java.util.HashSet)3 HttpSession (javax.servlet.http.HttpSession)3 XXGroupUser (org.apache.ranger.entity.XXGroupUser)3 XXResource (org.apache.ranger.entity.XXResource)3 EntityManager (javax.persistence.EntityManager)2 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)2 Predicate (javax.persistence.criteria.Predicate)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2