use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class OAuth20ProfileControllerTests method verifyExpiredAccessToken.
@Test
public void verifyExpiredAccessToken() throws Exception {
final Principal principal = CoreAuthenticationTestUtils.getPrincipal(ID, new HashMap<>());
final Authentication authentication = getAuthentication(principal);
final DefaultAccessTokenFactory expiringAccessTokenFactory = new DefaultAccessTokenFactory(new AlwaysExpiresExpirationPolicy());
final AccessToken accessToken = expiringAccessTokenFactory.create(RegisteredServiceTestUtils.getService(), authentication, new MockTicketGrantingTicket("casuser"), new ArrayList<>());
this.ticketRegistry.addTicket(accessToken);
final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.PROFILE_URL);
mockRequest.setParameter(OAuth20Constants.ACCESS_TOKEN, accessToken.getId());
final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
final ResponseEntity<String> entity = oAuth20ProfileController.handleRequest(mockRequest, mockResponse);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
assertEquals(CONTENT_TYPE, mockResponse.getContentType());
assertTrue(entity.getBody().contains(OAuth20Constants.EXPIRED_ACCESS_TOKEN));
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class SyncopeAuthenticationHandler method authenticateUsernamePasswordInternal.
@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential c, final String originalPassword) throws GeneralSecurityException {
try {
final String syncopeUrl = StringUtils.appendIfMissing(this.syncopeUrl, "/rest/users/self");
final HttpResponse response = HttpUtils.executeGet(syncopeUrl, c.getUsername(), c.getPassword(), new HashMap<>(), CollectionUtils.wrap("X-Syncope-Domain", this.syncopeDomain));
LOGGER.debug("Received http response status as [{}]", response.getStatusLine());
if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
LOGGER.debug("Received user object as [{}]", result);
final UserTO user = this.objectMapper.readValue(result, UserTO.class);
if (user.isSuspended()) {
throw new AccountDisabledException("Could not authenticate forbidden account for " + c.getUsername());
}
if (user.isMustChangePassword()) {
throw new AccountPasswordMustChangeException("Account password must change for " + c.getUsername());
}
final Principal principal = this.principalFactory.createPrincipal(user.getUsername(), buildSyncopeUserAttributes(user));
return createHandlerResult(c, principal, new ArrayList<>());
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
throw new FailedLoginException("Could not authenticate account for " + c.getUsername());
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class GroovyScriptInterruptInquirer method inquire.
@Override
public InterruptResponse inquire(final Authentication authentication, final RegisteredService registeredService, final Service service) {
if (ResourceUtils.doesResourceExist(resource)) {
final Principal principal = authentication.getPrincipal();
final Map<String, Object> attributes = new LinkedHashMap<>(principal.getAttributes());
attributes.putAll(authentication.getAttributes());
final Object[] args = { principal.getId(), attributes, service != null ? service.getId() : null, LOGGER };
return ScriptingUtils.executeGroovyScript(resource, args, InterruptResponse.class);
}
return new InterruptResponse(false);
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class BaseOidcScopeAttributeReleasePolicy method getAttributesInternal.
@Override
public Map<String, Object> getAttributesInternal(final Principal principal, final Map<String, Object> attributes, final RegisteredService service) {
final ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
if (applicationContext == null) {
LOGGER.warn("Could not locate the application context to process attributes");
return new HashMap<>();
}
final Map<String, Object> resolvedAttributes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
resolvedAttributes.putAll(attributes);
final Map<String, Object> attributesToRelease = new HashMap<>(resolvedAttributes.size());
LOGGER.debug("Attempting to map and filter claims based on resolved attributes [{}]", resolvedAttributes);
final CasConfigurationProperties properties = applicationContext.getBean(CasConfigurationProperties.class);
final List<String> supportedClaims = properties.getAuthn().getOidc().getClaims();
final Set<String> allowedClaims = new HashSet<>(getAllowedAttributes());
allowedClaims.retainAll(supportedClaims);
LOGGER.debug("[{}] is designed to allow claims [{}] for scope [{}]. After cross-checking with " + "supported claims [{}], the final collection of allowed attributes is [{}]", getClass().getSimpleName(), getAllowedAttributes(), getScopeName(), supportedClaims, allowedClaims);
allowedClaims.stream().map(claim -> mapClaimToAttribute(claim, resolvedAttributes)).filter(p -> p.getValue() != null).forEach(p -> attributesToRelease.put(p.getKey(), p.getValue()));
return attributesToRelease;
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class OidcIdTokenGeneratorService method produceIdTokenClaims.
/**
* Produce id token claims jwt claims.
*
* @param request the request
* @param accessTokenId the access token id
* @param timeout the timeout
* @param service the service
* @param profile the user profile
* @param context the context
* @param responseType the response type
* @return the jwt claims
*/
protected JwtClaims produceIdTokenClaims(final HttpServletRequest request, final AccessToken accessTokenId, final long timeout, final OidcRegisteredService service, final UserProfile profile, final J2EContext context, final OAuth20ResponseTypes responseType) {
final Authentication authentication = accessTokenId.getAuthentication();
final Principal principal = authentication.getPrincipal();
final OidcProperties oidc = casProperties.getAuthn().getOidc();
final JwtClaims claims = new JwtClaims();
claims.setJwtId(getOAuthServiceTicket(accessTokenId.getTicketGrantingTicket()).getKey());
claims.setIssuer(oidc.getIssuer());
claims.setAudience(service.getClientId());
final NumericDate expirationDate = NumericDate.now();
expirationDate.addSeconds(timeout);
claims.setExpirationTime(expirationDate);
claims.setIssuedAtToNow();
claims.setNotBeforeMinutesInThePast(oidc.getSkew());
claims.setSubject(principal.getId());
final MultifactorAuthenticationProperties mfa = casProperties.getAuthn().getMfa();
final Map<String, Object> attributes = authentication.getAttributes();
if (attributes.containsKey(mfa.getAuthenticationContextAttribute())) {
final Collection<Object> val = CollectionUtils.toCollection(attributes.get(mfa.getAuthenticationContextAttribute()));
claims.setStringClaim(OidcConstants.ACR, val.iterator().next().toString());
}
if (attributes.containsKey(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS)) {
final Collection<Object> val = CollectionUtils.toCollection(attributes.get(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS));
claims.setStringListClaim(OidcConstants.AMR, val.toArray(new String[] {}));
}
claims.setClaim(OAuth20Constants.STATE, attributes.get(OAuth20Constants.STATE));
claims.setClaim(OAuth20Constants.NONCE, attributes.get(OAuth20Constants.NONCE));
claims.setClaim(OidcConstants.CLAIM_AT_HASH, generateAccessTokenHash(accessTokenId, service));
principal.getAttributes().entrySet().stream().filter(entry -> oidc.getClaims().contains(entry.getKey())).forEach(entry -> claims.setClaim(entry.getKey(), entry.getValue()));
if (!claims.hasClaim(OidcConstants.CLAIM_PREFERRED_USERNAME)) {
claims.setClaim(OidcConstants.CLAIM_PREFERRED_USERNAME, profile.getId());
}
return claims;
}
Aggregations