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:co.com.ppit2.web.controller.HotelesController.java

@RequestMapping(value = "/hoteles.do", method = RequestMethod.GET)
public String hoteles(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)
            && authentication.isAuthenticated()) {
        return "hoteles/hoteles";
    }/*from  w ww .  j  a v a2s  .com*/
    return "hoteles/hoteles";
}

From source file:com.orcid.api.common.server.delegator.impl.OrcidClientCredentialEndPointDelegatorImpl.java

@Transactional
public Response obtainOauth2Token(String clientId, String clientSecret, String refreshToken, String grantType,
        String code, Set<String> scopes, String state, String redirectUri, String resourceId) {

    LOGGER.info(//from w  w  w.  ja v a 2s  . c  o  m
            "OAuth2 authorization requested: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
            new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });

    Authentication client = getClientAuthentication();
    if (!client.isAuthenticated()) {
        LOGGER.info(
                "Not authenticated for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
                new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new InsufficientAuthenticationException(
                localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
    }

    /**
     * Patch, update any orcid-grants scope to funding scope
     * */
    for (String scope : scopes) {
        if (scope.contains("orcid-grants")) {
            String newScope = scope.replace("orcid-grants", "funding");
            LOGGER.info("Client {} provided a grants scope {} which will be updated to {}",
                    new Object[] { clientId, scope, newScope });
            scopes.remove(scope);
            scopes.add(newScope);
        }
    }

    try {
        boolean isClientCredentialsGrantType = OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS
                .equals(grantType);
        if (scopes != null) {
            List<String> toRemove = new ArrayList<String>();
            for (String scope : scopes) {
                ScopePathType scopeType = ScopePathType.fromValue(scope);
                if (scopeType.isInternalScope()) {
                    // You should not allow any internal scope here! go away!
                    String message = localeManager.resolveMessage("apiError.9015.developerMessage",
                            new Object[] {});
                    throw new OrcidInvalidScopeException(message);
                } else if (isClientCredentialsGrantType) {
                    if (!scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                } else {
                    if (scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                }
            }

            for (String remove : toRemove) {
                scopes.remove(remove);
            }
        }
    } catch (IllegalArgumentException iae) {
        String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
        throw new OrcidInvalidScopeException(message);
    }

    OAuth2AccessToken token = generateToken(client, scopes, code, redirectUri, grantType, refreshToken, state);
    return getResponse(token);
}

From source file:waffle.spring.WindowsAuthenticationProviderTests.java

/**
 * Test authenticate.//from   w ww .j  av a  2s.c  o m
 */
@Test
public void testAuthenticate() {
    final MockWindowsIdentity mockIdentity = new MockWindowsIdentity(WindowsAccountImpl.getCurrentUsername(),
            new ArrayList<String>());
    final WindowsPrincipal principal = new WindowsPrincipal(mockIdentity);
    final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            principal, "password");
    final Authentication authenticated = this.provider.authenticate(authentication);
    Assert.assertNotNull(authenticated);
    Assert.assertTrue(authenticated.isAuthenticated());
    final Collection<? extends GrantedAuthority> authorities = authenticated.getAuthorities();
    final Iterator<? extends GrantedAuthority> authoritiesIterator = authorities.iterator();
    Assert.assertEquals(3, authorities.size());

    final List<String> list = new ArrayList<>();
    while (authoritiesIterator.hasNext()) {
        list.add(authoritiesIterator.next().getAuthority());
    }
    Collections.sort(list);
    Assert.assertEquals("ROLE_EVERYONE", list.get(0));
    Assert.assertEquals("ROLE_USER", list.get(1));
    Assert.assertEquals("ROLE_USERS", list.get(2));
    Assert.assertTrue(authenticated.getPrincipal() instanceof WindowsPrincipal);
}

From source file:org.vaadin.spring.security.AbstractVaadinSecurity.java

@Override
public boolean isAuthenticated() {
    final Authentication authentication = getAuthentication();
    return authentication != null && authentication.isAuthenticated()
            && !(authentication instanceof AnonymousAuthenticationToken);
}

From source file:waffle.spring.WindowsAuthenticationProviderTests.java

/**
 * Test authenticate with custom granted authority factory.
 *///from  w ww  . j  av  a 2  s. c  o  m
@Test
public void testAuthenticateWithCustomGrantedAuthorityFactory() {
    this.provider.setDefaultGrantedAuthority(null);
    this.provider.setGrantedAuthorityFactory(new FqnGrantedAuthorityFactory(null, false));

    final MockWindowsIdentity mockIdentity = new MockWindowsIdentity(WindowsAccountImpl.getCurrentUsername(),
            new ArrayList<String>());
    final WindowsPrincipal principal = new WindowsPrincipal(mockIdentity);
    final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            principal, "password");

    final Authentication authenticated = this.provider.authenticate(authentication);
    Assert.assertNotNull(authenticated);
    Assert.assertTrue(authenticated.isAuthenticated());
    final Collection<? extends GrantedAuthority> authorities = authenticated.getAuthorities();
    final Iterator<? extends GrantedAuthority> authoritiesIterator = authorities.iterator();
    Assert.assertEquals(2, authorities.size());

    final List<String> list = new ArrayList<>();
    while (authoritiesIterator.hasNext()) {
        list.add(authoritiesIterator.next().getAuthority());
    }
    Collections.sort(list);
    Assert.assertEquals("Everyone", list.get(0));
    Assert.assertEquals("Users", list.get(1));
    Assert.assertTrue(authenticated.getPrincipal() instanceof WindowsPrincipal);
}

From source file:org.vaadin.spring.security.AbstractVaadinSecurity.java

@Override
public boolean hasAuthority(String authority) {
    final Authentication authentication = getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        return false;
    }/*from   w  ww.  ja  v a 2s. c  o m*/

    for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
        if (authority.equals(grantedAuthority.getAuthority())) {
            return true;
        }
    }

    return false;
}

