Java Code Examples for org.jasig.cas.authentication.Credential

The following examples show how to use org.jasig.cas.authentication.Credential. These examples are extracted from open source projects. 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 Project: springboot-shiro-cas-mybatis   Source File: KryoTranscoderTests.java    License: MIT License 6 votes vote down vote up
public MockTicketGrantingTicket(final String id, final Credential credential, final Map<String, Object> principalAttributes) {
    this.id = id;
    final CredentialMetaData credentialMetaData = new BasicCredentialMetaData(credential);
    final DefaultAuthenticationBuilder builder = new DefaultAuthenticationBuilder();
    builder.setPrincipal(this.principalFactory.createPrincipal(USERNAME, principalAttributes));
    builder.setAuthenticationDate(new Date());
    builder.addCredential(credentialMetaData);
    builder.addAttribute(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, Boolean.TRUE);
    final AuthenticationHandler handler = new MockAuthenticationHandler();
    try {
        builder.addSuccess(handler.getName(), handler.authenticate(credential));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
    builder.addFailure(handler.getName(), FailedLoginException.class);
    this.authentication = builder.build();
}
 
Example 2
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(new SimplePrincipal(
                principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example 3
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException {
    final OpenIdCredential c = (OpenIdCredential) credential;

    final TicketGrantingTicket t = this.ticketRegistry.getTicket(c.getTicketGrantingTicketId(),
                    TicketGrantingTicket.class);

    if (t == null || t.isExpired()) {
        throw new FailedLoginException("TGT is null or expired.");
    }
    final Principal principal = t.getAuthentication().getPrincipal();
    if (!principal.getId().equals(c.getUsername())) {
        throw new FailedLoginException("Principal ID mismatch");
    }
    return new HandlerResult(this, new BasicCredentialMetaData(c), principal);
}
 
Example 4
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example 5
protected String resolveFromInternal(final JoinPoint joinPoint) {
    final Object arg1 = joinPoint.getArgs()[0];
    if (arg1 instanceof Credential) {
       return arg1.toString();
    } else if (arg1 instanceof String) {
        final Ticket ticket = this.ticketRegistry.getTicket((String) arg1);
        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();
        }
    } else {
        final SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            final Authentication authentication = securityContext.getAuthentication();

            if (authentication != null) {
                return ((UserDetails) authentication.getPrincipal()).getUsername();
            }
        }
    }
    return UNKNOWN_USER;
}
 
Example 6
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        logger.debug("Remote  User [{}] found in HttpServletRequest", remoteUser);
        return new PrincipalBearingCredential(new SimplePrincipal(remoteUser));
    }

    logger.debug("Remote User not found in HttpServletRequest.");

    return null;
}
 
Example 7
@Override
public HandlerResult authenticate(final Credential credential)
        throws GeneralSecurityException, PreventedException {

    final UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential;
    final String username = usernamePasswordCredential.getUsername();
    final String password = usernamePasswordCredential.getPassword();

    final Exception exception = this.usernameErrorMap.get(username);
    if (exception instanceof GeneralSecurityException) {
        throw (GeneralSecurityException) exception;
    } else if (exception instanceof PreventedException) {
        throw (PreventedException) exception;
    } else if (exception instanceof RuntimeException) {
        throw (RuntimeException) exception;
    } else if (exception != null) {
        logger.debug("Cannot throw checked exception {} since it is not declared by method signature.", exception);
    }

    if (StringUtils.hasText(username) && StringUtils.hasText(password) && username.equals(password)) {
        logger.debug("User [{}] was successfully authenticated.", username);
        return new DefaultHandlerResult(this, new BasicCredentialMetaData(credential));
    }
    logger.debug("User [{}] failed authentication", username);
    throw new FailedLoginException();
}
 
Example 8
@Test
public void examineResolve() throws Exception {
    final Credential credential = mock(Credential.class);
    when(credential.getId()).thenReturn("input");

    final PrincipalResolver resolver1 = mock(PrincipalResolver.class);
    when(resolver1.supports(eq(credential))).thenReturn(true);
    when(resolver1.resolve((eq(credential)))).thenReturn(principalFactory.createPrincipal("output"));

    final PrincipalResolver resolver2 = mock(PrincipalResolver.class);
    when(resolver2.supports(any(Credential.class))).thenReturn(false);
    when(resolver2.resolve(argThat(new ArgumentMatcher<Credential>() {
        @Override
        public boolean matches(final Object o) {
            return "output".equals(((Credential) o).getId());
        }
    }))).thenReturn(principalFactory.createPrincipal("final", Collections.<String, Object>singletonMap("mail", "[email protected]")));

    final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver();
    resolver.setChain(Arrays.asList(resolver1, resolver2));
    final Principal principal = resolver.resolve(credential);
    assertEquals("final", principal.getId());
    assertEquals("[email protected]", principal.getAttributes().get("mail"));
}
 
