use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class DefaultAcceptableUsagePolicyRepository method verify.
@Override
public Pair<Boolean, Principal> verify(final RequestContext requestContext, final Credential credential) {
final String key = credential.getId();
final Principal principal = WebUtils.getPrincipalFromRequestContext(requestContext, this.ticketRegistrySupport);
if (this.policyMap.containsKey(key)) {
return Pair.of(this.policyMap.get(key), principal);
}
return Pair.of(false, principal);
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class BaseOAuthWrapperController method createAuthentication.
/**
* Create an authentication from a user profile.
*
* @param profile the given user profile
* @param registeredService the registered service
* @param context the context
* @param service the service
* @return the built authentication
*/
protected Authentication createAuthentication(final UserProfile profile, final RegisteredService registeredService, final J2EContext context, final Service service) {
final Principal newPrincipal = this.scopeToAttributesFilter.filter(service, this.principalFactory.createPrincipal(profile.getId(), profile.getAttributes()), registeredService, context);
LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService);
final String authenticator = profile.getClass().getCanonicalName();
final CredentialMetaData metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId()));
final HandlerResult handlerResult = new DefaultHandlerResult(authenticator, metadata, newPrincipal, new ArrayList<>());
final String state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuthConstants.STATE), StringUtils.EMPTY);
final String nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuthConstants.NONCE), StringUtils.EMPTY);
LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuthConstants.STATE, state, OAuthConstants.NONCE, nonce);
final AuthenticationBuilder bldr = DefaultAuthenticationBuilder.newInstance().addAttribute("permissions", profile.getPermissions()).addAttribute("roles", profile.getRoles()).addAttribute(OAuthConstants.STATE, state).addAttribute(OAuthConstants.NONCE, nonce).addCredential(metadata).setPrincipal(newPrincipal).setAuthenticationDate(ZonedDateTime.now()).addSuccess(profile.getClass().getCanonicalName(), handlerResult);
// Add "other" profile attributes as authentication attributes.
if (casProperties.getAuthn().getOauth().getAccessToken().isReleaseProtocolAttributes()) {
profile.getAttributes().forEach((k, v) -> {
if (!newPrincipal.getAttributes().containsKey(k)) {
LOGGER.debug("Added attribute [{}] with value [{}] to the authentication", k, v);
bldr.addAttribute(k, v);
} else {
LOGGER.debug("Skipped over attribute [{}] since it's already contained by the principal", k);
}
});
}
return bldr.build();
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class Cas30JsonResponseView method createAuthenticationSuccess.
private CasServiceResponseAuthenticationSuccess createAuthenticationSuccess(final Map<String, Object> model) {
final CasServiceResponseAuthenticationSuccess success = new CasServiceResponseAuthenticationSuccess();
success.setAttributes(getModelAttributes(model));
final Principal principal = getPrincipal(model);
success.setUser(principal.getId());
success.setProxyGrantingTicket(getProxyGrantingTicketIou(model));
final Collection<Authentication> chainedAuthentications = getChainedAuthentications(model);
if (chainedAuthentications != null && !chainedAuthentications.isEmpty()) {
final List<String> proxies = chainedAuthentications.stream().map(authn -> authn.getPrincipal().getId()).collect(Collectors.toList());
success.setProxies(proxies);
}
return success;
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class OAuthUserAuthenticator method validate.
@Override
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws CredentialsException {
final UsernamePasswordCredential casCredential = new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
try {
final String clientId = context.getRequestParameter(OAuthConstants.CLIENT_ID);
final Service service = this.webApplicationServiceFactory.createService(clientId);
final RegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(this.servicesManager, clientId);
RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);
final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, casCredential);
final Authentication authentication = authenticationResult.getAuthentication();
final Principal principal = authentication.getPrincipal();
final OAuthUserProfile profile = new OAuthUserProfile();
final String id = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service);
LOGGER.debug("Created profile id [{}]", id);
profile.setId(id);
final Map<String, Object> attributes = registeredService.getAttributeReleasePolicy().getAttributes(principal, registeredService);
profile.addAttributes(attributes);
LOGGER.debug("Authenticated user profile [{}]", profile);
credentials.setUserProfile(profile);
} catch (final Exception e) {
throw new CredentialsException("Cannot login user using CAS internal authentication", e);
}
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class OAuth20AccessTokenControllerTests method internalVerifyRefreshTokenOk.
private void internalVerifyRefreshTokenOk(final RegisteredService service, final boolean json) throws Exception {
final Principal principal = createPrincipal();
final RefreshToken refreshToken = addRefreshToken(principal, service);
final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name().toLowerCase());
mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, refreshToken.getId());
final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
//This assert fails because deep down inside Oauth2 access token ctrl the refresh token gets deleted
//assertNotNull(oAuth20AccessTokenController.getRegistry().getTicket((refreshToken.getId())));
assertEquals(200, mockResponse.getStatus());
final String body = mockResponse.getContentAsString();
final String accessTokenId;
if (json) {
assertEquals("application/json", mockResponse.getContentType());
assertTrue(body.contains('"' + OAuthConstants.ACCESS_TOKEN + "\":\"AT-"));
assertFalse(body.contains('"' + OAuthConstants.REFRESH_TOKEN + "\":\"RT-"));
assertTrue(body.contains('"' + OAuthConstants.EXPIRES_IN + "\":7"));
accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + "\":\"", "\",\"");
} else {
assertEquals("text/plain", mockResponse.getContentType());
assertTrue(body.contains(OAuthConstants.ACCESS_TOKEN + '='));
assertFalse(body.contains(OAuthConstants.REFRESH_TOKEN + '='));
assertTrue(body.contains(OAuthConstants.EXPIRES_IN + '='));
accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + '=', "&");
}
final AccessToken accessToken = oAuth20AccessTokenController.getTicketRegistry().getTicket(accessTokenId, AccessToken.class);
assertEquals(principal, accessToken.getAuthentication().getPrincipal());
final int timeLeft = getTimeLeft(body, false, json);
assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
Aggregations