Java Code Examples for org.jasig.cas.ticket.TicketGrantingTicket#grantServiceTicket()

The following examples show how to use org.jasig.cas.ticket.TicketGrantingTicket#grantServiceTicket() . 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: DistributedTicketRegistryTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyUpdateOfRegistry() {
    final TicketGrantingTicket t = new TicketGrantingTicketImpl("test", TestUtils.getAuthentication(),
            new NeverExpiresExpirationPolicy());
    this.ticketRegistry.addTicket(t);
    final TicketGrantingTicket returned = (TicketGrantingTicket) this.ticketRegistry.getTicket("test");

    final ServiceTicket s = returned.grantServiceTicket("test2", TestUtils.getService(),
            new NeverExpiresExpirationPolicy(), true);

    this.ticketRegistry.addTicket(s);
    final ServiceTicket s2 = (ServiceTicket) this.ticketRegistry.getTicket("test2");
    assertNotNull(s2.grantTicketGrantingTicket("ff", TestUtils.getAuthentication(),
            new NeverExpiresExpirationPolicy()));

    assertTrue(s2.isValidFor(TestUtils.getService()));
    assertTrue(this.wasTicketUpdated);

    returned.markTicketExpired();
    assertTrue(t.isExpired());
}
 
Example 2
Source File: DistributedTicketRegistryTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateOfRegistry() {
    final TicketGrantingTicket t = new TicketGrantingTicketImpl("test", TestUtils.getAuthentication(),
            new NeverExpiresExpirationPolicy());
    this.ticketRegistry.addTicket(t);
    final TicketGrantingTicket returned = (TicketGrantingTicket) this.ticketRegistry.getTicket("test");

    final ServiceTicket s = returned.grantServiceTicket("test2", TestUtils.getService(),
            new NeverExpiresExpirationPolicy(), true);

    this.ticketRegistry.addTicket(s);
    final ServiceTicket s2 = (ServiceTicket) this.ticketRegistry.getTicket("test2");
    assertNotNull(s2.grantTicketGrantingTicket("ff", TestUtils.getAuthentication(),
            new NeverExpiresExpirationPolicy()));

    assertTrue(s2.isValidFor(TestUtils.getService()));
    assertTrue(this.wasTicketUpdated);

    returned.markTicketExpired();
    assertTrue(t.isExpired());
}
 
Example 3
Source File: JpaTicketRegistryTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
static ServiceTicket newST(final TicketGrantingTicket parent) {
   return parent.grantServiceTicket(
           ID_GENERATOR.getNewTicketId("ST"),
           new MockService("https://service.example.com"),
           EXP_POLICY_ST,
           false);
}
 
Example 4
Source File: JBossCacheTicketRegistryTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTicketsFromRegistryEqualToTicketsAdded() {
    final Collection<Ticket> tickets = new ArrayList<Ticket>();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", "test");

    for (int i = 0; i < TICKETS_IN_REGISTRY; i++) {
        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
                "TEST" + i, TestUtils.getAuthentication(),
                new NeverExpiresExpirationPolicy());
        final ServiceTicket st = ticketGrantingTicket.grantServiceTicket(
                "tests" + i, SimpleWebApplicationServiceImpl.createServiceFrom(request),
                new NeverExpiresExpirationPolicy(), false);
        tickets.add(ticketGrantingTicket);
        tickets.add(st);
        this.ticketRegistry.addTicket(ticketGrantingTicket);
        this.ticketRegistry.addTicket(st);
    }

    try {
        Collection<Ticket> ticketRegistryTickets = this.ticketRegistry.getTickets();
        assertEquals(
                "The size of the registry is not the same as the collection.",
                ticketRegistryTickets.size(), tickets.size());

        for (final Ticket ticket : tickets) {
            if (!ticketRegistryTickets.contains(ticket)) {
                fail("Ticket was added to registry but was not found in retrieval of collection of all tickets.");
            }
        }
    } catch (final Exception e) {
        fail("Caught an exception. But no exception should have been thrown.");
    }
}
 
Example 5
Source File: KryoTranscoderTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeDecode() throws Exception {
    final ServiceTicket expectedST =
            new MockServiceTicket(ST_ID);
    assertEquals(expectedST, transcoder.decode(transcoder.encode(expectedST)));

    final Credential userPassCredential = new UsernamePasswordCredential("handymanbob", "foo");
    final TicketGrantingTicket expectedTGT =
            new MockTicketGrantingTicket(TGT_ID, userPassCredential);
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));

    internalProxyTest("http://localhost");
    internalProxyTest("https://localhost:8080/path/file.html?p1=v1&p2=v2#fragment");
}
 