Example 9
@Test
public void verifyAttributePopulationWithPasswordWithDifferentCredentialsType() {
    final Authentication auth = TestUtils.getAuthentication();
    final Map<String, String> map = new HashMap<>();
    final CacheCredentialsMetaDataPopulator populator = new CacheCredentialsMetaDataPopulator(map);

    final Credential c = new Credential() {
        @Override
        public String getId() {
            return "something";
        }
    };

    if (populator.supports(c)) {
        populator.populateAttributes(DefaultAuthenticationBuilder.newInstance(auth), c);
    }

    assertEquals(map.size(), 0);

}
 
Example 10
Source Project: springboot-shiro-cas-mybatis   Source File: TicketResource.java    License: MIT License 6 votes vote down vote up
/**
 * Obtain credentials from the request.
 *
 * @return the credential
 */
protected Credential obtainCredentials() {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();
    final WebRequestDataBinder binder = new WebRequestDataBinder(c);
    final RestletWebRequest webRequest = new RestletWebRequest(getRequest());

    final Form form = new Form(getRequest().getEntity());
    logFormRequest(form);

    if (!form.isEmpty()) {
        binder.bind(webRequest);
        return c;
    }
    LOGGER.trace("Failed to bind the request to credentials. Resulting form is empty");
    return null;
}
 
Example 11
@Test
public void verifyRenewWithServiceAndDifferentCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");
    request.addParameter("username", "test2");
    request.addParameter("password", "test2");

    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
}
 
Example 12
@Test
public void testAuthenticationViaTGT() {
    setMockAuthenticationContextWith(null);
    setMockTgtContextWith(TGT_ID);

    final Credential c = getCredentials();

    when(this.sessionFlowScope.getRequired(anyString(),
            any(UsernamePasswordCredentials.class.getClass()))).thenReturn(c);
    when(this.requestContext.getFlowScope().get("credential")).thenReturn(c);

    final Event event = this.action.doExecute(this.requestContext);
    final Credential creds = (Credential)
            event.getAttributes().get(GenerateMultiFactorCredentialsAction.ATTRIBUTE_ID_MFA_CREDENTIALS);

    assertTrue(creds instanceof MultiFactorCredentials);
    final MultiFactorCredentials mfaCreds = (MultiFactorCredentials) creds;

    assertEquals(mfaCreds.countChainedAuthentications(), 1);
    assertEquals(mfaCreds.getChainedCredentials().size(), 1);

    assertEquals(mfaCreds.getAuthentication().getPrincipal().getId(), authentication.getPrincipal().getId());
    assertEquals(mfaCreds.getCredentials(), c);
}
 
Example 13
@Override
protected Event doExecute(final RequestContext context) {
    final FlowSession session = context.getFlowExecutionContext().getActiveSession();
    LOGGER.debug("Authentication has entered the flow [{}] executing state [{}",
            context.getActiveFlow().getId(), session.getState().getId());
    final Credential creds = WebUtils.getCredential(context);
    final String id = creds != null ? creds.getId() : null;

    final Credential mfaCreds = createCredentials(context, creds, id);
    final AttributeMap map = new LocalAttributeMap(ATTRIBUTE_ID_MFA_CREDENTIALS, mfaCreds);
    return new Event(this, EVENT_ID_SUCCESS, map);
}
 
Example 14
Source Project: springboot-shiro-cas-mybatis   Source File: ClientActionTests.java    License: MIT License 5 votes vote down vote up
@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(ClientAction.THEME, MY_THEME);
    mockSession.setAttribute(ClientAction.LOCALE, MY_LOCALE);
    mockSession.setAttribute(ClientAction.METHOD, MY_METHOD);
    final Service service = new SimpleWebApplicationServiceImpl(MY_SERVICE);
    mockSession.setAttribute(ClientAction.SERVICE, service);
    mockRequest.setSession(mockSession);

    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);

    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);

    final FacebookClient facebookClient = new MockFacebookClient();
    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(Credential.class))).thenReturn(tgt);
    final ClientAction action = new ClientAction(casImpl, clients);
    final Event event = action.execute(mockRequestContext);
    assertEquals("success", event.getId());
    assertEquals(MY_THEME, mockRequest.getAttribute(ClientAction.THEME));
    assertEquals(MY_LOCALE, mockRequest.getAttribute(ClientAction.LOCALE));
    assertEquals(MY_METHOD, mockRequest.getAttribute(ClientAction.METHOD));
    assertEquals(MY_SERVICE, mockRequest.getAttribute(ClientAction.SERVICE));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    final MutableAttributeMap requestScope = mockRequestContext.getRequestScope();
    assertEquals(service, flowScope.get(ClientAction.SERVICE));
    assertEquals(TGT_ID, flowScope.get(TGT_NAME));
    assertEquals(TGT_ID, requestScope.get(TGT_NAME));
}
 
