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.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {/*  w  ww .  j a  va2  s. c o m*/
        Authentication credentials = extractCredentials(request);

        if (credentials != null) {

            if (debug) {
                logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
            }

            Authentication authResult = authenticationManager.authenticate(credentials);

            if (debug) {
                logger.debug("Authentication success: " + authResult.getName());
            }

            Authentication requestingPrincipal = SecurityContextHolder.getContext().getAuthentication();
            if (requestingPrincipal == null) {
                throw new BadCredentialsException(
                        "No client authentication found. Remember to put a filter upstream of the LoginAuthenticationFilter.");
            }

            String clientId = request.getParameter("client_id");
            if (null == clientId) {
                logger.error("No client_id in the request");
                throw new BadCredentialsException("No client_id in the request");
            }

            // Check that the client exists
            ClientDetails authenticatingClient = clientDetailsService.loadClientByClientId(clientId);
            if (authenticatingClient == null) {
                throw new BadCredentialsException("No client " + clientId + " found");
            }

            DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(
                    getSingleValueMap(request), null, authenticatingClient.getClientId(), getScope(request));
            if (requestingPrincipal.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }

            SecurityContextHolder.getContext()
                    .setAuthentication(new OAuth2Authentication(authorizationRequest, authResult));

            onSuccessfulAuthentication(request, response, authResult);

        }

    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }

        onUnsuccessfulAuthentication(request, response, failed);

        authenticationEntryPoint.commence(request, response, failed);

        return;
    }

    chain.doFilter(request, response);
}

From source file:de.thm.arsnova.service.UserServiceImpl.java

@Override
public void authenticate(final UsernamePasswordAuthenticationToken token,
        final UserProfile.AuthProvider authProvider) {
    Authentication auth;
    switch (authProvider) {
    case LDAP:/* w  w  w . j a  v a 2 s . c om*/
        auth = ldapAuthenticationProvider.authenticate(token);
        break;
    case ARSNOVA:
        auth = daoProvider.authenticate(token);
        break;
    case ARSNOVA_GUEST:
        String id = token.getName();
        boolean autoCreate = false;
        if (id == null || id.isEmpty()) {
            id = generateGuestId();
            autoCreate = true;
        }
        UserDetails userDetails = guestUserDetailsService.loadUserByUsername(id, autoCreate);
        if (userDetails == null) {
            throw new UsernameNotFoundException("Guest user does not exist");
        }
        auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        break;
    default:
        throw new IllegalArgumentException("Unsupported authentication provider");
    }

    if (!auth.isAuthenticated()) {
        throw new BadRequestException();
    }
    SecurityContextHolder.getContext().setAuthentication(auth);
}

From source file:de.hska.ld.oidc.controller.OIDCController.java

