org.jasig.cas.authentication.principal.Service Java Examples

The following examples show how to use org.jasig.cas.authentication.principal.Service. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenIdSingleSignOnAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String userName = this.extractor
            .extractLocalUsernameFromUri(context.getRequestParameters()
                    .get("openid.identity"));
    final Service service = WebUtils.getService(context);

    context.getExternalContext().getSessionMap().put("openIdLocalId", userName);

    // clear the service because otherwise we can fake the username
    if (service instanceof OpenIdService && userName == null) {
        context.getFlowScope().remove("service");
    }

    if (ticketGrantingTicketId == null || userName == null) {
        return null;
    }

    return new OpenIdCredential(
            ticketGrantingTicketId, userName);
}
 
Example #2
Source File: AbstractCasAttributeEncoder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public final Map<String, Object> encodeAttributes(final Map<String, Object> attributes,
                                                  final Service service) {
    logger.debug("Starting to encode attributes for release to service [{}]", service);
    final Map<String, Object> newEncodedAttributes = new HashMap<>(attributes);
    final Map<String, String> cachedAttributesToEncode = initialize(newEncodedAttributes);

    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    if (registeredService != null && registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        encodeAttributesInternal(newEncodedAttributes, cachedAttributesToEncode,
                this.cipherExecutor, registeredService);
        logger.debug("[{}] Encoded attributes are available for release to [{}]",
                newEncodedAttributes.size(), service);
    } else {
        logger.debug("Service [{}] is not found and/or enabled in the service registry. "
                + "No encoding has taken place.", service);
    }

    return newEncodedAttributes;
}
 
Example #3
Source File: CentralAuthenticationServiceImplTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateServiceTicketWithInvalidUsernameAttribute() throws Exception {
    final UsernamePasswordCredential cred =  TestUtils.getCredentialsWithSameUsernameAndPassword();
    final String ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(cred);

    final Service svc = TestUtils.getService("eduPersonTestInvalid");
    final String serviceTicket = getCentralAuthenticationService().grantServiceTicket(ticketGrantingTicket, svc);

    final Assertion assertion = getCentralAuthenticationService().validateServiceTicket(serviceTicket, svc);
    final Authentication auth = assertion.getPrimaryAuthentication();

    /*
     * The attribute specified for this service does not resolve.
     * Therefore, we expect the default to be returned.
     */
    assertEquals(auth.getPrincipal().getId(), cred.getUsername());
}
 
Example #4
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // save parameters in web session
    final Service service = (Service) context.getFlowScope().get(SERVICE);
    logger.info("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.info("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example #5
Source File: CentralAuthenticationServiceImpl.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Audit(
    action="SERVICE_TICKET",
    actionResolverName="GRANT_SERVICE_TICKET_RESOLVER",
    resourceResolverName="GRANT_SERVICE_TICKET_RESOURCE_RESOLVER")
@Timed(name = "GRANT_SERVICE_TICKET_TIMER")
@Metered(name="GRANT_SERVICE_TICKET_METER")
@Counted(name="GRANT_SERVICE_TICKET_COUNTER", monotonic=true)
@Override
public ServiceTicket grantServiceTicket(final String ticketGrantingTicketId,
    final Service service) throws TicketException {
    try {
        return this.grantServiceTicket(ticketGrantingTicketId, service, (Credential[]) null);
    } catch (final AuthenticationException e) {
        throw new IllegalStateException("Unexpected authentication exception", e);
    }
}
 
Example #6
Source File: ImmutableAssertion.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance with required parameters.
 *
 * @param primary Primary authentication.
 * @param chained Chained authentitications.
 * @param service The service we are asserting this ticket for.
 * @param fromNewLogin True if the ticket was issued as a result of authentication, false otherwise.
 *
 * @throws IllegalArgumentException If any of the given arguments do not meet requirements.
 */
public ImmutableAssertion(
        final Authentication primary,
        final List<Authentication> chained,
        final Service service,
        final boolean fromNewLogin) {

    Assert.notNull(primary, "primary authentication cannot be null");
    Assert.notNull(chained, "chained authentications cannot be null");
    Assert.notNull(service, "service cannot be null");
    Assert.notEmpty(chained, "chained authentications cannot be empty");

    this.primaryAuthentication = primary;
    this.chainedAuthentications = chained;
    this.service = service;
    this.fromNewLogin = fromNewLogin;
}
 
Example #7
Source File: PrincipalAttributeRegisteredServiceUsernameProvider.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public String resolveUsername(final Principal principal, final Service service) {
    String principalId = principal.getId();
    
    if (principal.getAttributes().containsKey(this.usernameAttribute)) {
        principalId = principal.getAttributes().get(this.usernameAttribute).toString();
    } else {
        logger.warn("Principal [{}] did not have attribute [{}] among attributes [{}] so CAS cannot "
                + "provide the user attribute the service expects. "
                + "CAS will instead return the default principal id [{}]",
                principalId,
                this.usernameAttribute,
                principal.getAttributes(),
                principalId);
    }
    
    logger.debug("Principal id to return is [{}]. The default principal id is [{}].",
            principalId, principal.getId());
    return principalId;
}
 
Example #8
Source File: GenerateServiceTicketAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) {
    final Service service = WebUtils.getService(context);
    final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);

    try {
        final String serviceTicketId = this.centralAuthenticationService
            .grantServiceTicket(ticketGrantingTicket,
                service);
        WebUtils.putServiceTicketInRequestScope(context,
            serviceTicketId);
        return success();
    } catch (final TicketException e) {
        if (isGatewayPresent(context)) {
            return result("gateway");
        }
    }

    return error();
}
 