Example 15
Source Project: springboot-shiro-cas-mybatis   Source File: Cas20ProxyHandler.java    License: MIT License 5 votes vote down vote up
@Override
public String handle(final Credential credential, final TicketGrantingTicket proxyGrantingTicketId) {
    final HttpBasedServiceCredential serviceCredentials = (HttpBasedServiceCredential) credential;
    final String proxyIou = this.uniqueTicketIdGenerator.getNewTicketId(TicketGrantingTicket.PROXY_GRANTING_TICKET_IOU_PREFIX);

    final URL callbackUrl = serviceCredentials.getCallbackUrl();
    final String serviceCredentialsAsString = callbackUrl.toExternalForm();
    final int bufferLength = serviceCredentialsAsString.length() + proxyIou.length()
            + proxyGrantingTicketId.getId().length() + BUFFER_LENGTH_ADDITIONAL_CHARGE;
    final StringBuilder stringBuffer = new StringBuilder(bufferLength);

    stringBuffer.append(serviceCredentialsAsString);

    if (callbackUrl.getQuery() != null) {
        stringBuffer.append('&');
    } else {
        stringBuffer.append('?');
    }

    stringBuffer.append(PARAMETER_PROXY_GRANTING_TICKET_IOU);
    stringBuffer.append('=');
    stringBuffer.append(proxyIou);
    stringBuffer.append('&');
    stringBuffer.append(PARAMETER_PROXY_GRANTING_TICKET_ID);
    stringBuffer.append('=');
    stringBuffer.append(proxyGrantingTicketId);

    if (this.httpClient.isValidEndPoint(stringBuffer.toString())) {
        logger.debug("Sent ProxyIou of {} for service: {}", proxyIou, serviceCredentials);
        return proxyIou;
    }

    logger.debug("Failed to send ProxyIou of {} for service: {}", proxyIou, serviceCredentials);
    return null;
}
 
Example 16
@Test
public void verifyNullAttributes() {
    final PersonDirectoryPrincipalResolver resolver = new PersonDirectoryPrincipalResolver();
    resolver.setReturnNullIfNoAttributes(true);
    resolver.setPrincipalAttributeName(TestUtils.CONST_USERNAME);
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final Principal p = resolver.resolve(c);
    assertNull(p);
}
 
Example 17
/**
 * Resolves a credential by delegating to each of the configured resolvers in sequence. Note that the
 * {@link PrincipalResolver#supports(org.jasig.cas.authentication.Credential)} method is called only for the
 * first configured resolver.
 *
 * @param credential Authenticated credential.
 *
 * @return The principal from the last configured resolver in the chain.
 */
public Principal resolve(final Credential credential) {
    Principal result = null;
    Credential input = credential;
    for (final PrincipalResolver resolver : this.chain) {
        if (result != null) {
            input = new IdentifiableCredential(result.getId());
        }
        result = resolver.resolve(input);
    }
    return result;
}
 
Example 18
Source Project: springboot-shiro-cas-mybatis   Source File: KryoTranscoderTests.java    License: 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 19
@Override
protected String extractPrincipalId(final Credential credential) {
    final SpnegoCredential c = (SpnegoCredential) credential;
    final String id = c.getPrincipal().getId();

    switch (this.transformPrincipalId) {
    case UPPERCASE:
        return id.toUpperCase(Locale.ENGLISH);
    case LOWERCASE:
        return id.toLowerCase(Locale.ENGLISH);
    default:
        return id;
    }
}
 
Example 20
/**
 * {@inheritDoc}
 * @throws IllegalArgumentException if given invalid credentials
 */
@Override
public ServiceTicket grantServiceTicket(
        final String ticketGrantingTicketId, final Service service, final Credential... credentials)
        throws AuthenticationException, TicketException {

    checkForErrors(credentials);

    return this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, credentials);
}
 
Example 21
/**
 * Check for errors by asking the validator to review each credential.
 *
 * @param credentials the credentials
 */
private void checkForErrors(final Credential... credentials) {
    if (credentials == null) {
        return;
    }

    for (final Credential c : credentials) {
        final Set<ConstraintViolation<Credential>> errors = this.validator.validate(c);
        if (!errors.isEmpty()) {
            throw new IllegalArgumentException("Error validating credentials: " + errors.toString());
        }
    }
}
 