Example 6
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecodeTGTWithSingletonMap() throws Exception {
    final Map<String, Object> newAttributes = Collections.singletonMap(NICKNAME_KEY, (Object) NICKNAME_VALUE);
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final TicketGrantingTicket expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes);
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));
}
 
Example 7
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecodeTGTWithSingleton() throws Exception {
    final Map<String, Object> newAttributes = new HashMap<>();
    newAttributes.put(NICKNAME_KEY, Collections.singleton(NICKNAME_VALUE));
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final TicketGrantingTicket expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes);
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));
}
 
Example 8
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecodeTGTWithUnmodifiableSet() throws Exception {
    final Map<String, Object> newAttributes = new HashMap<>();
    final Set<String> values = new HashSet<>();
    values.add(NICKNAME_VALUE);
    newAttributes.put(NICKNAME_KEY, Collections.unmodifiableSet(values));
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final TicketGrantingTicket expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes);
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));
}
 
Example 9
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecodeTGTWithListOrderedMap() throws Exception {
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    @SuppressWarnings("unchecked")
    final TicketGrantingTicket expectedTGT =
            new MockTicketGrantingTicket(TGT_ID, userPassCredential, ListOrderedMap.listOrderedMap(this.principalAttributes));
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));
}
 
Example 10
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecodeTGTWithLinkedHashMap() throws Exception {
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final TicketGrantingTicket expectedTGT =
            new MockTicketGrantingTicket(TGT_ID, userPassCredential, new LinkedHashMap<String, Object>(this.principalAttributes));
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));
}
 
Example 11
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecodeTGTWithUnmodifiableList() throws Exception {
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final List<String> values = new ArrayList<>();
    values.add(NICKNAME_VALUE);
    final Map<String, Object> newAttributes = new HashMap<>();
    newAttributes.put(NICKNAME_KEY, Collections.unmodifiableList(values));
    final TicketGrantingTicket expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes);
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));
}
 
Example 12
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecodeTGTWithUnmodifiableMap() throws Exception {
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final TicketGrantingTicket expectedTGT =
            new MockTicketGrantingTicket(TGT_ID, userPassCredential, Collections.unmodifiableMap(this.principalAttributes));
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));
}
 
Example 13
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
private void internalProxyTest(final String proxyUrl) throws MalformedURLException {
    final RegisteredServiceImpl svc = new RegisteredServiceImpl();
    svc.setServiceId("https://some.app.edu");
    final Credential proxyCredential = new HttpBasedServiceCredential(new URL(proxyUrl), svc);
    final TicketGrantingTicket expectedTGT = new MockTicketGrantingTicket(TGT_ID, proxyCredential, this.principalAttributes);
    expectedTGT.grantServiceTicket(ST_ID, null, null, false);
    assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT)));        
}
 
Example 14
Source File: DistributedTicketRegistryTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testProxiedInstancesEqual() {
    final TicketGrantingTicket t = new TicketGrantingTicketImpl("test", TestUtils.getAuthentication(),
            new NeverExpiresExpirationPolicy());
    this.ticketRegistry.addTicket(t);

    final TicketGrantingTicket returned = (TicketGrantingTicket) this.ticketRegistry.getTicket("test");
    assertEquals(t, returned);
    assertEquals(returned, t);

    assertEquals(t.getCreationTime(), returned.getCreationTime());
    assertEquals(t.getAuthentication(), returned.getAuthentication());
    assertEquals(t.getCountOfUses(), returned.getCountOfUses());
    assertEquals(t.getGrantingTicket(), returned.getGrantingTicket());
    assertEquals(t.getId(), returned.getId());
    assertEquals(t.getChainedAuthentications(), returned.getChainedAuthentications());
    assertEquals(t.isExpired(), returned.isExpired());
    assertEquals(t.isRoot(), returned.isRoot());

    final ServiceTicket s = t.grantServiceTicket("stest", TestUtils.getService(),
            new NeverExpiresExpirationPolicy(), false);
    this.ticketRegistry.addTicket(s);

    final ServiceTicket sreturned = (ServiceTicket) this.ticketRegistry.getTicket("stest");
    assertEquals(s, sreturned);
    assertEquals(sreturned, s);

    assertEquals(s.getCreationTime(), sreturned.getCreationTime());
    assertEquals(s.getCountOfUses(), sreturned.getCountOfUses());
    assertEquals(s.getGrantingTicket(), sreturned.getGrantingTicket());
    assertEquals(s.getId(), sreturned.getId());
    assertEquals(s.isExpired(), sreturned.isExpired());
    assertEquals(s.getService(), sreturned.getService());
    assertEquals(s.isFromNewLogin(), sreturned.isFromNewLogin());
}
 