From source file:org.sharetask.controller.UserController.java

@RequestMapping(value = "/login/status", method = RequestMethod.GET)
public void loginStatus(final HttpServletRequest request, final HttpServletResponse response) {
    int resultCode = HttpStatus.UNAUTHORIZED.value();
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    log.info("authetication: {}", authentication);
    if (authentication != null && authentication.isAuthenticated()
            && !authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))) {
        resultCode = HttpStatus.OK.value();
    }//w  ww  .j  a  v a  2s  .c o m
    response.setStatus(resultCode);
}

From source file:org.geonode.security.DatabaseSecurityClientTest.java

@Test
public void testAuthenticateUserPassword() throws Exception {
    String username = "aang";
    String password = "katara";
    final String[] requestHeaders = { "Authorization",
            "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes())) };

    final String response = "{\"superuser\": true, \"user\": \"aang\", \"geoserver\": \"false\"}";

    EasyMock.expect(mockHttpClient.sendGET(EasyMock.eq("http://localhost:8000/layers/resolve_user"),
            EasyMock.aryEq(requestHeaders))).andReturn(response);
    EasyMock.replay(mockHttpClient);/*from   w ww.j  a  va  2s  . c o  m*/

    Authentication authentication = client.authenticateUserPwd(username, password);
    EasyMock.verify(mockHttpClient);

    assertNotNull(authentication);
    assertTrue(authentication instanceof UsernamePasswordAuthenticationToken);
    assertTrue(authentication.isAuthenticated());
    assertEquals("aang", ((UserDetails) authentication.getPrincipal()).getUsername());

    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.addAll(authentication.getAuthorities());
    assertTrue(authorities.contains(GeoServerRole.ADMIN_ROLE));
    assertTrue(authorities.contains(GeoServerRole.AUTHENTICATED_ROLE));
}

From source file:org.vaadin.spring.security.Security.java

/**
 * Checks if the current user is authenticated.
 *
 * @return true if the current {@link org.springframework.security.core.context.SecurityContext} contains an {@link org.springframework.security.core.Authentication} token,
 * and the token has been authenticated by an {@link org.springframework.security.authentication.AuthenticationManager}.
 * @see org.springframework.security.core.Authentication#isAuthenticated()
 *///from  ww  w . jav a 2s. co  m
public boolean isAuthenticated() {
    final Authentication authentication = getAuthentication();
    return authentication != null && authentication.isAuthenticated();
}

From source file:org.vaadin.spring.security.Security.java

/**
 * Checks if the current user has the specified authority. This method works with static authorities (such as roles).
 * If you need more dynamic authorization (such as ACLs or EL expressions), use {@link #hasAccessToObject(Object, String...)}.
 *
 * @param authority the authority to check, must not be {@code null}.
 * @return true if the current {@link org.springframework.security.core.context.SecurityContext} contains an authenticated {@link org.springframework.security.core.Authentication}
 * token that has a {@link org.springframework.security.core.GrantedAuthority} whose string representation matches the specified {@code authority}.
 * @see org.springframework.security.core.Authentication#getAuthorities()
 * @see org.springframework.security.core.GrantedAuthority#getAuthority()
 *//*from   w  w w.  j av  a  2 s  . c om*/
public boolean hasAuthority(String authority) {
    final Authentication authentication = getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        return false;
    }
    for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
        if (authority.equals(grantedAuthority.getAuthority())) {
            return true;
        }
    }
    return false;
}