Example usage for org.springframework.security.core Authentication isAuthenticated

List of usage examples for org.springframework.security.core Authentication isAuthenticated

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication isAuthenticated.

Prototype

boolean isAuthenticated();

Source Link

Document

Used to indicate to AbstractSecurityInterceptor whether it should present the authentication token to the AuthenticationManager.

Usage

From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String authType = PropertiesUtil.getProperty(RANGER_AUTH_TYPE);
    String userName = null;//from www  . j  a  v  a2s  .c  o  m
    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) && sessionUserName.equalsIgnoreCase("keyadmin")
            && !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);
    }
}

From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

@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;//from www.  j  a va 2s  .  co  m
        Cookie[] cookie = httpRequest.getCookies();
        if (cookie != null) {
            for (Cookie c : cookie) {
                String cname = c.getName();
                if (cname != null && cname.equalsIgnoreCase("u")) {
                    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 && cname.equalsIgnoreCase(AUTH_COOKIE_NAME)) {
                    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);
    }
}

From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

private Authentication getGrantedAuthority(Authentication authentication) {
    UsernamePasswordAuthenticationToken result = null;
    if (authentication != null && authentication.isAuthenticated()) {
        final List<GrantedAuthority> grantedAuths = getAuthorities(authentication.getName().toString());
        final UserDetails userDetails = new User(authentication.getName().toString(),
                authentication.getCredentials().toString(), grantedAuths);
        result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(),
                grantedAuths);//from  w  w w. jav  a 2  s . co  m
        result.setDetails(authentication.getDetails());
        return result;
    }
    return authentication;
}

From source file:org.artifactory.security.SecurityServiceImpl.java

private static boolean isAuthenticated(Authentication authentication) {
    return authentication != null && authentication.isAuthenticated();
}

From source file:org.artifactory.security.SecurityServiceImpl.java

@Override
public String currentUserEncryptedPassword(boolean escape) {
    Authentication authentication = AuthenticationHelper.getAuthentication();
    if ((authentication != null) && authentication.isAuthenticated()) {
        String authUsername = ((UserDetails) authentication.getPrincipal()).getUsername();
        String password = (String) authentication.getCredentials();
        if (StringUtils.isNotBlank(password)) {
            UserInfo user = userGroupStoreService.findUser(authUsername);
            if (user == null) {
                log.warn("Can't return the encrypted password of the unfound user '{}'", authUsername);
            } else {
                String encrypted = createEncryptedPasswordIfNeeded(user, password);
                if (!encrypted.equals(password)) {
                    if (escape) {
                        return CryptoHelper.needsEscaping(encrypted);
                    } else {
                        return encrypted;
                    }//from  w  w  w. j  a  va  2 s .  c  om
                }
            }
        }
    }

    return null;
}

From source file:org.artifactory.webapp.servlet.AccessFilter.java

private void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final String servletPath = RequestUtils.getServletPathFromRequest(request);
    // add no cache header to web app request
    RequestUtils.addAdditionalHeadersToWebAppRequest(request, response);
    String method = request.getMethod();
    if ((servletPath == null || "/".equals(servletPath) || servletPath.length() == 0)
            && "get".equalsIgnoreCase(method)) {
        //We were called with an empty path - redirect to the app main page
        response.sendRedirect(HttpUtils.WEBAPP_URL_PATH_PREFIX + "/");
        return;//from  ww w.  j a v  a 2  s.  c om
    }
    //Reuse the authentication if it exists
    Authentication authentication = RequestUtils.getAuthentication(request);
    boolean isAuthenticated = authentication != null && authentication.isAuthenticated();
    // Make sure this is called only once
    boolean reAuthRequired = reAuthenticationRequired(request, authentication);
    if (reAuthRequired) {
        /**
         * A re-authentication is required but we might still have data that needs to be invalidated (like the
         * web session)
         */
        Map<String, LogoutHandler> logoutHandlers = ContextHelper.get().beansForType(LogoutHandler.class);
        for (LogoutHandler logoutHandler : logoutHandlers.values()) {
            logoutHandler.logout(request, response, authentication);
        }
    }
    boolean authenticationRequired = !isAuthenticated || reAuthRequired;
    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (authenticationRequired) {
        if (authFilter.acceptFilter(request)) {
            authenticateAndExecute(request, response, chain, securityContext);
        } else {
            useAnonymousIfPossible(request, response, chain, securityContext);
        }
    } else {
        log.debug("Using authentication {} from Http session.", authentication);
        useAuthentication(request, response, chain, authentication, securityContext);
    }
}

From source file:org.artifactory.webapp.servlet.AccessFilter.java

private boolean reAuthenticationRequired(HttpServletRequest request, Authentication authentication) {
    if (authentication == null || !authentication.isAuthenticated()) {
        // Not authenticated so not required to redo ;-)
        return false;
    }/*from w  ww. j  a  va  2s  . c  o m*/
    // If user changed force re-auth
    String username = authentication.getName();
    AuthenticationCache authenticationCache = userChangedCache.get(username);
    if (authenticationCache != null && authenticationCache.isChanged(authentication)) {
        authenticationCache.loggedOut(authentication);
        return true;
    }
    return authFilter.requiresReAuthentication(request, authentication);
}

From source file:org.artifactory.webapp.servlet.AccessFilter.java