Example 15
Source File: AbstractTicketRegistryTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGetTicketsFromRegistryEqualToTicketsAdded() {
    final Collection<Ticket> tickets = new ArrayList<>();

    for (int i = 0; i < TICKETS_IN_REGISTRY; i++) {
        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl("TEST" + i,
                TestUtils.getAuthentication(), new NeverExpiresExpirationPolicy());
        final ServiceTicket st = ticketGrantingTicket.grantServiceTicket("tests" + i, TestUtils.getService(),
                new NeverExpiresExpirationPolicy(), false);
        tickets.add(ticketGrantingTicket);
        tickets.add(st);
        this.ticketRegistry.addTicket(ticketGrantingTicket);
        this.ticketRegistry.addTicket(st);
    }

    try {
        final Collection<Ticket> ticketRegistryTickets = this.ticketRegistry.getTickets();
        assertEquals("The size of the registry is not the same as the collection.", ticketRegistryTickets.size(),
                tickets.size());

        for (final Ticket ticket : tickets) {
            if (!ticketRegistryTickets.contains(ticket)) {
                fail("Ticket was added to registry but was not found in retrieval of collection of all tickets.");
            }
        }
    } catch (final Exception e) {
        fail("Caught an exception. But no exception should have been thrown.");
    }
}
 
Example 16
Source File: DistributedTicketRegistryTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyProxiedInstancesEqual() {
    final TicketGrantingTicket t = new TicketGrantingTicketImpl("test", TestUtils.getAuthentication(),
            new NeverExpiresExpirationPolicy());
    this.ticketRegistry.addTicket(t);

    final TicketGrantingTicket returned = (TicketGrantingTicket) this.ticketRegistry.getTicket("test");
    assertEquals(t, returned);
    assertEquals(returned, t);

    assertEquals(t.getCreationTime(), returned.getCreationTime());
    assertEquals(t.getAuthentication(), returned.getAuthentication());
    assertEquals(t.getCountOfUses(), returned.getCountOfUses());
    assertEquals(t.getGrantingTicket(), returned.getGrantingTicket());
    assertEquals(t.getId(), returned.getId());
    assertEquals(t.getChainedAuthentications(), returned.getChainedAuthentications());
    assertEquals(t.isExpired(), returned.isExpired());
    assertEquals(t.isRoot(), returned.isRoot());

    final ServiceTicket s = t.grantServiceTicket("stest", TestUtils.getService(),
            new NeverExpiresExpirationPolicy(), false);
    this.ticketRegistry.addTicket(s);

    final ServiceTicket sreturned = (ServiceTicket) this.ticketRegistry.getTicket("stest");
    assertEquals(s, sreturned);
    assertEquals(sreturned, s);

    assertEquals(s.getCreationTime(), sreturned.getCreationTime());
    assertEquals(s.getCountOfUses(), sreturned.getCountOfUses());
    assertEquals(s.getGrantingTicket(), sreturned.getGrantingTicket());
    assertEquals(s.getId(), sreturned.getId());
    assertEquals(s.isExpired(), sreturned.isExpired());
    assertEquals(s.getService(), sreturned.getService());
    assertEquals(s.isFromNewLogin(), sreturned.isFromNewLogin());
}
 
Example 17
Source File: JBossCacheTicketRegistryTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGetTicketsFromRegistryEqualToTicketsAdded() {
    final Collection<Ticket> tickets = new ArrayList<>();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", "test");

    for (int i = 0; i < TICKETS_IN_REGISTRY; i++) {
        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
                "TEST" + i, TestUtils.getAuthentication(),
                new NeverExpiresExpirationPolicy());
        final ServiceTicket st = ticketGrantingTicket.grantServiceTicket(
                "tests" + i, SimpleWebApplicationServiceImpl.createServiceFrom(request),
                new NeverExpiresExpirationPolicy(), false);
        tickets.add(ticketGrantingTicket);
        tickets.add(st);
        this.ticketRegistry.addTicket(ticketGrantingTicket);
        this.ticketRegistry.addTicket(st);
    }

    try {
        final Collection<Ticket> ticketRegistryTickets = this.ticketRegistry.getTickets();
        assertEquals(
                "The size of the registry is not the same as the collection.",
                ticketRegistryTickets.size(), tickets.size());

        for (final Ticket ticket : tickets) {
            if (!ticketRegistryTickets.contains(ticket)) {
                fail("Ticket was added to registry but was not found in retrieval of collection of all tickets.");
            }
        }
    } catch (final Exception e) {
        fail("Caught an exception. But no exception should have been thrown.");
    }
}
 
