org.jasig.cas.authentication.Authentication Java Examples

The following examples show how to use org.jasig.cas.authentication.Authentication. 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: CentralAuthenticationServiceImpl.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * @throws IllegalArgumentException if the credentials are null.
 */
@Audit(
    action="TICKET_GRANTING_TICKET",
    actionResolverName="CREATE_TICKET_GRANTING_TICKET_RESOLVER",
    resourceResolverName="CREATE_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER")
@Profiled(tag = "CREATE_TICKET_GRANTING_TICKET", logFailuresSeparately = false)
@Transactional(readOnly = false)
public String createTicketGrantingTicket(final Credential... credentials)
        throws AuthenticationException, TicketException {

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

    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.getId();
}
 
Example #2
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 #3
Source File: CentralAuthenticationServiceImpl.java    From taoshop with Apache License 2.0 6 votes vote down vote up
/**
 * Always keep track of a single authentication object,
 * as opposed to keeping a history of all. This helps with
 * memory consumption. Note that supplemental authentications
 * are to be removed.
 *
 * @param context              authentication context
 * @param ticketGrantingTicket the tgt
 * @return the processed authentication in the current context
 * @throws MixedPrincipalException in case there is a principal mismatch between TGT and the current authN.
 */
private Authentication evaluatePossibilityOfMixedPrincipals(final AuthenticationContext context,
                                                                   final TicketGrantingTicket ticketGrantingTicket)
        throws MixedPrincipalException {
    Authentication currentAuthentication = null;
    if (context != null) {
        currentAuthentication = context.getAuthentication();
        if (currentAuthentication != null) {
            final Authentication original = ticketGrantingTicket.getAuthentication();
            if (!currentAuthentication.getPrincipal().equals(original.getPrincipal())) {
                logger.debug("Principal associated with current authentication {} does not match "
                        + " the principal {} associated with the original authentication",
                        currentAuthentication.getPrincipal(), original.getPrincipal());
                throw new MixedPrincipalException(
                        currentAuthentication, currentAuthentication.getPrincipal(), original.getPrincipal());
            }
            ticketGrantingTicket.getSupplementalAuthentications().clear();
            ticketGrantingTicket.getSupplementalAuthentications().add(currentAuthentication);
            logger.debug("Added authentication to the collection of supplemental authentications");
        }
    }
    return currentAuthentication;
}
 
Example #4
Source File: Saml10SuccessResponseView.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected void prepareResponse(final Response response, final Map<String, Object> model) {
    final Authentication authentication = getAssertionFrom(model).getPrimaryAuthentication();
    final DateTime issuedAt = response.getIssueInstant();
    final Service service = getAssertionFrom(model).getService();

    final Object o = authentication.getAttributes().get(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME);
    final boolean isRemembered = o == Boolean.TRUE && !getAssertionFrom(model).isFromNewLogin();

    // Build up the SAML assertion containing AuthenticationStatement and AttributeStatement
    final Assertion assertion = newSamlObject(Assertion.class);
    assertion.setID(generateId());
    assertion.setIssueInstant(issuedAt);
    assertion.setIssuer(this.issuer);
    assertion.setConditions(newConditions(issuedAt, service.getId()));
    final AuthenticationStatement authnStatement = newAuthenticationStatement(authentication);
    assertion.getAuthenticationStatements().add(authnStatement);
    final Map<String, Object> attributes = authentication.getPrincipal().getAttributes();
    if (!attributes.isEmpty() || isRemembered) {
        assertion.getAttributeStatements().add(
                newAttributeStatement(newSubject(authentication.getPrincipal().getId()), attributes, isRemembered));
    }
    response.setStatus(newStatus(StatusCode.SUCCESS, null));
    response.getAssertions().add(assertion);
}
 
Example #5
Source File: MultiFactorCredentialsTests.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultifactorAddMatchingCredentials() {
    final Principal firstPrincipal =  new DefaultPrincipalFactory().createPrincipal("casuser");

    final Authentication firstAuthentication = mock(Authentication.class);
    when(firstAuthentication.getPrincipal()).thenReturn(firstPrincipal);

    final Principal secondPrincipal =  new DefaultPrincipalFactory().createPrincipal("casuser");

    final Authentication secondAuthentication = mock(Authentication.class);
    when(secondAuthentication.getPrincipal()).thenReturn(secondPrincipal);

    final MultiFactorCredentials c = new MultiFactorCredentials();
    c.addAuthenticationToChain(firstAuthentication);
    c.addAuthenticationToChain(secondAuthentication);
    assertEquals(2, c.countChainedAuthentications());
}
 
