org.jasig.cas.authentication.UsernamePasswordCredential Java Examples

The following examples show how to use org.jasig.cas.authentication.UsernamePasswordCredential. 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: SearchModeSearchDatabaseAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    final String username = credential.getUsername();
    final String encyptedPassword = getPasswordEncoder().encode(credential.getPassword());
    final int count;
    try {
        count = getJdbcTemplate().queryForObject(this.sql, Integer.class, username, encyptedPassword);
    } catch (final DataAccessException e) {
        throw new PreventedException("SQL exception while executing query for " + username, e);
    }
    if (count == 0) {
        throw new FailedLoginException(username + " not found with SQL query.");
    }
    return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
}
 
Example #2
Source File: RadiusAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    final String username = credential.getUsername();
    for (final RadiusServer radiusServer : this.servers) {
        logger.debug("Attempting to authenticate {} at {}", username, radiusServer);
        try {
            if (radiusServer.authenticate(username, credential.getPassword())) {
                return createHandlerResult(credential, new SimplePrincipal(username), null);
            } 
            
            if (!this.failoverOnAuthenticationFailure) {
                throw new FailedLoginException();
            }
            logger.debug("failoverOnAuthenticationFailure enabled -- trying next server");
        } catch (final PreventedException e) {
            if (!this.failoverOnException) {
                throw e;
            }
            logger.warn("failoverOnException enabled -- trying next server.", e);
        }
    }
    throw new FailedLoginException();
}
 
Example #3
Source File: SimpleTestUsernamePasswordAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@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 HandlerResult(this, new BasicCredentialMetaData(credential));
    }
    logger.debug("User [{}] failed authentication", username);
    throw new FailedLoginException();
}
 
Example #4
Source File: FileAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {
    try {
        
        final String username = credential.getUsername();
        final String passwordOnRecord = getPasswordOnRecord(username);
        if (passwordOnRecord == null) {
            throw new AccountNotFoundException(username + " not found in backing file.");
        }
        if (credential.getPassword() != null
                && this.getPasswordEncoder().encode(credential.getPassword()).equals(passwordOnRecord)) {
            return createHandlerResult(credential, new SimplePrincipal(username), null);
        }
    } catch (final IOException e) {
        throw new PreventedException("IO error reading backing file", e);
    }
    throw new FailedLoginException();
}
 
Example #5
Source File: SamlAuthenticationMetaDataPopulator.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Instantiates a new SAML authentication meta data populator.
 */
public SamlAuthenticationMetaDataPopulator() {
    this.authenticationMethods.put(
            HttpBasedServiceCredential.class.getName(),
            AUTHN_METHOD_SSL_TLS_CLIENT);
    this.authenticationMethods.put(
            UsernamePasswordCredential.class.getName(),
            AUTHN_METHOD_PASSWORD);

    // Next two classes are in other modules, so avoid using Class#getName() to prevent circular dependency
    this.authenticationMethods.put(
            "org.jasig.cas.adaptors.trusted.authentication.principal.PrincipalBearingCredentials",
            AUTHN_METHOD_UNSPECIFIED);
    this.authenticationMethods.put(
            "org.jasig.cas.adaptors.x509.authentication.principal.X509CertificateCredentials",
            AUTHN_METHOD_X509_PUBLICKEY);
}
 
Example #6
Source File: TicketResource.java    From springboot-shiro-cas-mybatis with 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 #7
Source File: AbstractUsernamePasswordAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 **/
@Override
protected final HandlerResult doAuthentication(final Credential credential)
        throws GeneralSecurityException, PreventedException {
    final UsernamePasswordCredential userPass = (UsernamePasswordCredential) credential;
    if (userPass.getUsername() == null) {
        throw new AccountNotFoundException("Username is null.");
    }
    
    final String transformedUsername= this.principalNameTransformer.transform(userPass.getUsername());
    if (transformedUsername == null) {
        throw new AccountNotFoundException("Transformed username is null.");
    }
    userPass.setUsername(transformedUsername);
    return authenticateUsernamePasswordInternal(userPass);
}
 