Example 18
Source File: JpaTicketRegistryTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
static ServiceTicket newST(final TicketGrantingTicket parent) {
   return parent.grantServiceTicket(
           ID_GENERATOR.getNewTicketId("ST"),
           new MockService("https://service.example.com"),
           EXP_POLICY_ST,
           false);
}
 
Example 19
Source File: CentralAuthenticationServiceImpl.java    From springboot-shiro-cas-mybatis with MIT License 4 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, final Credential... credentials)
        throws AuthenticationException, TicketException {

    final TicketGrantingTicket ticketGrantingTicket = getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    verifyRegisteredServiceProperties(registeredService, service);
    final Set<Credential> sanitizedCredentials = sanitizeCredentials(credentials);

    Authentication currentAuthentication = null;
    if (sanitizedCredentials.size() > 0) {
        currentAuthentication = this.authenticationManager.authenticate(
                sanitizedCredentials.toArray(new Credential[] {}));
        final Authentication original = ticketGrantingTicket.getAuthentication();
        if (!currentAuthentication.getPrincipal().equals(original.getPrincipal())) {
            throw new MixedPrincipalException(
                    currentAuthentication, currentAuthentication.getPrincipal(), original.getPrincipal());
        }
        ticketGrantingTicket.getSupplementalAuthentications().add(currentAuthentication);
    }

    if (currentAuthentication == null && !registeredService.getAccessStrategy().isServiceAccessAllowedForSso()) {
        logger.warn("ServiceManagement: Service [{}] is not allowed to use SSO.", service.getId());
        throw new UnauthorizedSsoServiceException();
    }

    final Service proxiedBy = ticketGrantingTicket.getProxiedBy();
    if (proxiedBy != null) {
        logger.debug("TGT is proxied by [{}]. Locating proxy service in registry...", proxiedBy.getId());
        final RegisteredService proxyingService = servicesManager.findServiceBy(proxiedBy);

        if (proxyingService != null) {
            logger.debug("Located proxying service [{}] in the service registry", proxyingService);
            if (!proxyingService.getProxyPolicy().isAllowedToProxy()) {
                logger.warn("Found proxying service {}, but it is not authorized to fulfill the proxy attempt made by {}",
                        proxyingService.getId(), service.getId());
                throw new UnauthorizedProxyingException("Proxying is not allowed for registered service "
                        + registeredService.getId());
            }
        } else {
            logger.warn("No proxying service found. Proxy attempt by service [{}] (registered service [{}]) is not allowed.",
                    service.getId(), registeredService.getId());
            throw new UnauthorizedProxyingException("Proxying is not allowed for registered service "
                    + registeredService.getId());
        }
    } else {
        logger.trace("TGT is not proxied by another service");
    }

    // Perform security policy check by getting the authentication that satisfies the configured policy
    // This throws if no suitable policy is found
    getAuthenticationSatisfiedByPolicy(ticketGrantingTicket, new ServiceContext(service, registeredService));

    final List<Authentication> authentications = ticketGrantingTicket.getChainedAuthentications();
    final Principal principal = authentications.get(authentications.size() - 1).getPrincipal();

    final Map<String, Object> principalAttrs = registeredService.getAttributeReleasePolicy().getAttributes(principal);
    if (!registeredService.getAccessStrategy().doPrincipalAttributesAllowServiceAccess(principalAttrs)) {
        logger.warn("ServiceManagement: Cannot grant service ticket because Service [{}] is not authorized for use by [{}].",
                service.getId(), principal);
        throw new UnauthorizedServiceForPrincipalException();
    }

    final String uniqueTicketIdGenKey = service.getClass().getName();
    logger.debug("Looking up service ticket id generator for [{}]", uniqueTicketIdGenKey);
    UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator =
            this.uniqueTicketIdGeneratorsForService.get(uniqueTicketIdGenKey);
    if (serviceTicketUniqueTicketIdGenerator == null) {
        serviceTicketUniqueTicketIdGenerator = this.defaultServiceTicketIdGenerator;
        logger.debug("Service ticket id generator not found for [{}]. Using the default generator...",
                uniqueTicketIdGenKey);
    }

    final String ticketPrefix = authentications.size() == 1 ? ServiceTicket.PREFIX : ServiceTicket.PROXY_TICKET_PREFIX;
    final String ticketId = serviceTicketUniqueTicketIdGenerator.getNewTicketId(ticketPrefix);
    final ServiceTicket serviceTicket = ticketGrantingTicket.grantServiceTicket(
            ticketId,
            service,
            this.serviceTicketExpirationPolicy,
            currentAuthentication != null);

    this.serviceTicketRegistry.addTicket(serviceTicket);

    logger.info("Granted ticket [{}] for service [{}] for user [{}]",
            serviceTicket.getId(), service.getId(), principal.getId());

    return serviceTicket;
}
 