Example 22
@Test
public void verifyNoAttributesWithPrincipal() {
    final PersonDirectoryPrincipalResolver resolver = new PersonDirectoryPrincipalResolver();
    resolver.setPrincipalAttributeName(TestUtils.CONST_USERNAME);
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final Principal p = resolver.resolve(c);
    assertNotNull(p);
}
 
Example 23
@Audit(
    action="TICKET_GRANTING_TICKET",
    actionResolverName="CREATE_TICKET_GRANTING_TICKET_RESOLVER",
    resourceResolverName="CREATE_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER")
@Timed(name = "CREATE_TICKET_GRANTING_TICKET_TIMER")
@Metered(name = "CREATE_TICKET_GRANTING_TICKET_METER")
@Counted(name="CREATE_TICKET_GRANTING_TICKET_COUNTER", monotonic=true)
@Override
public TicketGrantingTicket createTicketGrantingTicket(final Credential... credentials)
        throws AuthenticationException, TicketException {

    final Set<Credential> sanitizedCredentials = sanitizeCredentials(credentials);
    if (sanitizedCredentials.size() > 0) {
        final Authentication authentication = this.authenticationManager.authenticate(credentials);

        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
                this.ticketGrantingTicketUniqueTicketIdGenerator
                        .getNewTicketId(TicketGrantingTicket.PREFIX),
                authentication, this.ticketGrantingTicketExpirationPolicy);

        this.ticketRegistry.addTicket(ticketGrantingTicket);
        return ticketGrantingTicket;
    }
    final String msg = "No credentials were specified in the request for creating a new ticket-granting ticket";
    logger.warn(msg);
    throw new TicketCreationException(new IllegalArgumentException(msg));
}
 
Example 24
/**
 * {@inheritDoc}
 * @throws IllegalArgumentException if given invalid credentials
 */
@Override
public String grantServiceTicket(
        final String ticketGrantingTicketId, final Service service, final Credential... credentials)
        throws AuthenticationException, TicketException {

    checkForErrors(credentials);

    return this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, credentials);
}
 
Example 25
@Override
public HandlerResult authenticate(final Credential credential)
        throws GeneralSecurityException, PreventedException {
    final OneTimePasswordCredential otp = (OneTimePasswordCredential) credential;
    final String valueOnRecord = credentialMap.get(otp.getId());
    if (otp.getPassword().equals(credentialMap.get(otp.getId()))) {
        return new HandlerResult(this, new BasicCredentialMetaData(otp), new SimplePrincipal(otp.getId()));
    }
    throw new FailedLoginException();
}
 
Example 26
/**
 * {@inheritDoc}
 * @throws IllegalArgumentException if the Credentials are null or if given
 * invalid credentials.
 */
@Override
public String createTicketGrantingTicket(final Credential... credentials)
        throws AuthenticationException, TicketException {

    Assert.notNull(credentials, "credentials cannot be null");
    checkForErrors(credentials);

    return this.centralAuthenticationService.createTicketGrantingTicket(credentials);
}
 
Example 27
Source Project: cas4.0.x-server-wechat   Source File: TicketResource.java    License: Apache License 2.0 5 votes vote down vote up
protected Credential obtainCredentials() {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();
    final WebRequestDataBinder binder = new WebRequestDataBinder(c);
    final RestletWebRequest webRequest = new RestletWebRequest(getRequest());

    logFormRequest(new Form(getRequest().getEntity()));
    binder.bind(webRequest);

    return c;
}
 
Example 28
Source Project: springboot-shiro-cas-mybatis   Source File: KryoTranscoderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecode() throws Exception {
    final ServiceTicket expectedST =
            new MockServiceTicket(ST_ID);
    assertEquals(expectedST, transcoder.decode(transcoder.encode(expectedST)));

    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final TicketGrantingTicket expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, this.principalAttributes);
    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 29
@Test
public void verifyGrantServiceTicketWithNullCredentials() throws Exception {
    final TicketGrantingTicket ticketGrantingTicketId = this.remoteCentralAuthenticationService
        .createTicketGrantingTicket(TestUtils
            .getCredentialsWithSameUsernameAndPassword());
    this.remoteCentralAuthenticationService.grantServiceTicket(
        ticketGrantingTicketId.getId(), TestUtils.getService(), (Credential[]) null);
}
 
Example 30
@Test
public void verifyResolverCredential() {
    final TicketOrCredentialPrincipalResolver res =
            new TicketOrCredentialPrincipalResolver(getCentralAuthenticationService());
    final JoinPoint jp = mock(JoinPoint.class);

    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    when(jp.getArgs()).thenReturn(new Object[] {c});

    final String result = res.resolveFrom(jp, null);
    assertNotNull(result);
    assertEquals(result, c.toString());
}