Example #9
Source File: AbstractServiceValidateControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyValidServiceTicketAndPgtUrlMismatch() throws Exception {
    final TicketGrantingTicket tId = getCentralAuthenticationService()
            .createTicketGrantingTicket(TestUtils.getCredentialsWithSameUsernameAndPassword());
    
    final Service svc = TestUtils.getService("proxyService");
    final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), svc);

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", svc.getId());
    request.addParameter("ticket", sId.getId());
    request.addParameter("pgtUrl", "http://www.github.com");
    
    final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse());
    assertEquals(ServiceValidateController.DEFAULT_SERVICE_FAILURE_VIEW_NAME, modelAndView.getViewName());
    assertNull(modelAndView.getModel().get("pgtIou"));
}
 
Example #10
Source File: AuthenticationViaFormAction.java    From taoshop with Apache License 2.0 5 votes vote down vote up
/**
 * Is request asking for service ticket?
 *
 * @param context the context
 * @return true, if both service and tgt are found, and the request is not asking to renew.
 * @since 4.1.0
 */
protected boolean isRequestAskingForServiceTicket(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final Service service = WebUtils.getService(context);
    return (StringUtils.isNotBlank(context.getRequestParameters().get(CasProtocolConstants.PARAMETER_RENEW))
            && ticketGrantingTicketId != null
            && service != null);
}
 
Example #11
Source File: ServiceTicketImplTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGetTicket() {
    final Service simpleService = TestUtils.getService();
    final ServiceTicket s = new ServiceTicketImpl("stest1", this.ticketGrantingTicket, simpleService, false,
            new NeverExpiresExpirationPolicy());
    assertEquals(this.ticketGrantingTicket, s.getGrantingTicket());
}
 
Example #12
Source File: ServiceTicketImplTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGetService() {
    final Service simpleService = TestUtils.getService();
    final ServiceTicket s = new ServiceTicketImpl("stest1", this.ticketGrantingTicket, simpleService, false,
            new NeverExpiresExpirationPolicy());
    assertEquals(simpleService, s.getService());
}
 
Example #13
Source File: DefaultServicesManagerImpl.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RegisteredService findServiceBy(final Service service) {
    final Collection<RegisteredService> c = convertToTreeSet();

    for (final RegisteredService r : c) {
        if (r.matches(service)) {
            return r;
        }
    }

    return null;
}
 
Example #14
Source File: CentralAuthenticationServiceImpl.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Audit(
    action="SERVICE_TICKET",
    actionResolverName="GRANT_SERVICE_TICKET_RESOLVER",
    resourceResolverName="GRANT_SERVICE_TICKET_RESOURCE_RESOLVER")
@Profiled(tag = "GRANT_SERVICE_TICKET", logFailuresSeparately = false)
@Transactional(readOnly = false)
public String grantServiceTicket(final String ticketGrantingTicketId,
    final Service service) throws TicketException {
    try {
        return this.grantServiceTicket(ticketGrantingTicketId, service, null);
    } catch (final AuthenticationException e) {
        throw new IllegalStateException("Unexpected authentication exception", e);
    }
}
 
Example #15
Source File: RegexRegisteredServiceTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testMatches() throws Exception {
    final Service testService;
    if (serviceToMatch == null) {
        testService = null;
    } else {
        testService = new MockService(serviceToMatch);
    }
    assertEquals(expected, service.matches(testService));
}
 
Example #16
Source File: ServiceResourceResolver.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public String[] resolveFrom(final JoinPoint joinPoint, final Object retval) {
    final Service service = (Service) AopUtils.unWrapJoinPoint(joinPoint).getArgs()[1];
    final StringBuilder builder = new StringBuilder(retval.toString());
    builder.append(" for ");
    builder.append(service.getId());

    return new String[] {builder.toString()};
}
 
