use of org.apereo.cas.authentication.Authentication in project cas by apereo.
the class RequestParameterMultifactorAuthenticationPolicyEventResolver method resolveInternal.
@Override
public Set<Event> resolveInternal(final RequestContext context) {
final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
final Authentication authentication = WebUtils.getAuthentication(context);
if (service == null || authentication == null) {
LOGGER.debug("No service or authentication is available to determine event for principal");
return null;
}
if (StringUtils.isBlank(mfaRequestParameter)) {
LOGGER.debug("No request parameter is defined to trigger multifactor authentication.");
return null;
}
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
final String[] values = request.getParameterValues(mfaRequestParameter);
if (values != null && values.length > 0) {
LOGGER.debug("Received request parameter [{}] as [{}]", mfaRequestParameter, values);
final Map<String, MultifactorAuthenticationProvider> providerMap = WebUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
if (providerMap == null || providerMap.isEmpty()) {
LOGGER.error("No multifactor authentication providers are available in the application context to satisfy [{}]", (Object[]) values);
throw new AuthenticationException();
}
final Optional<MultifactorAuthenticationProvider> providerFound = resolveProvider(providerMap, values[0]);
if (providerFound.isPresent()) {
final MultifactorAuthenticationProvider provider = providerFound.get();
if (provider.isAvailable(service)) {
LOGGER.debug("Attempting to build an event based on the authentication provider [{}] and service [{}]", provider, service.getName());
final Event event = validateEventIdForMatchingTransitionInContext(provider.getId(), context, buildEventAttributeMap(authentication.getPrincipal(), service, provider));
return Collections.singleton(event);
}
LOGGER.warn("Located multifactor provider [{}], yet the provider cannot be reached or verified", providerFound.get());
return null;
} else {
LOGGER.warn("No multifactor provider could be found for request parameter [{}]", (Object[]) values);
throw new AuthenticationException();
}
}
LOGGER.debug("No value could be found for request parameter [{}]", mfaRequestParameter);
return null;
}
use of org.apereo.cas.authentication.Authentication in project cas by apereo.
the class ServiceWarningAction method doExecute.
@Override
protected Event doExecute(final RequestContext context) throws Exception {
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
final Service service = WebUtils.getService(context);
final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);
final Authentication authentication = this.ticketRegistrySupport.getAuthenticationFrom(ticketGrantingTicket);
if (authentication == null) {
throw new InvalidTicketException(new AuthenticationException("No authentication found for ticket " + ticketGrantingTicket), ticketGrantingTicket);
}
final Credential credential = WebUtils.getCredential(context);
final AuthenticationResultBuilder authenticationResultBuilder = authenticationSystemSupport.establishAuthenticationContextFromInitial(authentication, credential);
final AuthenticationResult authenticationResult = authenticationResultBuilder.build(service);
final ServiceTicket serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicket, service, authenticationResult);
WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
if (request.getParameterMap().containsKey("ignorewarn")) {
if (Boolean.valueOf(request.getParameter("ignorewarn").toString())) {
this.warnCookieGenerator.removeCookie(response);
}
}
return new Event(this, CasWebflowConstants.STATE_ID_REDIRECT);
}
use of org.apereo.cas.authentication.Authentication in project cas by apereo.
the class HazelcastTicketRegistryReplicationTests method verifyDeleteTicketWithPGT.
@Test
public void verifyDeleteTicketWithPGT() {
final Authentication a = CoreAuthenticationTestUtils.getAuthentication();
this.hzTicketRegistry1.addTicket(new TicketGrantingTicketImpl(TGT_ID, a, new NeverExpiresExpirationPolicy()));
final TicketGrantingTicket tgt = this.hzTicketRegistry1.getTicket(TGT_ID, TicketGrantingTicket.class);
final Service service = RegisteredServiceTestUtils.getService("TGT_DELETE_TEST");
final ServiceTicket st1 = tgt.grantServiceTicket(ST_ID_1, service, new NeverExpiresExpirationPolicy(), false, true);
this.hzTicketRegistry1.addTicket(st1);
assertNotNull(this.hzTicketRegistry1.getTicket(TGT_ID, TicketGrantingTicket.class));
assertNotNull(this.hzTicketRegistry1.getTicket(ST_ID_1, ServiceTicket.class));
final ProxyGrantingTicket pgt = st1.grantProxyGrantingTicket(PGT_ID_1, a, new NeverExpiresExpirationPolicy());
assertEquals(a, pgt.getAuthentication());
this.hzTicketRegistry1.addTicket(pgt);
this.hzTicketRegistry1.updateTicket(tgt);
assertSame(3, this.hzTicketRegistry1.deleteTicket(tgt.getId()));
assertNull(this.hzTicketRegistry1.getTicket(TGT_ID, TicketGrantingTicket.class));
assertNull(this.hzTicketRegistry1.getTicket(ST_ID_1, ServiceTicket.class));
assertNull(this.hzTicketRegistry1.getTicket(PGT_ID_1, ProxyGrantingTicket.class));
}
use of org.apereo.cas.authentication.Authentication in project cas by apereo.
the class ECPProfileHandlerController method handleEcpRequest.
/**
* Handle ecp request.
*
* @param response the response
* @param request the request
* @param soapContext the soap context
* @param credential the credential
*/
protected void handleEcpRequest(final HttpServletResponse response, final HttpServletRequest request, final MessageContext soapContext, final Credential credential) {
final Envelope envelope = soapContext.getSubcontext(SOAP11Context.class).getEnvelope();
SamlUtils.logSamlObject(configBean, envelope);
final AuthnRequest authnRequest = (AuthnRequest) soapContext.getMessage();
final Pair<AuthnRequest, MessageContext> authenticationContext = Pair.of(authnRequest, soapContext);
try {
final Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> serviceRequest = verifySamlAuthenticationRequest(authenticationContext, request);
final Authentication authentication = authenticateEcpRequest(credential, authenticationContext);
buildSamlResponse(response, request, authenticationContext, buildEcpCasAssertion(authentication, serviceRequest.getKey()));
} catch (final AuthenticationException e) {
LOGGER.error(e.getMessage(), e);
final String error = e.getHandlerErrors().values().stream().map(Class::getSimpleName).collect(Collectors.joining(","));
buildEcpFaultResponse(response, request, Pair.of(authnRequest, error));
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
buildEcpFaultResponse(response, request, Pair.of(authnRequest, e.getMessage()));
}
}
use of org.apereo.cas.authentication.Authentication in project cas by apereo.
the class OAuth20AccessTokenEndpointController method handleRequestInternal.
/**
* Handle request internal model and view.
*
* @param request the request
* @param response the response
* @return the model and view
* @throws Exception the exception
*/
@PostMapping(path = OAuthConstants.BASE_OAUTH20_URL + '/' + OAuthConstants.ACCESS_TOKEN_URL)
public ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
try {
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
if (!verifyAccessTokenRequest(request, response)) {
LOGGER.error("Access token request verification fails");
return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_REQUEST);
}
final String grantType = request.getParameter(OAuthConstants.GRANT_TYPE);
final Service service;
final Authentication authentication;
final boolean generateRefreshToken;
final OAuthRegisteredService registeredService;
final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE) || isGrantType(grantType, OAuth20GrantTypes.REFRESH_TOKEN)) {
final Optional<UserProfile> profile = manager.get(true);
final String clientId = profile.get().getId();
registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
// we generate a refresh token if requested by the service but not from a refresh token
generateRefreshToken = registeredService != null && registeredService.isGenerateRefreshToken() && isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE);
final String parameterName;
if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE)) {
parameterName = OAuthConstants.CODE;
} else {
parameterName = OAuthConstants.REFRESH_TOKEN;
}
final OAuthToken token = getToken(request, parameterName);
if (token == null) {
LOGGER.error("No token found for authorization_code or refresh_token grant types");
return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_GRANT);
}
service = token.getService();
authentication = token.getAuthentication();
} else {
final String clientId = request.getParameter(OAuthConstants.CLIENT_ID);
registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
generateRefreshToken = registeredService != null && registeredService.isGenerateRefreshToken();
try {
// resource owner password grant type
final Optional<OAuthUserProfile> profile = manager.get(true);
if (!profile.isPresent()) {
throw new UnauthorizedServiceException("OAuth user profile cannot be determined");
}
service = createService(registeredService, context);
authentication = createAuthentication(profile.get(), registeredService, context, service);
RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService(service, registeredService, authentication);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_GRANT);
}
}
final AccessToken accessToken = generateAccessToken(service, authentication, context);
RefreshToken refreshToken = null;
if (generateRefreshToken) {
refreshToken = this.refreshTokenFactory.create(service, authentication);
getTicketRegistry().addTicket(refreshToken);
}
LOGGER.debug("access token: [{}] / timeout: [{}] / refresh token: [{}]", accessToken, casProperties.getTicket().getTgt().getTimeToKillInSeconds(), refreshToken);
final String responseType = context.getRequestParameter(OAuthConstants.RESPONSE_TYPE);
final OAuth20ResponseTypes type = Arrays.stream(OAuth20ResponseTypes.values()).filter(t -> t.getType().equalsIgnoreCase(responseType)).findFirst().orElse(OAuth20ResponseTypes.CODE);
this.accessTokenResponseGenerator.generate(request, response, registeredService, service, accessToken, refreshToken, casProperties.getTicket().getTgt().getTimeToKillInSeconds(), type);
getTicketRegistry().addTicket(accessToken);
response.setStatus(HttpServletResponse.SC_OK);
return null;
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
Aggregations