private User _authenticate(HttpServletRequest request, String issuer, String Authorization, boolean forceUpdate)
        throws IOException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    // 1. check that the OIDC token is set in the correct way
    String oidcToken = null;//from   w ww  .  java 2  s .  c om
    try {
        oidcToken = Authorization.substring("Bearer ".length(), Authorization.length());
    } catch (Exception e) {
        throw new ValidationException("malformed oidc token information");
    }

    // 2. check if the oidcUserinfo is accessible via the access token
    OIDCUserinfoDto oidcUserinfoDto = authenticateTowardsOIDCIdentityProvider(issuer, oidcToken);
    if (!oidcUserinfoDto.isEmailVerified()) {
        throw new ValidationException("user email not verified");
    }

    // 3. check if a a user account for this oidc user still exists within living documents
    User user = userService.findBySubIdAndIssuer(oidcUserinfoDto.getSub(), issuer + "/");

    if (user == null) {
        // 3.1. If the user does NOT already exist:
        //      Create the new user in the database
        user = creatNewUserFromOIDCUserinfo(request, issuer, oidcUserinfoDto, oidcToken);
    } else {
        // 3.2. If the user does already exist:
        //      update the user's authentication
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        enrichAuthoritiesWithStoredAuthorities(request, oidcUserinfoDto.getSub(), issuer + "/", oidcUserinfoDto,
                oidcToken, user, auth);
    }

    if (!authentication.isAuthenticated() || forceUpdate) {
        if (request.getSession(false) == null) {
            request.getSession(true);
        }
        // 4.   After the user data has been retrieved or created:
        //      Update the security context with the needed information (give the user access to other rest resources)
        Authentication auth = null;
        try {
            auth = SecurityContextHolder.getContext().getAuthentication();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (auth == null) {
            throw new ValidationException("no security context for this user available");
        } else {
            try {
                Field detailsField = AbstractAuthenticationToken.class.getDeclaredField("details");
                detailsField.setAccessible(true);
                HttpSession session = request.getSession(false);
                /*if (session == null || !session.isNew()) {
                   //session = request.getSession(true);
                }*/
                Field authenticatedField = AbstractAuthenticationToken.class.getDeclaredField("authenticated");
                authenticatedField.setAccessible(true);
                authenticatedField.set(auth, true);
                SecurityContextHolder.getContext().setAuthentication(auth);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    return user;
}

From source file:com.companyname.filters.Oauth2ReAuthenticationFilter.java

public void performFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Oauth2 Re-Authentication filter starts.");

    HttpServletRequest request = (HttpServletRequest) req;

    Boolean authenticated = true;

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        logger.info("user needs to be re-authenticated via oauth2 token stored in cookies");

        logger.info("get access token cookie");
        Cookie accessTokenCookie = getCookie(request, getAccessTokenCookieName());
        logger.info("get refresh token cookie");
        Cookie refreshTokenCookie = getCookie(request, getRefreshTokenCookieName());

        String accessTokenValue = null;
        String refreshTokenValue = null;

        if (refreshTokenCookie != null) {
            refreshTokenValue = accessTokenCookie.getValue();
            logger.info("refresh token cookie is retrieved from cookie with value = " + refreshTokenValue);
        }/*w  w w. ja  v  a 2s  . c  o m*/

        if (accessTokenCookie != null) {
            accessTokenValue = accessTokenCookie.getValue();
            logger.info("access token cookie is retrieved from cookie with value = " + accessTokenValue);
        }

        if (accessTokenValue != null) {
            authentication = getAuthenticationFromAccessToken(accessTokenValue);
            logger.info("authentication object is obtained successfully via the access token");
        }

        if (authentication != null) {
            /**
            PlatAuthentication appAuthentication
                = (PlatAuthentication) authentication;
            PlatformTokens tokens = new PlatformTokens();
            tokens.setAccessToken(accessTokenValue);
            tokens.setRefreshToken(refreshTokenValue);
            appAuthentication.setTokens(tokens);
            SecurityContextHolder.getContext().setAuthentication(appAuthentication);
            * **/

            if (!authentication.isAuthenticated()) {
                logger.info("Although the authentication object is retrieved via the access token "
                        + " however, it's marked as not authenticated.");
            }

            SecurityContextHolder.getContext().setAuthentication(authentication);
            logger.info("security context is loaded with the user's authentication object");
        } else {
            authenticated = false;
            logger.info("Authentication failure, no authentication is loaded into the security context");
        }

    }

    if (authenticated) {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());

        for (String role : roles) {
            logger.info("role found: " + role);
        }

        if (roles.contains("ROLE_USER")) {
            logger.info("This user has role of ROLE_USER");
            request.getSession().setAttribute("myVale", "myvalue");
        }
        //chain.doFilter(req, res);
    } //else {            
      //HttpServletResponse response = (HttpServletResponse) res;
      //response.sendRedirect("http://localhost.drillmap.com:8080"); // hardcoded for now        
      //}

    chain.doFilter(req, res);

}