Example #6
Source File: MultiFactorCredentialsTests.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Test(expected = UnknownPrincipalMatchException.class)
public void testMultifactorMismatchedPrincipals() {

    final Principal firstPrincipal = new DefaultPrincipalFactory().createPrincipal("casuser");

    final Authentication firstAuthentication = mock(Authentication.class);
    when(firstAuthentication.getPrincipal()).thenReturn(firstPrincipal);

    final Principal secondPrincipal =  new DefaultPrincipalFactory().createPrincipal("antheruser");

    final Authentication secondAuthentication = mock(Authentication.class);
    when(secondAuthentication.getPrincipal()).thenReturn(secondPrincipal);

    final MultiFactorCredentials c = new MultiFactorCredentials();
    c.addAuthenticationToChain(firstAuthentication);
    c.addAuthenticationToChain(secondAuthentication);
}
 
Example #7
Source File: CentralAuthenticationServiceImpl.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Gets the authentication satisfied by policy.
 *
 * @param ticket the ticket
 * @param context the context
 * @return the authentication satisfied by policy
 * @throws org.jasig.cas.ticket.TicketException the ticket exception
 */
private Authentication getAuthenticationSatisfiedByPolicy(
        final TicketGrantingTicket ticket, final ServiceContext context) throws TicketException {

    final ContextualAuthenticationPolicy<ServiceContext> policy =
            serviceContextAuthenticationPolicyFactory.createPolicy(context);
    if (policy.isSatisfiedBy(ticket.getAuthentication())) {
        return ticket.getAuthentication();
    }
    for (final Authentication auth : ticket.getSupplementalAuthentications()) {
        if (policy.isSatisfiedBy(auth)) {
            return auth;
        }
    }
    throw new UnsatisfiedAuthenticationPolicyException(policy);
}
 
Example #8
Source File: PrincipalAttributeMultiFactorAuthenticationRequestResolver.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
/**
 * Gets mfa request context.
 *
 * @param method         the mfa method
 * @param authentication the authentication
 * @param targetService  the target service
 * @param responseType   the response type
 * @return the mfa request context
 */
private MultiFactorAuthenticationRequestContext getMfaRequestContext(final String method,
                                                                     final Authentication authentication,
                                                                     final WebApplicationService targetService,
                                                                     final ResponseType responseType) {

    final String mfaMethod = this.authenticationMethodTranslator.translate(targetService, method);
    if (StringUtils.isNotBlank(mfaMethod)) {
        logger.debug("Found mfa attribute [{}] with value [{}] for principal [{}]", this.authenticationMethodAttributeName,
                mfaMethod, authentication.getPrincipal().getId());

        if (!this.authenticationMethodConfiguration.containsAuthenticationMethod(mfaMethod)) {
            logger.info("MFA attribute [{}] with value [{}] is not supported by the authentication method configuration.",
                    this.authenticationMethodAttributeName,
                    mfaMethod);
            return null;
        }
        final int mfaMethodRank = this.authenticationMethodConfiguration.getAuthenticationMethod(mfaMethod).getRank();
        final MultiFactorAuthenticationSupportingWebApplicationService svc =
                this.mfaServiceFactory.create(targetService.getId(), targetService.getId(),
                        targetService.getArtifactId(), responseType, mfaMethod, AuthenticationMethodSource.PRINCIPAL_ATTRIBUTE);

        return new MultiFactorAuthenticationRequestContext(svc, mfaMethodRank);
    }
    return null;
}
 
Example #9
Source File: TicketGrantingTicketImplTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyGetChainedPrincipalsWithTwo() {
    final Authentication authentication = TestUtils.getAuthentication();
    final Authentication authentication1 = TestUtils.getAuthentication("test1");
    final List<Authentication> principals = new ArrayList<>();
    principals.add(authentication);
    principals.add(authentication1);

    final TicketGrantingTicketImpl t1 = new TicketGrantingTicketImpl("test", null, null,
        authentication1, new NeverExpiresExpirationPolicy());
    final TicketGrantingTicket t = new TicketGrantingTicketImpl("test",
            new SimpleWebApplicationServiceImpl("gantor"), t1,
        authentication, new NeverExpiresExpirationPolicy());

    assertEquals(principals, t.getChainedAuthentications());
}
 