private void authenticateAndExecute(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
        SecurityContext securityContext) throws IOException, ServletException {
    // Try to see if authentication in cache based on the hashed header and client ip
    Authentication authentication = getNonUiCachedAuthentication(request);
    if (authentication != null && authentication.isAuthenticated()
            && !reAuthenticationRequired(request, authentication)) {
        log.debug("Header authentication {} found in cache.", authentication);
        useAuthentication(request, response, chain, authentication, securityContext);
        // Add to user change cache the login state
        addToUserChange(authentication);
        return;/*from   www  .j  a va 2s .  c  o m*/
    }
    try {
        authFilter.doFilter(request, response, chain);
    } finally {
        Authentication newAuthentication = securityContext.getAuthentication();
        if (newAuthentication != null && newAuthentication.isAuthenticated()) {
            // Add to user change cache the login state
            addToUserChange(newAuthentication);
            // Save authentication (if session exists)
            if (RequestUtils.setAuthentication(request, newAuthentication, false)) {
                log.debug("Added authentication {} in Http session.", newAuthentication);
            } else {
                // If it did not work use the header cache
                // An authorization cache key with no header can only be used for Anonymous authentication
                AuthCacheKey authCacheKey = new AuthCacheKey(authFilter.getCacheKey(request),
                        request.getRemoteAddr());
                String username = newAuthentication.getName();
                if ((UserInfo.ANONYMOUS.equals(username) && authCacheKey.hasEmptyHeader())
                        || (!UserInfo.ANONYMOUS.equals(username) && !authCacheKey.hasEmptyHeader())) {
                    nonUiAuthCache.put(authCacheKey, newAuthentication);
                    userChangedCache.get(username).addAuthCacheKey(authCacheKey);
                    log.debug("Added authentication {} in cache.", newAuthentication);
                }
            }
        }
        securityContext.setAuthentication(null);
    }
}

From source file:org.artifactory.webapp.servlet.AccessFilter.java

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
private void useAnonymousIfPossible(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
        SecurityContext securityContext) throws IOException, ServletException {
    boolean anonAccessEnabled = context.getAuthorizationService().isAnonAccessEnabled();
    if (anonAccessEnabled || authInterceptors.accept(request)) {
        log.debug("Using anonymous");
        Authentication authentication = getNonUiCachedAuthentication(request);
        if (authentication == null) {
            log.debug("Creating the Anonymous token");
            final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    UserInfo.ANONYMOUS, "");
            AuthenticationDetailsSource ads = new HttpAuthenticationDetailsSource();
            //noinspection unchecked
            authRequest.setDetails(ads.buildDetails(request));
            // explicitly ask for the default spring authentication manager by name (we have another one which
            // is only used by the basic authentication filter)
            AuthenticationManager authenticationManager = context.beanForType("authenticationManager",
                    AuthenticationManager.class);
            authentication = authenticationManager.authenticate(authRequest);
            if (authentication != null && authentication.isAuthenticated()
                    && !RequestUtils.isUiRequest(request)) {
                AuthCacheKey authCacheKey = new AuthCacheKey(authFilter.getCacheKey(request),
                        request.getRemoteAddr());
                nonUiAuthCache.put(authCacheKey, authentication);
                log.debug("Added anonymous authentication {} to cache", authentication);
            }//  w  ww  .  j  a v  a 2s.c  o  m
        } else {
            log.debug("Using cached anonymous authentication");
        }
        useAuthentication(request, response, chain, authentication, securityContext);
    } else {
        if (authFilter.acceptEntry(request)) {
            log.debug("Sending request requiring authentication");
            authFilter.commence(request, response,
                    new InsufficientAuthenticationException("Authentication is required"));
        } else {
            log.debug("No filter or entry just chain");
            chain.doFilter(request, response);
        }
    }
}

From source file:org.artifactory.webapp.wicket.application.ArtifactoryWebSession.java

@Override
public boolean authenticate(final String username, final String password) {
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
            password);/*  w  w  w. j  a v a 2 s  . co  m*/
    HttpServletRequest servletRequest = WicketUtils.getHttpServletRequest();
    HttpServletResponse servletResponse = WicketUtils.getHttpServletResponse();
    replaceSession(); // protect against session fixation
    WebAuthenticationDetails details = new UiAuthenticationDetails(servletRequest, servletResponse);
    authenticationToken.setDetails(details);
    boolean authenticated;
    try {
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        authenticated = authentication.isAuthenticated();
        if (authenticated) {
            setAuthentication(authentication);
            if (StringUtils.isNotBlank(username) && (!username.equals(UserInfo.ANONYMOUS))) {

                //Save the user's last login info in the web session so we can display it in the welcome page
                ArtifactoryContext context = ContextHelper.get();
                SecurityService securityService = context.beanForType(SecurityService.class);
                SerializablePair<String, Long> lastLoginInfo = securityService.getUserLastLoginInfo(username);
                ArtifactoryWebSession.get().setLastLoginInfo(lastLoginInfo);

                //Update the user's current login info in the database
                String remoteAddress = new HttpAuthenticationDetails(servletRequest).getRemoteAddress();
                securityService.updateUserLastLogin(username, remoteAddress, System.currentTimeMillis());
            }
        }
    } catch (AuthenticationException e) {
        authenticated = false;
        AccessLogger.loginDenied(authenticationToken);
        if (log.isDebugEnabled()) {
            log.debug("Failed to authenticate " + username, e);
        }
    }
    return authenticated;
}