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.slc.sli.api.resources.util.ResourceUtil.java

/**
 * Analyzes security context to get SLIPrincipal for user.
 * /*  w  ww  .ja  v a2 s  . c  o  m*/
 * @return SLIPrincipal from security context
 */
public static SLIPrincipal getSLIPrincipalFromSecurityContext() {

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

    if (auth instanceof AnonymousAuthenticationToken || auth.getPrincipal() instanceof String
            || !auth.isAuthenticated()) {
        throw new InsufficientAuthenticationException("Login Required");
    }

    // lookup security/login information
    SLIPrincipal principal = (SLIPrincipal) auth.getPrincipal();
    return principal;
}

From source file:org.springframework.security.access.intercept.AbstractSecurityInterceptor.java

/**
 * Checks the current authentication token and passes it to the AuthenticationManager
 * if {@link org.springframework.security.core.Authentication#isAuthenticated()}
 * returns false or the property <tt>alwaysReauthenticate</tt> has been set to true.
 *
 * @return an authenticated <tt>Authentication</tt> object.
 *//*from www  .j  a v a 2s .  c  o  m*/
private Authentication authenticateIfRequired() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication.isAuthenticated() && !alwaysReauthenticate) {
        if (logger.isDebugEnabled()) {
            logger.debug("Previously Authenticated: " + authentication);
        }

        return authentication;
    }

    authentication = authenticationManager.authenticate(authentication);

    // We don't authenticated.setAuthentication(true), because each provider should do
    // that
    if (logger.isDebugEnabled()) {
        logger.debug("Successfully Authenticated: " + authentication);
    }

    SecurityContextHolder.getContext().setAuthentication(authentication);

    return authentication;
}

From source file:org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProviderTests.java

License:asdf

@Test
public void authenticateSuccess() throws Exception {
    Authentication auth = provider.authenticate(token);
    assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal());
    assertThat(auth.getCredentials()).isEqualTo(token.getCredentials());
    assertThat(auth.isAuthenticated()).isEqualTo(true);
    assertThat(auth.getAuthorities().isEmpty()).isEqualTo(false);
    verify(publisher).publishEvent(isA(JaasAuthenticationSuccessEvent.class));
    verifyNoMoreInteractions(publisher);
}

From source file:org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProviderTests.java

License:asdf

@Test
public void javadocExample() {
    String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(resName);
    context.registerShutdownHook();//from ww w  .java2 s  .  c  o  m
    try {
        provider = context.getBean(DefaultJaasAuthenticationProvider.class);
        Authentication auth = provider.authenticate(token);
        assertThat(auth.isAuthenticated()).isEqualTo(true);
        assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal());
    } finally {
        context.close();
    }
}

From source file:org.springframework.security.oauth.consumer.filter.OAuthConsumerProcessingFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    Set<String> accessTokenDeps = getAccessTokenDependencies(request, response, chain);
    if (!accessTokenDeps.isEmpty()) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (isRequireAuthenticated() && !authentication.isAuthenticated()) {
            throw new InsufficientAuthenticationException("An authenticated principal must be present.");
        }/* www . j  ava 2s  .c  om*/

        OAuthSecurityContext context = OAuthSecurityContextHolder.getContext();
        if (context == null) {
            throw new IllegalStateException(
                    "No OAuth security context has been established. Unable to access resources.");
        }

        Map<String, OAuthConsumerToken> accessTokens = context.getAccessTokens();

        for (String dependency : accessTokenDeps) {
            if (!accessTokens.containsKey(dependency)) {
                throw new AccessTokenRequiredException(
                        getProtectedResourceDetailsService().loadProtectedResourceDetailsById(dependency));
            }
        }

        chain.doFilter(request, response);
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No access token dependencies for request.");
        }
        chain.doFilter(servletRequest, servletResponse);
    }
}

From source file:org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler.java