Example #10
Source File: SamlAuthenticationMetaDataPopulatorTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationTypeFoundCustom() {
    final CustomCredential credentials = new CustomCredential();

    final Map<String, String> added = new HashMap<String, String>();
    added.put(CustomCredential.class.getName(), "FF");

    this.populator.setUserDefinedMappings(added);

    final AuthenticationBuilder builder = newAuthenticationBuilder(TestUtils.getPrincipal());
    this.populator.populateAttributes(builder, credentials);
    final Authentication auth = builder.build();

    assertEquals(
            "FF",
            auth.getAttributes().get(SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD));
}
 
Example #11
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 #12
Source File: ServiceTicketImplTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testTicketGrantingTicketGrantedTwice() {
    Authentication a = TestUtils.getAuthentication();
    TicketGrantingTicket t = new TicketGrantingTicketImpl("test", TestUtils.getAuthentication(),
            new NeverExpiresExpirationPolicy());
    ServiceTicket s = t.grantServiceTicket(this.uniqueTicketIdGenerator.getNewTicketId(ServiceTicket.PREFIX),
            TestUtils.getService(), new MultiTimeUseOrTimeoutExpirationPolicy(1, 5000), false);
    s.grantTicketGrantingTicket(this.uniqueTicketIdGenerator.getNewTicketId(TicketGrantingTicket.PREFIX), a,
            new NeverExpiresExpirationPolicy());

    try {
        s.grantTicketGrantingTicket(this.uniqueTicketIdGenerator.getNewTicketId(TicketGrantingTicket.PREFIX), a,
                new NeverExpiresExpirationPolicy());
        fail("Exception expected.");
    } catch (final Exception e) {
        return;
    }
}
 
Example #13
Source File: CentralAuthenticationServiceImplTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyValidateServiceTicketWithInvalidUsernameAttribute() throws Exception {
    final UsernamePasswordCredential cred =  TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(cred);

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

    final Assertion assertion = getCentralAuthenticationService().validateServiceTicket(serviceTicket.getId(), 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 #14
Source File: OpenIdSingleSignOnActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifySuccessfulServiceTicket() throws Exception {
    final MockRequestContext context = new MockRequestContext();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final Authentication authentication = TestUtils.getAuthentication("scootman28");
    final TicketGrantingTicket t = new TicketGrantingTicketImpl("TGT-11", authentication,
            new NeverExpiresExpirationPolicy());

    this.ticketRegistry.addTicket(t);

    request.setParameter(OpenIdConstants.OPENID_IDENTITY, "http://openid.aol.com/scootman28");
    request.setParameter(OpenIdConstants.OPENID_RETURNTO, "http://www.cnn.com");

    final OpenIdService service = OpenIdService.createServiceFrom(request, null);
    context.getFlowScope().put("service", service);
    context.getFlowScope().put("ticketGrantingTicketId", t.getId());

    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request,
            new MockHttpServletResponse()));
    assertEquals("success", this.action.execute(context).getId());
}
 
Example #15
Source File: Cas10ResponseViewTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.model = new HashMap<String, Object>();
    List<Authentication> list = new ArrayList<Authentication>();
    list.add(TestUtils.getAuthentication("someothername"));
    this.model.put("assertion", new ImmutableAssertion(
            TestUtils.getAuthentication(), list, TestUtils.getService("TestService"), true));
}
 
Example #16
Source File: OAuth20ProfileControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testOK() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.PROFILE_URL);
    mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, TGT_ID);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    final TicketRegistry ticketRegistry = mock(TicketRegistry.class);
    final TicketGrantingTicket ticketGrantingTicket = mock(TicketGrantingTicket.class);
    when(ticketGrantingTicket.isExpired()).thenReturn(false);
    when(ticketRegistry.getTicket(TGT_ID)).thenReturn(ticketGrantingTicket);
    final Authentication authentication = mock(Authentication.class);
    final Principal principal = mock(Principal.class);
    when(principal.getId()).thenReturn(ID);
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put(NAME, VALUE);
    List<String> list = Arrays.asList(VALUE, VALUE);
    map.put(NAME2, list);
    when(principal.getAttributes()).thenReturn(map);
    when(authentication.getPrincipal()).thenReturn(principal);
    when(ticketGrantingTicket.getAuthentication()).thenReturn(authentication);
    oauth20WrapperController.setTicketRegistry(ticketRegistry);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(200, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());
    assertEquals("{\"id\":\"" + ID + "\",\"attributes\":[{\"" + NAME + "\":\"" + VALUE + "\"},{\"" + NAME2
            + "\":[\"" + VALUE + "\",\"" + VALUE + "\"]}]}", mockResponse.getContentAsString());
}
 
