List of usage examples for org.springframework.security.core Authentication isAuthenticated
boolean isAuthenticated();
AuthenticationManager
. From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void testLoad_Opaque_AuthenticationForAUser() { defaultClient.setAutoApproveScopes(singleton("true")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResponseTypes(new HashSet(Arrays.asList(CompositeAccessToken.ID_TOKEN, "token"))); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE); azParameters.put(REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);/*from ww w. ja v a 2 s .c o m*/ OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertNotNull(accessToken); assertTrue("Token should be composite token", accessToken instanceof CompositeAccessToken); CompositeAccessToken composite = (CompositeAccessToken) accessToken; assertThat("id_token should be JWT, thus longer than 36 characters", composite.getIdTokenValue().length(), greaterThan(36)); assertThat("Opaque access token must be shorter than 37 characters", accessToken.getValue().length(), lessThanOrEqualTo(36)); assertThat("Opaque refresh token must be shorter than 37 characters", accessToken.getRefreshToken().getValue().length(), lessThanOrEqualTo(36)); String accessTokenValue = tokenProvisioning.retrieve(composite.getValue()).getValue(); Map<String, Object> accessTokenClaims = tokenServices.validateToken(accessTokenValue).getClaims(); assertEquals(true, accessTokenClaims.get(ClaimConstants.REVOCABLE)); String refreshTokenValue = tokenProvisioning.retrieve(composite.getRefreshToken().getValue()).getValue(); Map<String, Object> refreshTokenClaims = tokenServices.validateToken(refreshTokenValue).getClaims(); assertEquals(true, refreshTokenClaims.get(ClaimConstants.REVOCABLE)); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertEquals(USER_AUTHORITIES, loadedAuthentication.getAuthorities()); assertEquals(username, loadedAuthentication.getName()); UaaPrincipal uaaPrincipal = (UaaPrincipal) defaultUserAuthentication.getPrincipal(); assertEquals(uaaPrincipal, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); Authentication userAuth = loadedAuthentication.getUserAuthentication(); assertEquals(username, userAuth.getName()); assertEquals(uaaPrincipal, userAuth.getPrincipal()); assertTrue(userAuth.isAuthenticated()); Map<String, String> params = new HashedMap(); params.put("grant_type", "refresh_token"); params.put("client_id", CLIENT_ID); OAuth2AccessToken newAccessToken = tokenServices.refreshAccessToken(composite.getRefreshToken().getValue(), new TokenRequest(params, CLIENT_ID, Collections.EMPTY_SET, "refresh_token")); System.out.println("newAccessToken = " + newAccessToken); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaUserApprovalHandler.java
/** * Allows automatic approval for a white list of clients in the implicit * grant case.// w ww. j av a 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(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { // if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) { // return true; // } if (!userAuthentication.isAuthenticated()) { return false; } if (authorizationRequest.isApproved()) { return true; } String clientId = authorizationRequest.getClientId(); boolean approved = false; if (clientDetailsService != null) { ClientDetails client = clientDetailsService.loadClientByClientId(clientId); Collection<String> requestedScopes = authorizationRequest.getScope(); if (isAutoApprove(client, requestedScopes)) { approved = true; } } return approved; }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaUserApprovalHandler.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 {//from www. j a v a 2 s .c o m 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 = 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; } authorizationRequest.setApproved(approved); return authorizationRequest; }
From source file:org.cloudfoundry.identity.uaa.oauth.UserManagedAuthzApprovalHandler.java
@Override public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { String flag = authorizationRequest.getApprovalParameters().get(approvalParameter); boolean userApproval = flag != null && flag.toLowerCase().equals("true"); if (logger.isDebugEnabled()) { StringBuilder builder = new StringBuilder("Looking up user approved authorizations for "); builder.append("client_id=").append(authorizationRequest.getClientId()); builder.append(" and username=").append(userAuthentication.getName()); logger.debug(builder.toString()); }/*from w w w . ja v a 2s .c o m*/ Collection<String> requestedScopes = authorizationRequest.getScope(); // Factor in auto approved scopes Set<String> autoApprovedScopes = new HashSet<>(); BaseClientDetails client = (BaseClientDetails) clientDetailsService .retrieve(authorizationRequest.getClientId()); if (client != null && requestedScopes != null) { autoApprovedScopes.addAll(client.getAutoApproveScopes()); autoApprovedScopes = UaaTokenUtils.retainAutoApprovedScopes(requestedScopes, autoApprovedScopes); } //translate scope to user scopes - including wild cards if (userApproval) { // Store the scopes that have been approved / denied Date expiry = computeExpiry(); // Get the approved scopes, calculate the denied scope Map<String, String> approvalParameters = authorizationRequest.getApprovalParameters(); Set<String> approvedScopes = new HashSet<>(); approvedScopes.addAll(autoApprovedScopes); boolean foundUserApprovalParameter = false; for (String approvalParameter : approvalParameters.keySet()) { if (approvalParameter.startsWith(SCOPE_PREFIX)) { approvedScopes.add(approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length())); foundUserApprovalParameter = true; } } if (foundUserApprovalParameter) { authorizationRequest.setScope(approvedScopes); for (String requestedScope : requestedScopes) { if (approvedScopes.contains(requestedScope)) { Approval approval = new Approval().setUserId(getUserId(userAuthentication)) .setClientId(authorizationRequest.getClientId()).setScope(requestedScope) .setExpiresAt(expiry).setStatus(APPROVED); approvalStore.addApproval(approval); } else { Approval approval = new Approval().setUserId(getUserId(userAuthentication)) .setClientId(authorizationRequest.getClientId()).setScope(requestedScope) .setExpiresAt(expiry).setStatus(DENIED); approvalStore.addApproval(approval); } } } else { // Deny all except auto approved scopes authorizationRequest.setScope(autoApprovedScopes); for (String requestedScope : requestedScopes) { if (!autoApprovedScopes.contains(requestedScope)) { Approval approval = new Approval().setUserId(getUserId(userAuthentication)) .setClientId(authorizationRequest.getClientId()).setScope(requestedScope) .setExpiresAt(expiry).setStatus(DENIED); approvalStore.addApproval(approval); } } } if (userAuthentication.isAuthenticated()) { return true; } } else { // Find the stored approvals for that user and client List<Approval> userApprovals = approvalStore.getApprovals(getUserId(userAuthentication), authorizationRequest.getClientId()); // Look at the scopes and see if they have expired Set<String> validUserApprovedScopes = new HashSet<>(); Set<String> approvedScopes = new HashSet<>(); approvedScopes.addAll(autoApprovedScopes); validUserApprovedScopes.addAll(autoApprovedScopes); Date today = new Date(); for (Approval approval : userApprovals) { if (approval.getExpiresAt().after(today)) { validUserApprovedScopes.add(approval.getScope()); if (approval.getStatus() == APPROVED) { approvedScopes.add(approval.getScope()); } } } if (logger.isDebugEnabled()) { logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes); } // If the requested scopes have already been acted upon by the user, // this request is approved if (validUserApprovedScopes.containsAll(requestedScopes) && userAuthentication.isAuthenticated()) { approvedScopes = UaaTokenUtils.retainAutoApprovedScopes(requestedScopes, approvedScopes); // Set only the scopes that have been approved by the user authorizationRequest.setScope(approvedScopes); return true; } } return false; }
From source file:org.cloudfoundry.identity.uaa.provider.IdentityProviderEndpoints.java
@RequestMapping(value = "test", method = POST) public ResponseEntity<String> testIdentityProvider(@RequestBody IdentityProviderValidationRequest body) { String exception = "ok"; HttpStatus status = OK;//from www . j a va2 s. com //create the LDAP IDP DynamicLdapAuthenticationManager manager = new DynamicLdapAuthenticationManager( ObjectUtils.castInstance(body.getProvider().getConfig(), LdapIdentityProviderDefinition.class), scimGroupExternalMembershipManager, scimGroupProvisioning, noOpManager); try { //attempt authentication Authentication result = manager.authenticate(body.getCredentials()); if ((result == null) || (result != null && !result.isAuthenticated())) { status = EXPECTATION_FAILED; } } catch (BadCredentialsException x) { status = EXPECTATION_FAILED; exception = "bad credentials"; } catch (InternalAuthenticationServiceException x) { status = BAD_REQUEST; exception = getExceptionString(x); } catch (Exception x) { logger.debug("Identity provider validation failed.", x); status = INTERNAL_SERVER_ERROR; exception = "check server logs"; } finally { //destroy IDP manager.destroy(); } //return results return new ResponseEntity<>(JsonUtils.writeValueAsString(exception), status); }
From source file:org.cloudfoundry.identity.uaa.security.CsrfAwareEntryPointAndDeniedHandler.java
protected boolean isUserLoggedIn() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); return auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof UaaPrincipal; }
From source file:org.cloudfoundry.identity.uaa.zone.IdentityProviderEndpoints.java
@RequestMapping(value = "test", method = POST) public ResponseEntity<String> testIdentityProvider(@RequestBody IdentityProviderValidationRequest body) { String exception = "ok"; HttpStatus status = OK;// w w w . ja v a 2s . com //create the LDAP IDP DynamicLdapAuthenticationManager manager = new DynamicLdapAuthenticationManager( body.getProvider().getConfigValue(LdapIdentityProviderDefinition.class), scimGroupExternalMembershipManager, scimGroupProvisioning, noOpManager); try { //attempt authentication Authentication result = manager.authenticate(body.getCredentials()); if ((result == null) || (result != null && !result.isAuthenticated())) { status = EXPECTATION_FAILED; } } catch (BadCredentialsException x) { status = EXPECTATION_FAILED; exception = "bad credentials"; } catch (InternalAuthenticationServiceException x) { status = BAD_REQUEST; exception = getExceptionString(x); } catch (Exception x) { logger.debug("Identity provider validation failed.", x); status = INTERNAL_SERVER_ERROR; exception = "check server logs"; } finally { //destroy IDP manager.destroy(); } //return results return new ResponseEntity<>(JsonUtils.writeValueAsString(exception), status); }
From source file:org.encuestame.core.security.web.SecurityUtils.java
/** * Check is Session is Expired./* w w w . ja v a 2s . co m*/ * Iterate the existing permission stored in the {@link Authentication} and check if at least * the ENCUESTAME_USER exist and return true if this condition exist. * @param authentication * @return */ public static boolean checkIsSessionIsExpired(final Authentication authentication) { boolean session = true; if (authentication != null) { session = authentication.isAuthenticated(); for (GrantedAuthority authority : authentication.getAuthorities()) { SimpleGrantedAuthority auth = (SimpleGrantedAuthority) authority; if (auth.getAuthority().equals(EnMePermission.ENCUESTAME_USER.toString())) { session = false; break; } } } log.trace("checkIsSessionIsExpired->" + session); return session; }
From source file:org.encuestame.rest.api.v1.AdministrationJsonController.java
/** * @api {post} /api/admon/status Check the auth status * @apiName GetHomeItems// w ww . j a v a2s . c o m * @apiGroup FrontEnd * @apiDescription Check if a user is already logged or not * @apiVersion 1.0.0 * @apiSampleRequest http://www.encuestame.org/demo/api/admon/status * @apiPermission none * @apiSuccessExample * @apiSuccess {Object} success * @apiSuccess {String} error */ @RequestMapping(value = "/api/user/status", method = RequestMethod.POST) public @ResponseBody LoginStatus checkAuthStatus() { try { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth.getName().equals("anonymousUser")) { return new LoginStatus(Boolean.FALSE, auth.getName()); } else { return new LoginStatus(auth.isAuthenticated(), auth.getName()); } } catch (BadCredentialsException e) { return new LoginStatus(false, null); } }
From source file:org.esupportail.pay.web.anonyme.PayController.java
@RequestMapping("/") public String index(Model uiModel) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth.isAuthenticated() && (auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN")) || auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_MANAGER")) || auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_VIEWER")))) { return "redirect:/admin"; }/*from w w w. ja va 2 s .c om*/ return "index"; }