org.jasig.cas.ticket.Ticket Java Examples

The following examples show how to use org.jasig.cas.ticket.Ticket. 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: AbstractTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws IllegalArgumentException if class is null.
 * @throws ClassCastException if class does not match requested ticket
 * class.
 * @return specified ticket from the registry
 */
@Override
public final <T extends Ticket> T getTicket(final String ticketId, final Class<? extends Ticket> clazz) {
    Assert.notNull(clazz, "clazz cannot be null");

    final Ticket ticket = this.getTicket(ticketId);

    if (ticket == null) {
        return null;
    }

    if (!clazz.isAssignableFrom(ticket.getClass())) {
        throw new ClassCastException("Ticket [" + ticket.getId()
            + " is of type " + ticket.getClass()
            + " when we were expecting " + clazz);
    }

    return (T) ticket;
}
 
Example #2
Source File: JpaTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
private void deleteTicketAndChildren(final Ticket ticket) {
    final List<TicketGrantingTicketImpl> ticketGrantingTicketImpls = entityManager
        .createQuery("select t from TicketGrantingTicketImpl t where t.ticketGrantingTicket.id = :id",
                TicketGrantingTicketImpl.class)
        .setLockMode(LockModeType.PESSIMISTIC_WRITE)
        .setParameter("id", ticket.getId())
        .getResultList();
    final List<ServiceTicketImpl> serviceTicketImpls = entityManager
            .createQuery("select s from ServiceTicketImpl s where s.ticketGrantingTicket.id = :id",
                    ServiceTicketImpl.class)
            .setParameter("id", ticket.getId())
            .getResultList();

    for (final ServiceTicketImpl s : serviceTicketImpls) {
        removeTicket(s);
    }

    for (final TicketGrantingTicketImpl t : ticketGrantingTicketImpls) {
        deleteTicketAndChildren(t);
    }

    removeTicket(ticket);
}
 
Example #3
Source File: JpaTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = false)
public boolean deleteTicket(final String ticketId) {
    final Ticket ticket = getRawTicket(ticketId);

    if (ticket == null) {
        return false;
    }

    if (ticket instanceof ServiceTicket) {
        removeTicket(ticket);
        logger.debug("Deleted ticket [{}] from the registry.", ticket);
        return true;
    }

    deleteTicketAndChildren(ticket);
    logger.debug("Deleted ticket [{}] and its children from the registry.", ticket);
    return true;
}
 
Example #4
Source File: CentralAuthenticationServiceImpl.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Timed(name = "GET_TICKET_TIMER")
@Metered(name = "GET_TICKET_METER")
@Counted(name="GET_TICKET_COUNTER", monotonic=true)
@Override
public <T extends Ticket> T getTicket(final String ticketId, final Class<? extends Ticket> clazz)
        throws InvalidTicketException {
    Assert.notNull(ticketId, "ticketId cannot be null");
    final Ticket ticket = this.ticketRegistry.getTicket(ticketId, clazz);

    if (ticket == null) {
        logger.debug("Ticket [{}] by type [{}] cannot be found in the ticket registry.", ticketId, clazz.getSimpleName());
        throw new InvalidTicketException(ticketId);
    }

    if (ticket instanceof TicketGrantingTicket) {
        synchronized (ticket) {
            if (ticket.isExpired()) {
                this.ticketRegistry.deleteTicket(ticketId);
                logger.debug("Ticket [{}] has expired and is now deleted from the ticket registry.", ticketId);
                throw new InvalidTicketException(ticketId);
            }
        }
    }
    return (T) ticket;
}
 
Example #5
Source File: JpaTicketRegistry.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Transactional(readOnly = false)
@Override
public boolean deleteTicket(final String ticketId) {
    final Ticket ticket = getRawTicket(ticketId);

    if (ticket == null) {
        return false;
    }

    if (ticket instanceof ServiceTicket) {
        removeTicket(ticket);
        logger.debug("Deleted ticket [{}] from the registry.", ticket);
        return true;
    }

    deleteTicketAndChildren(ticket);
    logger.debug("Deleted ticket [{}] and its children from the registry.", ticket);
    return true;
}
 