Example #17
Source File: Saml10SuccessResponseViewTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponse() throws Exception {
    final Map<String, Object> model = new HashMap<String, Object>();

    final Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("testAttribute", "testValue");
    attributes.put("testEmptyCollection", Collections.emptyList());
    attributes.put("testAttributeCollection", Arrays.asList(new String[] {"tac1", "tac2"}));
    final SimplePrincipal principal = new SimplePrincipal("testPrincipal", attributes);

    final Map<String, Object> authAttributes = new HashMap<String, Object>();
    authAttributes.put(
            SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD,
            SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT);
    authAttributes.put("testSamlAttribute", "value");

    final Authentication primary = TestUtils.getAuthentication(principal, authAttributes);
    final Assertion assertion = new ImmutableAssertion(
            primary, Collections.singletonList(primary), TestUtils.getService(), true);
    model.put("assertion", assertion);

    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();

    assertTrue(written.contains("testPrincipal"));
    assertTrue(written.contains("testAttribute"));
    assertTrue(written.contains("testValue"));
    assertFalse(written.contains("testEmptyCollection"));
    assertTrue(written.contains("testAttributeCollection"));
    assertTrue(written.contains("tac1"));
    assertTrue(written.contains("tac2"));
    assertTrue(written.contains(SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT));
    assertTrue(written.contains("AuthenticationMethod"));
    assertTrue(written.contains("AssertionID"));
}
 
Example #18
Source File: CacheCredentialsMetaDataPopulatorTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyAttributePopulationWithPassword() {
    final Authentication auth = TestUtils.getAuthentication();
    final Map<String, String> map = new HashMap<>();
    final CacheCredentialsMetaDataPopulator populator = new CacheCredentialsMetaDataPopulator(map);

    final UsernamePasswordCredential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    populator.populateAttributes(DefaultAuthenticationBuilder.newInstance(auth), c);

    assertTrue(map.containsKey(auth.getPrincipal().getId()));
    assertEquals(map.get(auth.getPrincipal().getId()), c.getPassword());
}
 
Example #19
Source File: CacheCredentialsMetaDataPopulator.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public void populateAttributes(final AuthenticationBuilder builder, final Credential credential) {
    if (credential instanceof UsernamePasswordCredential) {
        final UsernamePasswordCredential c = (UsernamePasswordCredential) credential;
        final Authentication authentication = builder.build();
        this.credentialCache.put(authentication.getPrincipal().getId(), c.getPassword());
    }
}
 
Example #20
Source File: CentralAuthenticationServiceImplTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyValidateServiceTicketReturnAllAttributes() throws Exception {
    final Service service = TestUtils.getService("eduPersonTest");
    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();
    assertEquals(3, auth.getPrincipal().getAttributes().size());
}
 
Example #21
Source File: MultiFactorUtils.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Generate the string the indicates the list of satisfied authentication methods.
 * Methods are separated by a space.
 * @param authentication the authentication carrying the methods.
 * @return the space-delimited list of authentication methods, or null if none is available
 */
public static String getFulfilledAuthenticationMethodsAsString(final Authentication authentication) {
    final Set<String> previouslyAchievedAuthenticationMethods = getSatisfiedAuthenticationMethods(authentication);
    if (!previouslyAchievedAuthenticationMethods.isEmpty()) {
        return StringUtils.join(previouslyAchievedAuthenticationMethods, " ");
    }
    return null;
}
 
Example #22
Source File: RememberMeAuthenticationMetaDataPopulatorTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyWithTrueRememberMeCredentials() {
    final RememberMeUsernamePasswordCredential c = new RememberMeUsernamePasswordCredential();
    c.setRememberMe(true);
    final AuthenticationBuilder builder = newBuilder(c);
    final Authentication auth = builder.build();

    assertEquals(true, auth.getAttributes().get(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME));
}
 