/**
 * Basic implementation just requires the authorization request to be explicitly approved and the user to be
 * authenticated./*from   w  w  w .  ja  va2  s  .  c o  m*/
 * 
 * @param authorizationRequest The authorization request.
 * @param userAuthentication the current user authentication
 * 
 * @return Whether the specified request has been approved by the current user.
 */
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {

    String flag = authorizationRequest.getApprovalParameters().get(approvalParameter);
    boolean approved = flag != null && flag.toLowerCase().equals("true");

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest, userAuthentication);
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up existing token for ");
        builder.append("client_id=" + authorizationRequest.getClientId());
        builder.append(", scope=" + authorizationRequest.getScope());
        builder.append(" and username=" + userAuthentication.getName());
        logger.debug(builder.toString());
    }

    OAuth2AccessToken accessToken = tokenServices.getAccessToken(authentication);
    logger.debug("Existing access token=" + accessToken);
    if (accessToken != null && !accessToken.isExpired()) {
        logger.debug("User already approved with token=" + accessToken);
        // A token was already granted and is still valid, so this is already approved
        approved = true;
    } else {
        logger.debug("Checking explicit approval");
        approved = userAuthentication.isAuthenticated() && approved;
    }

    return approved;

}

From source file:org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler.java

@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    boolean approved = false;

    String clientId = authorizationRequest.getClientId();
    Set<String> scopes = authorizationRequest.getScope();
    if (clientDetailsService != null) {
        try {//  w w  w  . j ava 2s . c om
            ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
            approved = true;
            for (String scope : scopes) {
                if (!client.isAutoApprove(scope)) {
                    approved = false;
                }
            }
            if (approved) {
                authorizationRequest.setApproved(true);
                return authorizationRequest;
            }
        } catch (ClientRegistrationException e) {
            logger.warn("Client registration problem prevent autoapproval check for client=" + clientId);
        }
    }

    OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest);

    OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, userAuthentication);
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up existing token for ");
        builder.append("client_id=" + clientId);
        builder.append(", scope=" + scopes);
        builder.append(" and username=" + userAuthentication.getName());
        logger.debug(builder.toString());
    }

    OAuth2AccessToken accessToken = tokenStore.getAccessToken(authentication);
    logger.debug("Existing access token=" + accessToken);
    if (accessToken != null && !accessToken.isExpired()) {
        logger.debug("User already approved with token=" + accessToken);
        // A token was already granted and is still valid, so this is already approved
        approved = true;
    } else {
        logger.debug("Checking explicit approval");
        approved = userAuthentication.isAuthenticated() && approved;
    }

    authorizationRequest.setApproved(approved);

    return authorizationRequest;
}

From source file:org.springframework.security.oauth2.provider.endpoint.TokenEndpointAuthenticationFilter.java

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 w w.  j  av  a2  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 clientAuth = SecurityContextHolder.getContext().getAuthentication();
            if (clientAuth == null) {
                throw new BadCredentialsException(
                        "No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
            }
            DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(
                    getSingleValueMap(request), null, clientAuth.getName(), getScope(request));
            if (clientAuth.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:org.taverna.server.master.TavernaServerSupport.java

/**
 * Gets the identity of the user currently accessing the webapp, which is
 * stored in a thread-safe way in the webapp's container's context.
 * /*from w w  w . j av a2s.c o  m*/
 * @return The identity of the user accessing the webapp.
 */
@NonNull
public UsernamePrincipal getPrincipal() {
    try {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated()) {
            if (logGetPrincipalFailures)
                log.warn("failed to get auth; going with <NOBODY>");
            return new UsernamePrincipal("<NOBODY>");
        }
        return new UsernamePrincipal(auth);
    } catch (RuntimeException e) {
        if (logGetPrincipalFailures)
            log.info("failed to map principal", e);
        throw e;
    }
}

From source file:org.unitime.timetable.filter.PageAccessFilter.java

private UserContext getUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()
            && authentication.getPrincipal() instanceof UserContext)
        return (UserContext) authentication.getPrincipal();
    return null;//from w w  w  .j  a  va2s. co m
}