Example #17
Source File: InitialFlowSetupActionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.warnCookieGenerator = new CookieRetrievingCookieGenerator();
    this.tgtCookieGenerator = new CookieRetrievingCookieGenerator();
    this.action.setTicketGrantingTicketCookieGenerator(this.tgtCookieGenerator);
    this.action.setWarnCookieGenerator(this.warnCookieGenerator);
    final ArgumentExtractor[] argExtractors = new ArgumentExtractor[] {new CasArgumentExtractor()};
    this.action.setArgumentExtractors(Arrays.asList(argExtractors));

    this.servicesManager = mock(ServicesManager.class);
    when(this.servicesManager.findServiceBy(any(Service.class))).thenReturn(TestUtils.getRegisteredService("test"));
    this.action.setServicesManager(this.servicesManager);

    this.action.afterPropertiesSet();
}
 
Example #18
Source File: SamlArgumentExtractorTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testObtainService() {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("TARGET", "test");
    final Service service = this.extractor.extractService(request);
    assertEquals("test", service.getId());
}
 
Example #19
Source File: MultiFactorAwareCentralAuthenticationService.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Audit(
        action="SERVICE_TICKET",
        actionResolverName="GRANT_SERVICE_TICKET_RESOLVER",
        resourceResolverName="GRANT_SERVICE_TICKET_RESOURCE_RESOLVER")
@Timed(name = "GRANT_SERVICE_TICKET_TIMER")
@Metered(name="GRANT_SERVICE_TICKET_METER")
@Counted(name="GRANT_SERVICE_TICKET_COUNTER", monotonic=true)
@Override
public ServiceTicket grantServiceTicket(final String ticketGrantingTicketId,
                                        final Service service) throws TicketException {
    return this.delegate.grantServiceTicket(ticketGrantingTicketId, service);
}
 
Example #20
Source File: MockTicketGrantingTicket.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public ServiceTicket grantServiceTicket(
        final String id,
        final Service service,
        final ExpirationPolicy expirationPolicy,
        final boolean credentialsProvided) {
    usageCount++;
    return new MockServiceTicket(id, service, this);
}
 
Example #21
Source File: CentralAuthenticationServiceImplTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyValidateServiceTicketReturnOnlyAllowedAttribute() throws Exception {
    final Service service = TestUtils.getService("eduPersonTestInvalid");
    final UsernamePasswordCredential cred =  TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(cred);
    final ServiceTicket serviceTicket = getCentralAuthenticationService().grantServiceTicket(ticketGrantingTicket.getId(),
            service);

    final Assertion assertion = getCentralAuthenticationService().validateServiceTicket(serviceTicket.getId(),
            service);
    final Authentication auth = assertion.getPrimaryAuthentication();
    final Map<String, Object> attributes = auth.getPrincipal().getAttributes();
    assertEquals(1, attributes.size());
    assertEquals("adopters", attributes.get("groupMembership"));
}
 
Example #22
Source File: GatewayServicesManagementCheck.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final Service service = WebUtils.getService(context);

    final boolean match = this.servicesManager.matchesExistingService(service);

    if (match) {
        return success();
    }

    final String msg = String.format("ServiceManagement: Unauthorized Service Access. "
            + "Service [%s] does not match entries in service registry.", service.getId());
    logger.warn(msg);
    throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
 
Example #23
Source File: DefaultCasAttributeEncoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void checkNoPublicKeyDefined() {
    final Service service = TestUtils.getService("testDefault");
    final CasAttributeEncoder encoder = new DefaultCasAttributeEncoder(this.servicesManager);
    final Map<String, Object> encoded = encoder.encodeAttributes(this.attributes, service);
    assertEquals(encoded.size(), this.attributes.size() - 2);
}
 
Example #24
Source File: ConfigurableUserAgentOverrideThemeResolver.java    From uPortal-start with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve the theme for the service. This method's logic is taken from ServiceThemeResolver.
 *
 * @param request
 * @return configured theme for this service
 */
protected String resolveServiceThemeName(HttpServletRequest request) {
    if (this.servicesManager == null) {
        return getDefaultThemeName();
    }

    final Service service = WebUtils.getService(this.argumentExtractors, request);

    final RegisteredService rService = this.servicesManager.findServiceBy(service);

    return service != null && rService != null && StringUtils.hasText(rService.getTheme())
            ? rService.getTheme()
            : getDefaultThemeName();
}
 