Example #23
Source File: CentralAuthenticationServiceImplTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateServiceTicketAnonymous() throws Exception {
    final Service service = TestUtils.getService("testAnonymous");
    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();
    assertNotEquals(cred.getUsername(), auth.getPrincipal().getId());
}
 
Example #24
Source File: ImmutableAssertionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEqualsWithValidObject() {
    final List<Authentication> list1 = new ArrayList<>();
    final List<Authentication> list2 = new ArrayList<>();

    final Authentication auth = TestUtils.getAuthentication();
    list1.add(auth);
    list2.add(auth);

    final ImmutableAssertion assertion1 = new ImmutableAssertion(auth, list1, TestUtils.getService(), true);
    final ImmutableAssertion assertion2 = new ImmutableAssertion(auth, list2, TestUtils.getService(), true);

    assertTrue(assertion1.equals(assertion2));
}
 
Example #25
Source File: ImmutableAssertionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGetterFalseForNewLogin() {
    final List<Authentication> list = new ArrayList<>();

    list.add(TestUtils.getAuthentication());

    final ImmutableAssertion assertion = new ImmutableAssertion(
            TestUtils.getAuthentication(), list, TestUtils.getService(), false);

    assertFalse(assertion.isFromNewLogin());
}
 
Example #26
Source File: ImmutableAssertionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGettersForChainedPrincipals() {
    final List<Authentication> list = new ArrayList<>();

    list.add(TestUtils.getAuthentication("test"));
    list.add(TestUtils.getAuthentication("test1"));
    list.add(TestUtils.getAuthentication("test2"));

    final ImmutableAssertion assertion = new ImmutableAssertion(
            TestUtils.getAuthentication(), list, TestUtils.getService(), true);

    assertEquals(list.toArray(new Authentication[0]).length, assertion.getChainedAuthentications().size());
}
 
Example #27
Source File: RememberMeDelegatingExpirationPolicyTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyTicketExpirationWithRememberMe() {
    final Authentication authentication = TestUtils.getAuthentication(
            this.principalFactory.createPrincipal("test"),
            Collections.<String, Object>singletonMap(
                    RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, true));
    final TicketGrantingTicketImpl t = new TicketGrantingTicketImpl("111", authentication, this.p);
    assertFalse(t.isExpired());
    t.grantServiceTicket("55", TestUtils.getService(), this.p, false);
    assertTrue(t.isExpired());

}
 
Example #28
Source File: Saml10SuccessResponseViewTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyResponseWithNoAttributes() throws Exception {
    final Map<String, Object> model = new HashMap<>();

    final Principal principal = new DefaultPrincipalFactory().createPrincipal("testPrincipal");

    final Map<String, Object> authAttributes = new HashMap<>();
    authAttributes.put(
            SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD,
            SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT);
    authAttributes.put("testSamlAttribute", "value");

    final Authentication primary = TestUtils.getAuthentication(principal, authAttributes);

    final Assertion assertion = new ImmutableAssertion(
            primary, Collections.singletonList(primary), TestUtils.getService(), true);
    model.put("assertion", assertion);

    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();

    assertTrue(written.contains("testPrincipal"));
    assertTrue(written.contains(SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT));
    assertTrue(written.contains("AuthenticationMethod="));
}
 
Example #29
Source File: CentralAuthenticationServiceImpl.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@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 #30
Source File: MultiFactorCredentials.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Enumerates the list of available principals in the authentication chain
 * and ensures that the newly given and provided principal is compliant
 * and equals the rest of the principals in the chain. The match
 * is explicitly controlled by {@link Principal#equals(Object)}
 * implementation.
 *
 * @param authentication the authentication object whose principal is compared against the chain
 * @return true if no mismatch is found; false otherwise.
 */
private boolean doesPrincipalMatchAuthenticationChain(final Authentication authentication) {
    for (final Authentication authn : this.chainedAuthentication) {
        final Principal currentPrincipal = authn.getPrincipal();
        final Principal newPrincipal = authentication.getPrincipal();

        if (!currentPrincipal.equals(newPrincipal)) {
            return false;
        }
    }
    return true;
}