Example #8
Source File: FileAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {
    try {
        final String username = credential.getUsername();
        final String passwordOnRecord = getPasswordOnRecord(username);
        if (StringUtils.isBlank(passwordOnRecord)) {
            throw new AccountNotFoundException(username + " not found in backing file.");
        }
        final String password = credential.getPassword();
        if (StringUtils.isNotBlank(password) && this.getPasswordEncoder().encode(password).equals(passwordOnRecord)) {
            return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
        }
    } catch (final IOException e) {
        throw new PreventedException("IO error reading backing file", e);
    }
    throw new FailedLoginException();
}
 
Example #9
Source File: SamlAuthenticationMetaDataPopulator.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
public SamlAuthenticationMetaDataPopulator() {
    this.authenticationMethods.put(
            HttpBasedServiceCredential.class.getName(),
            AUTHN_METHOD_SSL_TLS_CLIENT);
    this.authenticationMethods.put(
            UsernamePasswordCredential.class.getName(),
            AUTHN_METHOD_PASSWORD);

    // Next two classes are in other modules, so avoid using Class#getName() to prevent circular dependency
    this.authenticationMethods.put(
            "org.jasig.cas.adaptors.trusted.authentication.principal.PrincipalBearingCredentials",
            AUTHN_METHOD_UNSPECIFIED);
    this.authenticationMethods.put(
            "org.jasig.cas.adaptors.x509.authentication.principal.X509CertificateCredentials",
            AUTHN_METHOD_X509_PUBLICKEY);
}
 
Example #10
Source File: FileAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void verifyFailsGoodUsernameBadPassword() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    this.authenticationHandler.setFileName(
            new ClassPathResource("org/jasig/cas/adaptors/generic/authentication2.txt"));
    this.authenticationHandler.setSeparator(",");

    c.setUsername("scott");
    c.setPassword("rutgers1");

    this.authenticationHandler.authenticate(c);
}
 
Example #11
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 #12
Source File: TicketResource.java    From cas4.0.x-server-wechat with 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 #13
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyEncodeDecodeTGTImpl() throws Exception {
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final AuthenticationBuilder bldr = new DefaultAuthenticationBuilder(
            new DefaultPrincipalFactory()
                    .createPrincipal("user", Collections.unmodifiableMap(this.principalAttributes)));
    bldr.setAttributes(Collections.unmodifiableMap(this.principalAttributes));
    bldr.setAuthenticationDate(new Date());
    bldr.addCredential(new BasicCredentialMetaData(userPassCredential));
    bldr.addFailure("error", AccountNotFoundException.class);
    bldr.addSuccess("authn", new DefaultHandlerResult(
            new AcceptUsersAuthenticationHandler(),
            new BasicCredentialMetaData(userPassCredential)));

    final TicketGrantingTicket parent =
            new TicketGrantingTicketImpl(TGT_ID, TestUtils.getService(), null, bldr.build(),
                    new NeverExpiresExpirationPolicy());

    final TicketGrantingTicket expectedTGT =
            new TicketGrantingTicketImpl(TGT_ID, TestUtils.getService(),
                    null, bldr.build(),
                    new NeverExpiresExpirationPolicy());

    final ServiceTicket ticket = expectedTGT.grantServiceTicket(ST_ID,
            TestUtils.getService(),
            new NeverExpiresExpirationPolicy(), false);
    CachedData result = transcoder.encode(expectedTGT);
    final TicketGrantingTicket resultTicket = (TicketGrantingTicket) transcoder.decode(result);

    assertEquals(expectedTGT, resultTicket);
    result = transcoder.encode(ticket);
    final ServiceTicket resultStTicket = (ServiceTicket) transcoder.decode(result);
    assertEquals(ticket, resultStTicket);

}
 
Example #14
Source File: PrincipalBearingCredentialsAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifySupports() {
    final PrincipalBearingCredential credentials =
            new PrincipalBearingCredential(new DefaultPrincipalFactory().createPrincipal("scott"));
    assertTrue(this.handler.supports(credentials));
    assertFalse(this.handler.supports(new UsernamePasswordCredential()));
}
 
Example #15
Source File: FileAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test(expected = PreventedException.class)
public void verifyAuthenticateNoFileName() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();
    this.authenticationHandler.setFileName(new ClassPathResource("fff"));

    c.setUsername("scott");
    c.setPassword("rutgers");

    this.authenticationHandler.authenticate(c);
}
 
Example #16
Source File: RejectUsersAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test(expected=FailedLoginException.class)
public void verifyFailsUserInMap() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername("scott");
    c.setPassword("rutgers");
    this.authenticationHandler.authenticate(c);
}
 