Example 20
Source File: CentralAuthenticationServiceImpl.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * @throws IllegalArgumentException if ticketGrantingTicketId or service are null.
 */
@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, final Credential... credentials)
        throws AuthenticationException, TicketException {
    Assert.notNull(ticketGrantingTicketId, "ticketGrantingticketId cannot be null");
    Assert.notNull(service, "service cannot be null");

    final TicketGrantingTicket ticketGrantingTicket = this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);

    if (ticketGrantingTicket == null) {
        logger.debug("TicketGrantingTicket [{}] cannot be found in the ticket registry.", ticketGrantingTicketId);
        throw new InvalidTicketException(ticketGrantingTicketId);
    }

    synchronized (ticketGrantingTicket) {
        if (ticketGrantingTicket.isExpired()) {
            this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
            logger.debug("TicketGrantingTicket[{}] has expired and is now deleted from the ticket registry.", ticketGrantingTicketId);
            throw new InvalidTicketException(ticketGrantingTicketId);
        }
    }

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

    verifyRegisteredServiceProperties(registeredService, service);
    
    if (!registeredService.isSsoEnabled() && credentials == null
        && ticketGrantingTicket.getCountOfUses() > 0) {
        logger.warn("ServiceManagement: Service [{}] is not allowed to use SSO.", service.getId());
        throw new UnauthorizedSsoServiceException();
    }

    //CAS-1019
    final List<Authentication> authns = ticketGrantingTicket.getChainedAuthentications();
    if(authns.size() > 1) {
        if (!registeredService.isAllowedToProxy()) {
            final String message = String.
                    format("ServiceManagement: Proxy attempt by service [%s] (registered service [%s]) is not allowed.",
                    service.getId(), registeredService.toString());
            logger.warn(message);
            throw new UnauthorizedProxyingException(message);
        }
    }

    if (credentials != null) {
        final Authentication current = this.authenticationManager.authenticate(credentials);
        final Authentication original = ticketGrantingTicket.getAuthentication();
        if (!current.getPrincipal().equals(original.getPrincipal())) {
            throw new MixedPrincipalException(current, current.getPrincipal(), original.getPrincipal());
        }
        ticketGrantingTicket.getSupplementalAuthentications().add(current);
    }

    // Perform security policy check by getting the authentication that satisfies the configured policy
    // This throws if no suitable policy is found
    getAuthenticationSatisfiedByPolicy(ticketGrantingTicket.getRoot(), new ServiceContext(service, registeredService));

    final String uniqueTicketIdGenKey = service.getClass().getName();
    if (!this.uniqueTicketIdGeneratorsForService.containsKey(uniqueTicketIdGenKey)) {
        logger.warn("Cannot create service ticket because the key [{}] for service [{}] is not linked to a ticket id generator",
                uniqueTicketIdGenKey, service.getId());
        throw new UnauthorizedSsoServiceException();
    }
    
    final UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator =
            this.uniqueTicketIdGeneratorsForService.get(uniqueTicketIdGenKey);

    final String generatedServiceTicketId = serviceTicketUniqueTicketIdGenerator.getNewTicketId(ServiceTicket.PREFIX);
    logger.debug("Generated service ticket id [{}] for ticket granting ticket [{}]",
            generatedServiceTicketId, ticketGrantingTicket.getId());
    
    final ServiceTicket serviceTicket = ticketGrantingTicket.grantServiceTicket(generatedServiceTicketId, service,
            this.serviceTicketExpirationPolicy, credentials != null);

    this.serviceTicketRegistry.addTicket(serviceTicket);

    if (logger.isInfoEnabled()) {
        final List<Authentication> authentications = serviceTicket.getGrantingTicket().getChainedAuthentications();
        final String formatString = "Granted %s ticket [%s] for service [%s] for user [%s]";
        final String type;
        final String principalId = authentications.get(authentications.size() - 1).getPrincipal().getId();

        if (authentications.size() == 1) {
            type = "service";
        } else {
            type = "proxy";
        }

        logger.info(String.format(formatString, type, serviceTicket.getId(), service.getId(), principalId));
    }

    return serviceTicket.getId();
}