Search in sources :

Example 1 with RangerAuthenticationProvider

use of org.apache.ranger.security.handler.RangerAuthenticationProvider in project ranger by apache.

the class RangerKRBAuthenticationFilter method doFilter.

@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    String authType = PropertiesUtil.getProperty(RANGER_AUTH_TYPE);
    String userName = null;
    boolean checkCookie = response.containsHeader("Set-Cookie");
    if (checkCookie) {
        Collection<String> authUserName = response.getHeaders("Set-Cookie");
        if (authUserName != null) {
            Iterator<String> i = authUserName.iterator();
            while (i.hasNext()) {
                String cookie = i.next();
                if (!StringUtils.isEmpty(cookie)) {
                    if (cookie.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase()) && cookie.contains("u=")) {
                        String[] split = cookie.split(";");
                        if (split != null) {
                            for (String s : split) {
                                if (!StringUtils.isEmpty(s) && s.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase())) {
                                    int ustr = s.indexOf("u=");
                                    if (ustr != -1) {
                                        int andStr = s.indexOf("&", ustr);
                                        if (andStr != -1) {
                                            try {
                                                userName = s.substring(ustr + 2, andStr);
                                            } catch (Exception e) {
                                                userName = null;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    String sessionUserName = request.getParameter(S_USER);
    String pathInfo = request.getPathInfo();
    if (!StringUtils.isEmpty(sessionUserName) && "keyadmin".equalsIgnoreCase(sessionUserName) && !StringUtils.isEmpty(pathInfo) && pathInfo.contains("public/v2/api/service")) {
        LOG.info("Session will be created by : " + sessionUserName);
        userName = sessionUserName;
    }
    if ((isSpnegoEnable(authType) && (!StringUtils.isEmpty(userName)))) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth == null || !existingAuth.isAuthenticated()) {
            // --------------------------- To Create Ranger Session --------------------------------------
            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
            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(request);
            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
            Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
            authentication = getGrantedAuthority(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            request.setAttribute("spnegoEnabled", true);
            LOG.info("Logged into Ranger as = " + userName);
            filterChain.doFilter(request, response);
        } else {
            try {
                super.doFilter(filterChain, request, response);
            } catch (Exception e) {
                throw restErrorUtil.createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage());
            }
        }
    } else {
        filterChain.doFilter(request, response);
    }
}
Also used : User(org.springframework.security.core.userdetails.User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) ArrayList(java.util.ArrayList) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) ServletException(javax.servlet.ServletException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) RangerAuthenticationProvider(org.apache.ranger.security.handler.RangerAuthenticationProvider) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails)

Example 2 with RangerAuthenticationProvider

use of org.apache.ranger.security.handler.RangerAuthenticationProvider 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 3 with RangerAuthenticationProvider

use of org.apache.ranger.security.handler.RangerAuthenticationProvider in project ranger by apache.

the class RangerKRBAuthenticationFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    String authtype = PropertiesUtil.getProperty(RANGER_AUTH_TYPE);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (isSpnegoEnable(authtype)) {
        KerberosName.setRules(PropertiesUtil.getProperty(NAME_RULES, "DEFAULT"));
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        String userName = null;
        Cookie[] cookie = httpRequest.getCookies();
        if (cookie != null) {
            for (Cookie c : cookie) {
                String cname = c.getName();
                if (cname != null && "u".equalsIgnoreCase(cname)) {
                    int ustr = cname.indexOf("u=");
                    if (ustr != -1) {
                        int andStr = cname.indexOf("&", ustr);
                        if (andStr != -1) {
                            userName = cname.substring(ustr + 2, andStr);
                        }
                    }
                } else if (cname != null && AUTH_COOKIE_NAME.equalsIgnoreCase(cname)) {
                    int ustr = cname.indexOf("u=");
                    if (ustr != -1) {
                        int andStr = cname.indexOf("&", ustr);
                        if (andStr != -1) {
                            userName = cname.substring(ustr + 2, andStr);
                        }
                    }
                }
            }
        }
        if ((existingAuth == null || !existingAuth.isAuthenticated()) && (!StringUtils.isEmpty(userName))) {
            // --------------------------- To Create Ranger Session --------------------------------------
            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
            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();
            Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
            authentication = getGrantedAuthority(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            request.setAttribute("spnegoEnabled", true);
            LOG.info("Logged into Ranger as = " + userName);
        } else {
            try {
                super.doFilter(request, response, filterChain);
            } catch (Exception e) {
                throw restErrorUtil.createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage());
            }
        }
    } else {
        filterChain.doFilter(request, response);
    }
}
Also used : Cookie(javax.servlet.http.Cookie) User(org.springframework.security.core.userdetails.User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) ArrayList(java.util.ArrayList) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) ServletException(javax.servlet.ServletException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) 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) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails)

Aggregations

ArrayList (java.util.ArrayList)3 RangerAuthenticationProvider (org.apache.ranger.security.handler.RangerAuthenticationProvider)3 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 Authentication (org.springframework.security.core.Authentication)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)3 User (org.springframework.security.core.userdetails.User)3 UserDetails (org.springframework.security.core.userdetails.UserDetails)3 WebAuthenticationDetails (org.springframework.security.web.authentication.WebAuthenticationDetails)3 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 ServletException (javax.servlet.ServletException)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 SignedJWT (com.nimbusds.jwt.SignedJWT)1 ParseException (java.text.ParseException)1 Cookie (javax.servlet.http.Cookie)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 UserSessionBase (org.apache.ranger.common.UserSessionBase)1 RangerSecurityContext (org.apache.ranger.security.context.RangerSecurityContext)1