Example #25
Source File: RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractorTests.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceWithDefaultMfaAttribute() {
    final List<ArgumentExtractor> set = new ArrayList<>();
    set.add(new CasArgumentExtractor());
    
    final MultiFactorWebApplicationServiceFactory factory = mock(MultiFactorWebApplicationServiceFactory.class);
    when(factory.create(anyString(), anyString(), anyString(), any(Response.ResponseType.class),
            anyString(), any(AuthenticationMethodSource.class)))
        .thenReturn(getMfaService());
    
    final AuthenticationMethodVerifier verifier = mock(AuthenticationMethodVerifier.class);

    final RegisteredService svc = TestUtils.getRegisteredService(CAS_SERVICE);
    final DefaultRegisteredServiceProperty prop = new DefaultRegisteredServiceProperty();
    prop.setValues(Collections.singleton(CAS_AUTHN_METHOD));
    svc.getProperties().put(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD, prop);
    
    final ServicesManager mgmr = mock(ServicesManager.class);
    when(mgmr.findServiceBy(anyInt())).thenReturn(svc);
    when(mgmr.findServiceBy(any(Service.class))).thenReturn(svc);
    
    final RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractor extractor = 
            new RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractor(set, factory, mgmr, verifier);

    final MultiFactorAuthenticationSupportingWebApplicationService webSvc =
            (MultiFactorAuthenticationSupportingWebApplicationService) extractor.extractService(getRequest());
    assertNotNull(webSvc);
    assertEquals(webSvc.getAuthenticationMethod(), CAS_AUTHN_METHOD);
}
 
Example #26
Source File: CentralAuthenticationServiceImplTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateServiceTicketNoAttributesReturned() throws Exception {
    final Service service = TestUtils.getService();
    final UsernamePasswordCredential cred =  TestUtils.getCredentialsWithSameUsernameAndPassword();
    final String ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(cred);
    final String serviceTicket = getCentralAuthenticationService().grantServiceTicket(ticketGrantingTicket,
            service);

    final Assertion assertion = getCentralAuthenticationService().validateServiceTicket(serviceTicket,
            service);
    final Authentication auth = assertion.getPrimaryAuthentication();
    assertEquals(0, auth.getPrincipal().getAttributes().size());
}
 
Example #27
Source File: RegisteredServiceImplTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testMatches() throws Exception {
    final Service testService;
    if (serviceToMatch == null) {
        testService = null;
    } else {
        testService = new MockService(serviceToMatch);
    }
    assertEquals(expected, service.matches(testService));
}
 
Example #28
Source File: RegisteredServiceImplTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyMatches() throws Exception {
    final Service testService;
    if (serviceToMatch == null) {
        testService = null;
    } else {
        testService = new MockService(serviceToMatch);
    }
    assertEquals(expected, service.matches(testService));
}
 
Example #29
Source File: InitialFlowSetupAction.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

    final String contextPath = context.getExternalContext().getContextPath();
    final String cookiePath = StringUtils.hasText(contextPath) ? contextPath + '/' : "/";

    if (!StringUtils.hasText(warnCookieGenerator.getCookiePath())) {
        logger.info("Setting path for cookies for warn cookie generator to: " + cookiePath);
        this.warnCookieGenerator.setCookiePath(cookiePath);
    } else {
        logger.debug("Warning cookie domain is set to " + warnCookieGenerator.getCookieDomain()
                + " and path " +  warnCookieGenerator.getCookiePath());
    }
    if (!StringUtils.hasText(ticketGrantingTicketCookieGenerator.getCookiePath())) {
        logger.info("Setting path for cookies for TGC cookie generator to: " + cookiePath);
        this.ticketGrantingTicketCookieGenerator.setCookiePath(cookiePath);
    } else {
        logger.debug("TGC cookie domain is set to " + ticketGrantingTicketCookieGenerator.getCookieDomain()
                + " and path " +  ticketGrantingTicketCookieGenerator.getCookiePath());
    }

    context.getFlowScope().put(
        "ticketGrantingTicketId", this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
    context.getFlowScope().put(
        "warnCookieValue",
        Boolean.valueOf(this.warnCookieGenerator.retrieveCookieValue(request)));

    final Service service = WebUtils.getService(this.argumentExtractors,
        context);

    if (service != null && logger.isDebugEnabled()) {
        logger.debug("Placing service in FlowScope: " + service.getId());
    }

    context.getFlowScope().put("service", service);

    return result("success");
}
 
Example #30
Source File: CentralAuthenticationServiceImplTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyValidateServiceTicketWithUsernameAttribute() throws Exception {
    final UsernamePasswordCredential cred =  TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(cred);

    final Service svc = TestUtils.getService("eduPersonTest");
    final ServiceTicket serviceTicket = getCentralAuthenticationService().grantServiceTicket(ticketGrantingTicket.getId(), svc);

    final Assertion assertion = getCentralAuthenticationService().validateServiceTicket(serviceTicket.getId(), svc);
    assertEquals("developer", assertion.getPrimaryAuthentication().getPrincipal().getId());
}