use of org.apereo.cas.authentication.principal.Service in project cas by apereo.
the class DelegatedClientAuthenticationAction method doExecute.
@Override
protected Event doExecute(final RequestContext context) throws Exception {
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
final HttpSession session = request.getSession();
// web context
final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
// get client
final String clientName = request.getParameter(this.clients.getClientNameParameter());
LOGGER.debug("clientName: [{}]", clientName);
if (hasDelegationRequestFailed(request, response.getStatus()).isPresent()) {
return stopWebflow();
}
// it's an authentication
if (StringUtils.isNotBlank(clientName)) {
// get client
final BaseClient<Credentials, CommonProfile> client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
LOGGER.debug("Client: [{}]", client);
// get credentials
final Credentials credentials;
try {
credentials = client.getCredentials(webContext);
LOGGER.debug("Retrieved credentials: [{}]", credentials);
} catch (final Exception e) {
LOGGER.debug("The request requires http action", e);
return stopWebflow();
}
// retrieve parameters from web session
final Service service = (Service) session.getAttribute(CasProtocolConstants.PARAMETER_SERVICE);
context.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, service);
LOGGER.debug("Retrieve service: [{}]", service);
if (service != null) {
request.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
}
restoreRequestAttribute(request, session, this.themeParamName);
restoreRequestAttribute(request, session, this.localParamName);
restoreRequestAttribute(request, session, CasProtocolConstants.PARAMETER_METHOD);
// credentials not null -> try to authenticate
if (credentials != null) {
final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, new ClientCredential(credentials));
final TicketGrantingTicket tgt = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
WebUtils.putTicketGrantingTicketInScopes(context, tgt);
return success();
}
}
// no or aborted authentication : go to login page
prepareForLoginPage(context);
if (response.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
return stopWebflow();
}
if (this.autoRedirect) {
final Set<ProviderLoginPageConfiguration> urls = context.getFlowScope().get(PAC4J_URLS, Set.class);
if (urls != null && urls.size() == 1) {
final ProviderLoginPageConfiguration cfg = urls.stream().findFirst().get();
LOGGER.debug("Auto-redirecting to client url [{}]", cfg.getRedirectUrl());
response.sendRedirect(cfg.getRedirectUrl());
final ExternalContext externalContext = context.getExternalContext();
externalContext.recordResponseComplete();
return stopWebflow();
}
}
return error();
}
use of org.apereo.cas.authentication.principal.Service in project cas by apereo.
the class DelegatedClientAuthenticationActionTests method verifyFinishAuthentication.
@Test
public void verifyFinishAuthentication() throws Exception {
final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
mockRequest.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "FacebookClient");
final MockHttpSession mockSession = new MockHttpSession();
mockSession.setAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME, MY_THEME);
mockSession.setAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME, MY_LOCALE);
mockSession.setAttribute(CasProtocolConstants.PARAMETER_METHOD, MY_METHOD);
final Service service = CoreAuthenticationTestUtils.getService(MY_SERVICE);
mockSession.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service);
mockRequest.setSession(mockSession);
final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);
when(servletExternalContext.getNativeResponse()).thenReturn(new MockHttpServletResponse());
final MockRequestContext mockRequestContext = new MockRequestContext();
mockRequestContext.setExternalContext(servletExternalContext);
final FacebookClient facebookClient = new FacebookClient() {
@Override
protected OAuth20Credentials retrieveCredentials(final WebContext context) throws HttpAction {
return new OAuth20Credentials("fakeVerifier", FacebookClient.class.getSimpleName());
}
};
facebookClient.setName(FacebookClient.class.getSimpleName());
final Clients clients = new Clients(MY_LOGIN_URL, facebookClient);
final TicketGrantingTicket tgt = new TicketGrantingTicketImpl(TGT_ID, mock(Authentication.class), mock(ExpirationPolicy.class));
final CentralAuthenticationService casImpl = mock(CentralAuthenticationService.class);
when(casImpl.createTicketGrantingTicket(any(AuthenticationResult.class))).thenReturn(tgt);
final AuthenticationTransactionManager transManager = mock(AuthenticationTransactionManager.class);
final AuthenticationManager authNManager = mock(AuthenticationManager.class);
when(authNManager.authenticate(any(AuthenticationTransaction.class))).thenReturn(CoreAuthenticationTestUtils.getAuthentication());
when(transManager.getAuthenticationManager()).thenReturn(authNManager);
when(transManager.handle(any(AuthenticationTransaction.class), any(AuthenticationResultBuilder.class))).thenReturn(transManager);
final AuthenticationSystemSupport support = mock(AuthenticationSystemSupport.class);
when(support.getAuthenticationTransactionManager()).thenReturn(transManager);
final DelegatedClientAuthenticationAction action = new DelegatedClientAuthenticationAction(clients, support, casImpl, "theme", "locale", false);
final Event event = action.execute(mockRequestContext);
assertEquals("success", event.getId());
assertEquals(MY_THEME, mockRequest.getAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME));
assertEquals(MY_LOCALE, mockRequest.getAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME));
assertEquals(MY_METHOD, mockRequest.getAttribute(CasProtocolConstants.PARAMETER_METHOD));
assertEquals(MY_SERVICE, mockRequest.getAttribute(CasProtocolConstants.PARAMETER_SERVICE));
final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
final MutableAttributeMap requestScope = mockRequestContext.getRequestScope();
assertEquals(service, flowScope.get(CasProtocolConstants.PARAMETER_SERVICE));
assertEquals(TGT_ID, flowScope.get(TGT_NAME));
assertEquals(TGT_ID, requestScope.get(TGT_NAME));
}
use of org.apereo.cas.authentication.principal.Service in project cas by apereo.
the class OAuth20AccessTokenControllerTests method addRefreshToken.
private RefreshToken addRefreshToken(final Principal principal, final RegisteredService registeredService) {
final Authentication authentication = getAuthentication(principal);
final WebApplicationServiceFactory factory = new WebApplicationServiceFactory();
final Service service = factory.createService(registeredService.getServiceId());
final RefreshToken refreshToken = oAuthRefreshTokenFactory.create(service, authentication);
oAuth20AccessTokenController.getTicketRegistry().addTicket(refreshToken);
return refreshToken;
}
use of org.apereo.cas.authentication.principal.Service in project cas by apereo.
the class WsFederationAction method doExecute.
/**
* Executes the webflow action.
*
* @param context the context
* @return the event
* @throws Exception all unhandled exceptions
*/
@Override
protected Event doExecute(final RequestContext context) throws Exception {
try {
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
final HttpSession session = request.getSession();
final String wa = request.getParameter(WA);
// it's an authentication
if (StringUtils.isNotBlank(wa) && wa.equalsIgnoreCase(WSIGNIN)) {
final String wResult = request.getParameter(WRESULT);
LOGGER.debug("Parameter [{}] received: [{}]", WRESULT, wResult);
if (StringUtils.isBlank(wResult)) {
LOGGER.error("No [{}] parameter is found", WRESULT);
return error();
}
// create credentials
LOGGER.debug("Attempting to create an assertion from the token parameter");
final Assertion assertion = this.wsFederationHelper.parseTokenFromString(wResult, configuration);
if (assertion == null) {
LOGGER.error("Could not validate assertion via parsing the token from [{}]", WRESULT);
return error();
}
LOGGER.debug("Attempting to validate the signature on the assertion");
if (!this.wsFederationHelper.validateSignature(assertion, this.configuration)) {
LOGGER.error("WS Requested Security Token is blank or the signature is not valid.");
return error();
}
try {
final Service service = (Service) session.getAttribute(SERVICE);
LOGGER.debug("Creating credential based on the provided assertion");
final WsFederationCredential credential = this.wsFederationHelper.createCredentialFromToken(assertion);
final String rpId = getRelyingPartyIdentifier(service);
if (credential != null && credential.isValid(rpId, this.configuration.getIdentityProviderIdentifier(), this.configuration.getTolerance())) {
LOGGER.debug("Validated assertion for the created credential successfully");
if (this.configuration.getAttributeMutator() != null) {
LOGGER.debug("Modifying credential attributes based on [{}]", this.configuration.getAttributeMutator().getClass().getSimpleName());
this.configuration.getAttributeMutator().modifyAttributes(credential.getAttributes());
}
} else {
LOGGER.warn("SAML assertions are blank or no longer valid based on RP identifier [{}] and IdP identifier [{}]", rpId, this.configuration.getIdentityProviderIdentifier());
final String url = authorizationUrl + rpId;
context.getFlowScope().put(PROVIDERURL, url);
LOGGER.warn("Created authentication url [{}] and returning error", url);
return error();
}
context.getFlowScope().put(SERVICE, service);
restoreRequestAttribute(request, session, THEME);
restoreRequestAttribute(request, session, LOCALE);
restoreRequestAttribute(request, session, METHOD);
LOGGER.debug("Creating final authentication result based on the given credential");
final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, credential);
LOGGER.debug("Attempting to create a ticket-granting ticket for the authentication result");
WebUtils.putTicketGrantingTicketInScopes(context, this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult));
LOGGER.info("Token validated and new [{}] created: [{}]", credential.getClass().getName(), credential);
return success();
} catch (final AbstractTicketException e) {
LOGGER.error(e.getMessage(), e);
return error();
}
} else {
// no authentication : go to login page. save parameters in web session
final Service service = (Service) context.getFlowScope().get(SERVICE);
if (service != null) {
session.setAttribute(SERVICE, service);
}
saveRequestParameter(request, session, THEME);
saveRequestParameter(request, session, LOCALE);
saveRequestParameter(request, session, METHOD);
final String url = authorizationUrl + getRelyingPartyIdentifier(service);
LOGGER.info("Preparing to redirect to the IdP [{}]", url);
context.getFlowScope().put(PROVIDERURL, url);
}
LOGGER.debug("Returning error event");
return error();
} catch (final Exception ex) {
LOGGER.error(ex.getMessage(), ex);
return error();
}
}
use of org.apereo.cas.authentication.principal.Service in project cas by apereo.
the class DistributedTicketRegistryTests method verifyDeleteTicketWithPGT.
@Test
public void verifyDeleteTicketWithPGT() {
final Authentication a = CoreAuthenticationTestUtils.getAuthentication();
this.ticketRegistry.addTicket(new TicketGrantingTicketImpl(TGT_NAME, a, new NeverExpiresExpirationPolicy()));
final TicketGrantingTicket tgt = this.ticketRegistry.getTicket(TGT_NAME, TicketGrantingTicket.class);
final Service service = CoreAuthenticationTestUtils.getService("TGT_DELETE_TEST");
final ServiceTicket st1 = tgt.grantServiceTicket("ST1", service, new NeverExpiresExpirationPolicy(), true, true);
this.ticketRegistry.addTicket(st1);
assertNotNull(this.ticketRegistry.getTicket(TGT_NAME, TicketGrantingTicket.class));
assertNotNull(this.ticketRegistry.getTicket("ST1", ServiceTicket.class));
final ProxyGrantingTicket pgt = st1.grantProxyGrantingTicket("PGT-1", a, new NeverExpiresExpirationPolicy());
assertEquals(a, pgt.getAuthentication());
this.ticketRegistry.addTicket(pgt);
assertSame(3, this.ticketRegistry.deleteTicket(tgt.getId()));
assertNull(this.ticketRegistry.getTicket(TGT_NAME, TicketGrantingTicket.class));
assertNull(this.ticketRegistry.getTicket("ST1", ServiceTicket.class));
assertNull(this.ticketRegistry.getTicket("PGT-1", ProxyGrantingTicket.class));
}
Aggregations