From source file:org.apache.ambari.server.security.authorization.AmbariAuthorizationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String requestURI = httpRequest.getRequestURI();

    SecurityContext context = getSecurityContext();

    Authentication authentication = context.getAuthentication();

    //  If no explicit authenticated user is set, set it to the default user (if one is specified)
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        Authentication defaultAuthentication = getDefaultAuthentication();
        if (defaultAuthentication != null) {
            context.setAuthentication(defaultAuthentication);
            authentication = defaultAuthentication;
        }/*from   w  w  w.  j  ava2 s.  c o  m*/
    }

    if (authentication == null || !authentication.isAuthenticated()) {
        String token = httpRequest.getHeader(INTERNAL_TOKEN_HEADER);
        if (token != null) {
            context.setAuthentication(new InternalAuthenticationToken(token));
        } else {
            // for view access, we should redirect to the Ambari login
            if (requestURI.matches(VIEWS_CONTEXT_ALL_PATTERN)) {
                String queryString = httpRequest.getQueryString();
                String requestedURL = queryString == null ? requestURI : (requestURI + '?' + queryString);
                String redirectURL = httpResponse.encodeRedirectURL(LOGIN_REDIRECT_BASE + requestedURL);

                httpResponse.sendRedirect(redirectURL);
                return;
            } else {
                httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Authentication required");
            }
        }
    } else if (!authorizationPerformedInternally(requestURI)) {
        boolean authorized = false;

        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (grantedAuthority instanceof AmbariGrantedAuthority) {

                AmbariGrantedAuthority ambariGrantedAuthority = (AmbariGrantedAuthority) grantedAuthority;

                PrivilegeEntity privilegeEntity = ambariGrantedAuthority.getPrivilegeEntity();
                Integer permissionId = privilegeEntity.getPermission().getId();

                // admin has full access
                if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
                    authorized = true;
                    break;
                }

                // clusters require permission
                if (!"GET".equalsIgnoreCase(httpRequest.getMethod())
                        && requestURI.matches(API_CREDENTIALS_AMBARI_PATTERN)) {
                    // Only the administrator can operate on credentials where the alias starts with "ambari."
                    if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_CLUSTERS_ALL_PATTERN)) {
                    if (permissionId.equals(PermissionEntity.CLUSTER_USER_PERMISSION)
                            || permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (STACK_ADVISOR_REGEX.matcher(requestURI).matches()) {
                    //TODO permissions model doesn't manage stacks api, but we need access to stack advisor to save configs
                    if (permissionId.equals(PermissionEntity.CLUSTER_USER_PERMISSION)
                            || permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_VIEWS_ALL_PATTERN)) {
                    // views require permission
                    if (permissionId.equals(PermissionEntity.VIEW_USER_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_PERSIST_ALL_PATTERN)) {
                    if (permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                }
            }
        }

        // allow GET for everything except /views, /api/v1/users, /api/v1/groups, /api/v1/ldap_sync_events
        if (!authorized && (!httpRequest.getMethod().equals("GET")
                || requestURI.matches(API_LDAP_SYNC_EVENTS_ALL_PATTERN))) {

            httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "You do not have permissions to access this resource.");
            httpResponse.flushBuffer();
            return;
        }
    }

    if (AuthorizationHelper.getAuthenticatedName() != null) {
        httpResponse.setHeader("User", AuthorizationHelper.getAuthenticatedName());
    }
    chain.doFilter(request, response);
}

From source file:org.apache.ambari.server.security.authorization.jwt.JwtAuthenticationFilter.java

/**
 * Do not try to validate JWT if user already authenticated via other provider
 * @return true, if JWT validation required
 *//*from  ww w.j a  va2 s. c  o  m*/
private boolean isAuthenticationRequired(String token) {
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();

    //authenticate if no auth
    if (existingAuth == null || !existingAuth.isAuthenticated()) {
        return true;
    }

    //revalidate if token was changed
    if (existingAuth instanceof JwtAuthentication
            && !StringUtils.equals(token, (String) existingAuth.getCredentials())) {
        return true;
    }

    //always try to authenticate in case of anonymous user
    if (existingAuth instanceof AnonymousAuthenticationToken) {
        return true;
    }

    return false;
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    FilterChain filterChainWrapper = new FilterChain() {
        @Override//  ww  w . j  av a 2  s.  c  om
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                throws IOException, ServletException {
            final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

            if (isKerberos) {
                Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
                String userName = readUserFromCookie(httpResponse);

                if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(httpRequest.getRemoteUser())) {
                    userName = httpRequest.getRemoteUser();
                }

                if ((existingAuth == null || !existingAuth.isAuthenticated())
                        && (!StringUtils.isEmpty(userName))) {

                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider
                            .getAuthoritiesFromUGI(userName);

                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                            principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    SecurityContextHolder.getContext().setAuthentication(finalAuthentication);

                    request.setAttribute("atlas.http.authentication.type", true);
                    LOG.info("Logged into Atlas as = {}", userName);
                }
            }
            // OPTIONS method is sent from quick start jersey atlas client
            if (httpRequest.getMethod().equals("OPTIONS")) {
                optionsServlet.service(request, response);
            } else {
                try {
                    String requestUser = httpRequest.getRemoteUser();
                    NDC.push(requestUser + ":" + httpRequest.getMethod() + httpRequest.getRequestURI());
                    RequestContext requestContext = RequestContext.get();
                    if (requestContext != null) {
                        requestContext.setUser(requestUser);
                    }
                    LOG.info("Request from authenticated user: {}, URL={}", requestUser,
                            Servlets.getRequestURI(httpRequest));

                    filterChain.doFilter(servletRequest, servletResponse);
                } finally {
                    NDC.pop();
                }
            }
        }
    };

    try {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
        responseWrapper.setHeader("X-Frame-Options", "DENY");

        if (existingAuth == null) {
            String authHeader = httpRequest.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Basic")) {
                filterChain.doFilter(request, response);
            } else if (isKerberos) {
                doKerberosAuth(request, response, filterChainWrapper, filterChain);
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    } catch (NullPointerException e) {
        LOG.error("Exception in AtlasAuthenticationFilter ", e);
        //PseudoAuthenticationHandler.getUserName() from hadoop-auth throws NPE if user name is not specified
        ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "Authentication is enabled and user is not specified. Specify user.name parameter");
    }
}