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:com.boundlessgeo.geoserver.AppAuthFilter.java

boolean isAuthenticated() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    return auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken);
}

From source file:org.glassmaker.spring.oauth.OAuth2Util.java

public boolean requiresAuthentication(HttpServletRequest request) {

    HttpSession session = request.getSession();
    if (session != null) {
        SecurityContext securityContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
        if (securityContext != null) {
            Authentication auth = securityContext.getAuthentication();
            if (auth != null && auth.isAuthenticated())
                return false;
        }/*from   ww  w. java2  s  .c  o m*/
    }

    String code = request.getParameter("code");
    // If we have a code, finish the OAuth 2.0 dance
    if (code == null) {
        return true;
    }
    return false;
}

From source file:eu.freme.broker.security.ManagementEndpointAuthenticationFilter.java

private Authentication tryToAuthenticate(Authentication requestAuthentication) {
    Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
    if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
        throw new InternalAuthenticationServiceException(
                "Unable to authenticate Backend Admin for provided credentials");
    }/*from   ww  w .j  ava2 s  .  c  om*/
    logger.debug("Backend Admin successfully authenticated");
    return responseAuthentication;
}

From source file:com.ixortalk.aws.cognito.boot.filter.AwsCognitoIdTokenProcessorTest.java

@Test
public void whenSignedJWTWithMatchingKeyInAuthorizationHeaderProvidedAuthenticationIsReturned()
        throws Exception {
    request.addHeader("Authorization", newJwtToken(KNOWN_KID, "role1").serialize());
    Authentication authentication = awsCognitoIdTokenProcessor.getAuthentication(request);
    assertThat(authentication.isAuthenticated()).isTrue();
}

From source file:info.raack.appliancelabeler.security.HttpSessionAndDatabaseOAuthRemeberMeServices.java

public void rememberTokens(Map<String, OAuthConsumerToken> tokens, HttpServletRequest request,
        HttpServletResponse response) {/*from  w w w .  ja va 2  s.  c  om*/
    // put tokens into session

    String email = "";

    HttpSession session = request.getSession(false);
    if (session != null) {
        session.setAttribute(REMEMBERED_TOKENS_KEY, tokens);
        email = (String) session.getAttribute(EMAIL_ATTRIBUTE);
    }

    // put tokens into database
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.isAuthenticated()) {
        String userId = null;

        if (auth instanceof RememberMeAuthenticationToken) {
            Object principal = auth.getPrincipal();
            if (principal instanceof OAuthUserDetails) {
                userId = ((OAuthUserDetails) principal).getUsername();
            } else if (principal instanceof String) {
                userId = (String) auth.getPrincipal();
            }
        } else if (auth instanceof OAuthAutomaticAuthenticationToken) {
            // user is already logged in via spring security
            userId = (String) auth.getPrincipal();
        }

        logger.debug("Saving oauth tokens to database");
        if (userId != null) {
            dataService.saveOAuthTokensForUserId(userId, email, tokens);
        }
    }

}

From source file:com.acc.oauth2.HybrisApprovalHandler.java

/**
 * Allows automatic approval for a white list of clients in the implicit grant case.
 * //from  ww w  .  j a  va 2s .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.
 */
@Override
public boolean isApproved(final AuthorizationRequest authorizationRequest,
        final Authentication userAuthentication) {
    if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) {
        return true;
    }
    if (!userAuthentication.isAuthenticated()) {
        return false;
    }
    return authorizationRequest.isApproved() || (authorizationRequest.getResponseTypes().contains("token")
            && autoApproveClients.contains(authorizationRequest.getClientId()));
}

From source file:org.openlmis.fulfillment.security.CustomUserAuthenticationConverterTest.java

private void checkAuthentication(UUID userId, Authentication authentication) {
    assertEquals(userId, authentication.getPrincipal());
    assertEquals("N/A", authentication.getCredentials());
    assertTrue(authentication.isAuthenticated());
}

From source file:com.castlemock.war.config.SecurityInterceptor.java

/**
 * The method will check if the logged in user is still valid.
 * @param request The incoming request.//  w  w w . ja v  a 2s.  c  om
 * @param response The outgoing response
 * @param handler The handler contains information about the method and controller that will process the incoming request
 * @return Returns true if the logged in users information is still valid. Returns false if the user is not valid
 * @throws IOException Upon unable to send a redirect as a response
 * @throws ServletException Upon unable to logout the user
 */
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws IOException, ServletException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        return true;
    }

    final String loggedInUsername = authentication.getName();
    if (ANONYMOUS_USER.equals(loggedInUsername)) {
        return true;
    }

    final ReadUserByUsernameInput readUserByUsernameInput = new ReadUserByUsernameInput(loggedInUsername);
    final ReadUserByUsernameOutput readUserByUsernameOutput = serviceProcessor.process(readUserByUsernameInput);
    final UserDto loggedInUser = readUserByUsernameOutput.getUser();
    if (loggedInUser == null) {
        LOGGER.info("The following logged in user is not valid anymore: " + loggedInUsername);
        request.logout();
        response.sendRedirect(request.getContextPath());
        return false;
    } else if (!Status.ACTIVE.equals(loggedInUser.getStatus())) {
        LOGGER.info("The following logged in user is not active anymore: " + loggedInUsername);
        request.logout();
        response.sendRedirect(request.getContextPath());
        return false;
    } else {
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            Role role = Role.valueOf(grantedAuthority.getAuthority());
            if (!loggedInUser.getRole().equals(role)) {
                LOGGER.info("The following logged in user's authorities has been updated: " + loggedInUsername);
                final UserDetails userDetails = userDetailSecurityService.loadUserByUsername(loggedInUsername);
                final Authentication newAuthentication = new UsernamePasswordAuthenticationToken(userDetails,
                        userDetails.getPassword(), userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(newAuthentication);
            }
        }
        return true;
    }
}

From source file:com.epam.ta.reportportal.auth.permissions.ReportPortalPermissionEvaluator.java

private boolean checkPermission(Authentication authentication, Object targetDomainObject,
        String permissionKey) {/*  ww w.j  a va  2  s.  co m*/
    verifyPermissionIsDefined(permissionKey);
    if (allowAllToAdmin && authentication.isAuthenticated()
            && authentication.getAuthorities().contains(ADMIN_AUTHORITY)) {
        return true;
    }
    Permission permission = permissionNameToPermissionMap.get(permissionKey);
    return permission.isAllowed(authentication, targetDomainObject);
}

From source file:net.maritimecloud.identityregistry.security.MCAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    logger.debug("In authenticate");
    // The login name is the org shortname
    // Organization org = this.organizationService.getOrganizationByShortName(name);
    // if an org was found, test the password
    // if (org != null && (new BCryptPasswordEncoder().matches(password, org.getPasswordHash()))) {
    if (!password.isEmpty()) {
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        Authentication auth = new UsernamePasswordAuthenticationToken(name, authentication.getCredentials(),
                grantedAuths);//from   w  w  w  . j av a 2 s.c  o m
        logger.debug("Got authenticated: " + auth.isAuthenticated());
        return auth;
    } else {
        logger.debug("Didn't get authenticated");
        throw new BadCredentialsException("Bad Credentials");
    }
}