Example #17
Source File: RejectUsersAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test(expected = AccountNotFoundException.class)
public void testPassesNullUserName() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername(null);
    c.setPassword("user");

    this.authenticationHandler.authenticate(c);
}
 
Example #18
Source File: FileAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test(expected = AccountNotFoundException.class)
public void verifyFailsNullUserName() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername(null);
    c.setPassword("user");
    this.authenticationHandler.authenticate(c);
}
 
Example #19
Source File: AuthenticationViaFormActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
   public void testTestBindingWithCredentialsBinder() throws Exception {
       final MockRequestContext context = new MockRequestContext();
       context.setExternalContext(new ServletExternalContext(
           new MockServletContext(), new MockHttpServletRequest(),
           new MockHttpServletResponse()));
 //      context.setLastEvent(new Event(this, "test"));

       final CredentialsBinder cb = new CredentialsBinder(){

           public void bind(final HttpServletRequest request, final Credential credentials) {
               ((UsernamePasswordCredential) credentials)
                   .setUsername("test2");
               ((UsernamePasswordCredential) credentials)
                   .setPassword("test2");
           }

           public boolean supports(final Class<?> clazz) {
               return true;
           }

       };
       this.action.setCredentialsBinder(cb);
  //     this.action.bindAndValidate(context);

//       assertEquals(
//           "test2",
//           ((UsernamePasswordCredential) context
//               .getFlowScope().get(
//                   "credentials")).getUsername());

   }
 
Example #20
Source File: TestUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public static UsernamePasswordCredential getCredentialsWithDifferentUsernameAndPassword(
    final String username, final String password) {
    // noinspection LocalVariableOfConcreteClass
    final UsernamePasswordCredential usernamePasswordCredentials = new UsernamePasswordCredential();
    usernamePasswordCredentials.setUsername(username);
    usernamePasswordCredentials.setPassword(password);

    return usernamePasswordCredentials;
}
 
Example #21
Source File: FileAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test(expected = PreventedException.class)
public void testAuthenticateNoFileName() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();
    this.authenticationHandler.setFileName(new ClassPathResource("fff"));

    c.setUsername("scott");
    c.setPassword("rutgers");

    this.authenticationHandler.authenticate(c);
}
 
Example #22
Source File: FileAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test(expected = AccountNotFoundException.class)
public void testFailsNullUserNameAndPassword() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername(null);
    c.setPassword(null);
    this.authenticationHandler.authenticate(c);
}
 
Example #23
Source File: FileAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test(expected = AccountNotFoundException.class)
public void testFailsNullUserName() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername(null);
    c.setPassword("user");
    this.authenticationHandler.authenticate(c);
}
 
Example #24
Source File: FileAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test(expected = AccountNotFoundException.class)
public void verifyFailsUserNotInFileWithDefaultSeparator() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername("fds");
    c.setPassword("rutgers");
    this.authenticationHandler.authenticate(c);
}
 
Example #25
Source File: RejectUsersAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifySupportsProperUserCredentials() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername("fff");
    c.setPassword("rutgers");
    assertNotNull(this.authenticationHandler.authenticate(c));
}
 
Example #26
Source File: TicketsResource.java    From taoshop with Apache License 2.0 5 votes vote down vote up
@Override
public Credential fromRequestBody(@NotNull final MultiValueMap<String, String> requestBody) {
    final String username = requestBody.getFirst("username");
    final String password = requestBody.getFirst("password");
    if(username == null || password == null) {
        throw new BadRequestException("Invalid payload. 'username' and 'password' form fields are required.");
    }
    return new UsernamePasswordCredential(requestBody.getFirst("username"), requestBody.getFirst("password"));
}
 
Example #27
Source File: TestUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public static Authentication getAuthentication(final Principal principal, final Map<String, Object> attributes) {
    final AuthenticationHandler handler = new SimpleTestUsernamePasswordAuthenticationHandler();
    final CredentialMetaData meta = new BasicCredentialMetaData(new UsernamePasswordCredential());
    return new AuthenticationBuilder(principal)
            .addCredential(meta)
            .addSuccess("testHandler", new HandlerResult(handler, meta))
            .setAttributes(attributes)
            .build();
}
 
Example #28
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 #29
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 #30
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)));
}