Example #6
Source File: TicketGrantingTicketCheckAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Determines whether the TGT in the flow request context is valid.
 *
 * @param requestContext Flow request context.
 *
 * @throws Exception in case ticket cannot be retrieved from the service layer
 * @return {@link #NOT_EXISTS}, {@link #INVALID}, or {@link #VALID}.
 */
@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
    final String tgtId = WebUtils.getTicketGrantingTicketId(requestContext);
    if (!StringUtils.hasText(tgtId)) {
        return new Event(this, NOT_EXISTS);
    }

    String eventId = INVALID;
    try {
        final Ticket ticket = this.centralAuthenticationService.getTicket(tgtId, Ticket.class);
        if (ticket != null && !ticket.isExpired()) {
            eventId = VALID;
        }
    } catch (final TicketException e) {
        logger.trace("Could not retrieve ticket id {} from registry.", e);
    }
    return new Event(this,  eventId);
}
 
Example #7
Source File: SingleSignOnSessionsReportController.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Gets sso sessions.
 *
 * @return the sso sessions
 */
private Collection<Map<String, Object>> getSsoSessions() {
    final List<Map<String, Object>> activeSessions = new ArrayList<Map<String, Object>>();

    for(final Ticket ticket : getNonExpiredTicketGrantingTickets()) {
        final TicketGrantingTicket tgt = (TicketGrantingTicket) ticket;

        final Map<String, Object> sso = new HashMap<>(SsoSessionAttributeKeys.values().length);
        sso.put(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.toString(), tgt.getAuthentication().getPrincipal().getId());
        sso.put(SsoSessionAttributeKeys.AUTHENTICATION_DATE.toString(), tgt.getAuthentication().getAuthenticationDate());
        sso.put(SsoSessionAttributeKeys.NUMBER_OF_USES.toString(), tgt.getCountOfUses());
        if (this.includeTicketGrantingTicketId) {
            sso.put(SsoSessionAttributeKeys.TICKET_GRANTING_TICKET.toString(), tgt.getId());
        }

        activeSessions.add(Collections.unmodifiableMap(sso));
    }
    return Collections.unmodifiableCollection(activeSessions);
}
 
Example #8
Source File: GenericSuccessViewActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyValidPrincipal() throws InvalidTicketException {
    final CentralAuthenticationService cas = mock(CentralAuthenticationService.class);
    final Authentication authn = mock(Authentication.class);
    when(authn.getPrincipal()).thenReturn(TestUtils.getPrincipal("cas"));
    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getAuthentication()).thenReturn(authn);



    when(cas.getTicket(any(String.class), any(Ticket.class.getClass()))).thenReturn(tgt);
    final GenericSuccessViewAction action = new GenericSuccessViewAction(cas);
    final Principal p = action.getAuthenticationPrincipal("TGT-1");
    assertNotNull(p);
    assertEquals(p.getId(), "cas");
}
 
Example #9
Source File: JpaTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private void removeTicket(final Ticket ticket) {
    try {
        if (logger.isDebugEnabled()) {
            final Date creationDate = new Date(ticket.getCreationTime());
            logger.debug("Removing Ticket [{}] created: {}", ticket, creationDate.toString());
         }
        entityManager.remove(ticket);
    } catch (final Exception e) {
        logger.error("Error removing {} from registry.", ticket, e);
    }
}
 
Example #10
Source File: AbstractDistributedTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public final TicketGrantingTicket getGrantingTicket() {
    final TicketGrantingTicket old = this.ticket.getGrantingTicket();

    if (old == null || !callback) {
        return old;
    }

    return this.ticketRegistry.getTicket(old.getId(), Ticket.class);
}
 
Example #11
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 #12
Source File: MemCacheTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public Ticket getTicket(final String ticketId) {
    try {
        final Ticket t = (Ticket) this.client.get(ticketId);
        if (t != null) {
            return getProxiedTicketInstance(t);
        }
    } catch (final Exception e) {
        logger.error("Failed fetching {} ", ticketId, e);
    }
    return null;
}
 
Example #13
Source File: MultiFactorAwareCentralAuthenticationService.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Timed(name = "GET_TICKET_TIMER")
@Metered(name = "GET_TICKET_METER")
@Counted(name="GET_TICKET_COUNTER", monotonic=true)
@Override
public <T extends Ticket> T getTicket(final String ticketId, final Class<? extends Ticket> clazz)
        throws InvalidTicketException {
    return delegate.getTicket(ticketId, clazz);

}
 
Example #14
Source File: CentralAuthenticationServiceImpl.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Timed(name = "GET_TICKETS_TIMER")
@Metered(name = "GET_TICKETS_METER")
@Counted(name="GET_TICKETS_COUNTER", monotonic=true)
@Override
public Collection<Ticket> getTickets(final Predicate predicate) {
    final Collection<Ticket> c = new HashSet<>(this.ticketRegistry.getTickets());
    final Iterator<Ticket> it = c.iterator();
    while (it.hasNext()) {
        if (!predicate.evaluate(it.next())) {
            it.remove();
        }
    }
    return c;
}
 
Example #15
Source File: TicketOrCredentialPrincipalResolver.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Resolve the join point argument.
 *
 * @param arg1 the arg
 * @return the resolved string
 */
private String resolveArgument(final Object arg1) {
    LOGGER.debug("Resolving argument [{}] for audit", arg1.getClass().getSimpleName());

    if (arg1 instanceof Credential) {
        return arg1.toString();
    } else if (arg1 instanceof String) {
        try {
            final Ticket ticket = this.centralAuthenticationService.getTicket((String) arg1, Ticket.class);
            if (ticket instanceof ServiceTicket) {
                final ServiceTicket serviceTicket = (ServiceTicket) ticket;
                return serviceTicket.getGrantingTicket().getAuthentication().getPrincipal().getId();
            } else if (ticket instanceof TicketGrantingTicket) {
                final TicketGrantingTicket tgt = (TicketGrantingTicket) ticket;
                return tgt.getAuthentication().getPrincipal().getId();
            }
        } catch (final InvalidTicketException e) {
            LOGGER.trace(e.getMessage(), e);
        }
        LOGGER.debug("Could not locate ticket [{}] in the registry", arg1);
    } else {
        final SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            final Authentication authentication = securityContext.getAuthentication();

            if (authentication != null) {
                return ((UserDetails) authentication.getPrincipal()).getUsername();
            }
        }
    }
    LOGGER.debug("Unable to determine the audit argument. Returning [{}]", UNKNOWN_USER);
    return UNKNOWN_USER;
}
 
Example #16
Source File: DefaultTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public int serviceTicketCount() {
    int count = 0;
    for (Ticket t : this.cache.values()) {
        if (t instanceof ServiceTicket) {
            count++;
        }
    }
    return count;
}
 
Example #17
Source File: AbstractDistributedTicketRegistry.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public final TicketGrantingTicket getGrantingTicket() {
    final TicketGrantingTicket old = this.ticket.getGrantingTicket();

    if (old == null || !callback) {
        return old;
    }

    return this.ticketRegistry.getTicket(old.getId(), Ticket.class);
}
 
Example #18
Source File: DefaultTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public int sessionCount() {
    int count = 0;
    for (Ticket t : this.cache.values()) {
        if (t instanceof TicketGrantingTicket) {
            count++;
        }
    }
    return count;
}
 
Example #19
Source File: TicketRegistryDecorator.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public void addTicket(final Ticket ticket) {
    if (ticket instanceof TicketGrantingTicket) {
        final TicketGrantingTicket ticketGrantingTicket = (TicketGrantingTicket) ticket;
        final String ticketId = ticketGrantingTicket.getId();
        final String userName = ticketGrantingTicket.getAuthentication().getPrincipal().getId().toLowerCase();

        logger.debug("Creating mapping ticket {} to user name {}", ticketId, userName);

        this.cache.put(ticketId, userName);
    }

    this.ticketRegistry.addTicket(ticket);
}
 
Example #20
Source File: TicketRegistryDecorator.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public void addTicket(final Ticket ticket) {
    if (ticket instanceof TicketGrantingTicket) {
        final TicketGrantingTicket ticketGrantingTicket = (TicketGrantingTicket) ticket;
        final String ticketId = ticketGrantingTicket.getId();
        final String userName = ticketGrantingTicket.getAuthentication().getPrincipal().getId().toLowerCase();

        logger.debug("Creating mapping ticket {} to user name {}", ticketId, userName);

        this.cache.put(ticketId, userName);
    }

    this.ticketRegistry.addTicket(ticket);
}
 
Example #21
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 #22
Source File: EhCacheTicketRegistry.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public Ticket getTicket(final String ticketId) {
    if (ticketId == null) {
        return null;
    }

    Element element = this.serviceTicketsCache.get(ticketId);
    if (element == null) {
        element = this.ticketGrantingTicketsCache.get(ticketId);
    }
    return element == null ? null : getProxiedTicketInstance((Ticket) element.getObjectValue());
}
 
Example #23
Source File: SingleSignOnSessionsReportController.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Gets non expired ticket granting tickets.
 *
 * @return the non expired ticket granting tickets
 */
private Collection<Ticket> getNonExpiredTicketGrantingTickets() {
    return this.centralAuthenticationService.getTickets(new Predicate() {
        @Override
        public boolean evaluate(final Object ticket) {
            if (ticket instanceof TicketGrantingTicket) {
                return !((TicketGrantingTicket) ticket).isExpired();
            }
            return false;
        }
    });
}
 
Example #24
Source File: DefaultTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public Ticket getTicket(final String ticketId) {
    if (ticketId == null) {
        return null;
    }

    logger.debug("Attempting to retrieve ticket [{}]", ticketId);
    final Ticket ticket = this.cache.get(ticketId);

    if (ticket != null) {
        logger.debug("Ticket [{}] found in registry.", ticketId);
    }

    return ticket;
}
 
Example #25
Source File: HazelcastTicketRegistry.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * A method to get the starting TTL for a ticket based upon type.
 *
 * @param t Ticket to get starting TTL for
 *
 * @return Initial TTL for ticket
 */
private long getTimeout(final Ticket t) {
    if (t instanceof TicketGrantingTicket) {
        return this.ticketGrantingTicketTimoutInSeconds;
    } else if (t instanceof ServiceTicket) {
        return this.serviceTicketTimeoutInSeconds;
    }
    throw new IllegalArgumentException(
            String.format("Invalid ticket type [%s]. Expecting either [TicketGrantingTicket] or [ServiceTicket]",
                    t.getClass().getName()));
}
 
Example #26
Source File: MemCacheTicketRegistry.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public Ticket getTicket(final String ticketId) {
    try {
        final Ticket t = (Ticket) this.client.get(ticketId);
        if (t != null) {
            return getProxiedTicketInstance(t);
        }
    } catch (final Exception e) {
        logger.error("Failed fetching {} ", ticketId, e);
    }
    return null;
}
 
Example #27
Source File: JBossCacheTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public void addTicket(final Ticket ticket) {
    try {
        logger.debug("Adding ticket to registry for: {}", ticket.getId());
        this.cache.put(FQN_TICKET, ticket.getId(), ticket);
    } catch (final CacheException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example #28
Source File: EhCacheTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public Ticket getTicket(final String ticketId) {
    if (ticketId == null) {
        return null;
    }

    Element element = this.serviceTicketsCache.get(ticketId);
    if (element == null) {
        element = this.ticketGrantingTicketsCache.get(ticketId);
    }
    return element == null ? null : getProxiedTicketInstance((Ticket) element.getObjectValue());
}
 
Example #29
Source File: EhCacheTicketRegistryTests.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>();

    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, getService(),
                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) {
        logger.error(e.getMessage(), e);
        fail("Caught an exception. But no exception should have been thrown.");
    }
}
 
Example #30
Source File: EhCacheTicketRegistryTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/**
 * Cleaning ticket registry to start afresh, after newing up the instance.
 * Leftover items from the cache interfere with the correctness of tests.
 * Resetting the registry instance back to its default empty state allows each
 * test to run an isolated mode independent of the previous state of either cache.
 */
private void initTicketRegistry() {
    final Iterator<Ticket> it = this.ticketRegistry.getTickets().iterator();

    while (it.hasNext()) {
        this.ticketRegistry.deleteTicket(it.next().getId());
    }
}