javax.security.auth.login.AccountNotFoundException Java Examples

The following examples show how to use javax.security.auth.login.AccountNotFoundException. 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: 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 #2
Source File: AcceptUsersAuthenticationHandler.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 {

    final String username = credential.getUsername();
    final String cachedPassword = this.users.get(username);

    if (cachedPassword == null) {
       logger.debug("{} was not found in the map.", username);
       throw new AccountNotFoundException(username + " not found in backing map.");
    }

    final String encodedPassword = this.getPasswordEncoder().encode(credential.getPassword());
    if (!cachedPassword.equals(encodedPassword)) {
        throw new FailedLoginException();
    }
    return createHandlerResult(credential, new SimplePrincipal(username), null);
}
 
Example #3
Source File: AbstractPasswordFilePrincipalDatabase.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
/**
 * SASL Callback Mechanism - sets the Password in the PasswordCallback based on the value in the PasswordFile
 * If you want to change the password for a user, use updatePassword instead.
 *
 * @param principal The Principal to set the password for
 * @param callback  The PasswordCallback to call setPassword on
 *
 * @throws javax.security.auth.login.AccountNotFoundException If the Principal cannot be found in this Database
 */
@Override
public final void setPassword(Principal principal, PasswordCallback callback) throws AccountNotFoundException
{
    if (_passwordFile == null)
    {
        throw new AccountNotFoundException("Unable to locate principal since no password file was specified during initialisation");
    }
    if (principal == null)
    {
        throw new IllegalArgumentException("principal must not be null");
    }
    char[] pwd = lookupPassword(principal.getName());

    if (pwd != null)
    {
        callback.setPassword(pwd);
    }
    else
    {
        throw new AccountNotFoundException("No account found for principal " + principal);
    }
}
 
Example #4
Source File: AbstractUsernamePasswordAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 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 #5
Source File: Base64MD5PasswordFilePrincipalDatabaseTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyPassword() throws IOException, AccountNotFoundException
{
    testCreateUserPrincipal();
    //assertFalse(_pwdDB.verifyPassword(_username, null));
    assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, new char[]{}));
    assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, (PASSWORD + "z").toCharArray()));
    assertTrue(_database.verifyPassword(PRINCIPAL_USERNAME, PASSWORD.toCharArray()));

    try
    {
        _database.verifyPassword("made.up.username", PASSWORD.toCharArray());
        fail("Should not have been able to verify this nonexistent users password.");
    }
    catch (AccountNotFoundException e)
    {
        // pass
    }
}
 
Example #6
Source File: PrincipalDatabaseAuthenticationManager.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
protected void changeAttributes(final Map<String, Object> attributes)
{
    if(attributes.containsKey(PASSWORD))
    {
        try
        {
            String desiredPassword = (String) attributes.get(PASSWORD);
            boolean changed = getPrincipalDatabase().updatePassword(_user, desiredPassword.toCharArray());
            if (!changed)
            {
                throw new IllegalStateException(String.format("Failed to user password for user : '%s'", getName()));
            }
        }
        catch(AccountNotFoundException e)
        {
            throw new IllegalStateException(e);
        }
    }
    super.changeAttributes(attributes);
}
 
Example #7
Source File: PlainPasswordFilePrincipalDatabaseTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyPassword() throws IOException, AccountNotFoundException
{
    createUserPrincipal();
    assertFalse(_database.verifyPassword(TEST_USERNAME, new char[]{}));
    assertFalse(_database.verifyPassword(TEST_USERNAME, "massword".toCharArray()));
    assertTrue(_database.verifyPassword(TEST_USERNAME, TEST_PASSWORD_CHARS));

    try
    {
        _database.verifyPassword("made.up.username", TEST_PASSWORD_CHARS);
        fail("Should not have been able to verify this non-existant users password.");
    }
    catch (AccountNotFoundException e)
    {
        // pass
    }
}
 
Example #8
Source File: LdapAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateNotFound() throws Exception {
    if (!this.supportsNotFound) {
        return;
    }
    String username;
    for (final LdapEntry entry : this.testEntries) {
        username = getUsername(entry);
        try {
            this.handler.authenticate(new UsernamePasswordCredential("nobody", "badpassword"));
            fail("Should have thrown AccountNotFoundException.");
        } catch (final AccountNotFoundException e) {
            assertNotNull(e.getMessage());
        }
    }
}
 
Example #9
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 #10
Source File: AuthorizationServiceImpl.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
@Override
public SecurityContext authorize(final AuthorizationRequestContext authRequestContext) {

    String[] userAndPassword = BasicAuthHelper.decode(authRequestContext.getAuthorizationToken());
    if (userAndPassword == null || userAndPassword.length != 2) {
        logger.error("Bad credentials: {}", authRequestContext.getAuthorizationToken());
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
    }
    String userName = userAndPassword[0];
    String password = userAndPassword[1];

    String apiKey = null;
    Account account = null;
    try {
        account = loginManager.login(apiKey);
    } catch (AccountNotFoundException e) {
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
    }
    return SecurityContextImpl.with().principal(account).roles(account.getRoles()).build();
}
 
Example #11
Source File: PrincipalDatabaseAuthenticationManager.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.qpid.server.security.auth.manager.UsernamePasswordAuthenticationProvider#authenticate(String, String)
 */
@Override
public AuthenticationResult authenticate(final String username, final String password)
{
    try
    {
        if (_principalDatabase.verifyPassword(username, password.toCharArray()))
        {
            return new AuthenticationResult(new UsernamePrincipal(username, this));
        }
        else
        {
            return new AuthenticationResult(AuthenticationStatus.ERROR);
        }
    }
    catch (AccountNotFoundException e)
    {
        return new AuthenticationResult(AuthenticationStatus.ERROR);
    }
}
 
Example #12
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 #13
Source File: AcceptUsersAuthenticationHandler.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 cachedPassword = this.users.get(username);

    if (cachedPassword == null) {
       logger.debug("{} was not found in the map.", username);
       throw new AccountNotFoundException(username + " not found in backing map.");
    }

    final String encodedPassword = this.getPasswordEncoder().encode(credential.getPassword());
    if (!cachedPassword.equals(encodedPassword)) {
        throw new FailedLoginException();
    }
    return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
}
 
Example #14
Source File: AuthenticationResource.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@GET
@ApiOperation(value = "Authentication for respondents", response = AbstractAccount.class)
public Response authenticate(
        @NotNull @QueryParam("invitation") @ApiParam(value = "Invitation token", required = true) String invitation)
        throws AccountNotFoundException {
    logger.info("New respondent authentication petition received");
    AuthenticationManager authManager = authenticationManagerFactory.getObject(AccountType.RESPONDENT);

    Account account = authManager.authenticate(RespondentAccount.USER_NAME, invitation);
    return Response.ok(account).build();
}
 
Example #15
Source File: AuthDataAccessor.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected boolean authenticate(final User user, final String password) {
    boolean authenticated = ENCRYPTOR.verify(password, user.getCipherAlgorithm(), user.getPassword());
    LOG.debug("{} authenticated on internal storage: {}", user.getUsername(), authenticated);

    for (Iterator<? extends ExternalResource> itor = getPassthroughResources(user).iterator();
            itor.hasNext() && !authenticated;) {

        ExternalResource resource = itor.next();
        String connObjectKey = null;
        try {
            AnyType userType = anyTypeDAO.findUser();
            Optional<? extends Provision> provision = resource.getProvision(userType);
            if (provision.isEmpty()) {
                throw new AccountNotFoundException("Unable to locate provision for user type " + userType.getKey());
            }
            Optional<String> connObjectKeyValue = mappingManager.getConnObjectKeyValue(user, provision.get());
            if (connObjectKeyValue.isEmpty()) {
                throw new AccountNotFoundException(
                        "Unable to locate conn object key value for " + userType.getKey());
            }
            connObjectKey = connObjectKeyValue.get();
            Uid uid = connFactory.getConnector(resource).authenticate(connObjectKey, password, null);
            if (uid != null) {
                authenticated = true;
            }
        } catch (Exception e) {
            LOG.debug("Could not authenticate {} on {}", user.getUsername(), resource.getKey(), e);
        }
        LOG.debug("{} authenticated on {} as {}: {}",
                user.getUsername(), resource.getKey(), connObjectKey, authenticated);
    }

    return authenticated;
}
 
Example #16
Source File: RespondentAuthenticationManagerTest.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void authenticateTest() throws AccountNotFoundException, SignatureException {
    Account account = authenticationManager.authenticate("respondent", "90POKHJE16");
    assertThat(account).isInstanceOf(RespondentAccount.class);
    RespondentAccount respondentAccount = (RespondentAccount) account;

    assertThat(respondentAccount.getGivenNames()).isEqualTo("Tyrion");
    assertThat(respondentAccount.getGrantedquestionnaireIds()).contains(73);

    account = authenticationManager.authenticate("respondent", "SYZPVHYMLK");
    assertThat(account).isInstanceOf(RespondentAccount.class);
    respondentAccount = (RespondentAccount) account;
    assertThat(respondentAccount.getGivenNames()).isEqualTo("anonymous");
    String secret = account.getSecret();
    assertThat(secret).isNotNull();

    int grantedQuestionnair = respondentAccount.getGrantedquestionnaireIds().iterator().next();
    String date = DateFormatUtils.SMTP_DATETIME_FORMAT.format(new Date());
    String resource = "/questionnaires/" + grantedQuestionnair;
    String method = "GET";
    String stringToSign = new StringBuilder().append(method).append(" ").append(resource).append("\n").append(date)
            .toString();
    String apiKey = respondentAccount.getApiKey();

    String signature = HMACSignature.calculateRFC2104HMAC(stringToSign, secret);

    AuthenticationToken token = new HmacAuthToken.Builder().apiKey(apiKey).signature(signature).dateUTC(date)
            .message(stringToSign).build();

    Subject subject = SecurityUtils.getSubject();
    subject.login(token);

    boolean isPermitted = subject.isPermitted("questionnaire:read:" + grantedQuestionnair);
    assertThat(isPermitted);
}
 
Example #17
Source File: PlainPasswordFilePrincipalDatabaseTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdatePassword() throws IOException, AccountNotFoundException
{
    createUserPrincipal();
    char[] newPwd = "newpassword".toCharArray();
    _database.updatePassword(_principal, newPwd);
    assertFalse(_database.verifyPassword(TEST_USERNAME, TEST_PASSWORD_CHARS));
    assertTrue(_database.verifyPassword(TEST_USERNAME, newPwd));
}
 
Example #18
Source File: Base64MD5PasswordFilePrincipalDatabaseTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdatePassword() throws IOException, AccountNotFoundException
{
    testCreateUserPrincipal();
    char[] newPwd = "newpassword".toCharArray();
    _database.updatePassword(PRINCIPAL, newPwd);
    assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, PASSWORD.toCharArray()));
    assertTrue(_database.verifyPassword(PRINCIPAL_USERNAME, newPwd));
}
 
Example #19
Source File: PlainPasswordFilePrincipalDatabase.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
/**
 * Used to verify that the presented Password is correct. Currently only used by Management Console
 *
 * @param principal The principal to authenticate
 * @param password  The plaintext password to check
 *
 * @return true if password is correct
 *
 * @throws AccountNotFoundException if the principal cannot be found
 */
@Override
public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException
{

    char[] pwd = lookupPassword(principal);

    if (pwd == null)
    {
        throw new AccountNotFoundException("Unable to lookup the specified users password");
    }

    return compareCharArray(pwd, password);

}
 
Example #20
Source File: AbstractPasswordFilePrincipalDatabase.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean deletePrincipal(Principal principal) throws AccountNotFoundException
{
    U user = _userMap.get(principal.getName());

    if (user == null)
    {
        throw new AccountNotFoundException(principal.getName());
    }

    try
    {
        _userUpdate.lock();
        user.delete();

        try
        {
            savePasswordFile();
        }
        catch (IOException e)
        {
            getLogger().error("Unable to remove user '{}' from password file.", user.getName());
            return false;
        }

        _userMap.remove(user.getName());
    }
    finally
    {
        _userUpdate.unlock();
    }

    return true;
}
 
Example #21
Source File: ConfigModelPasswordManagingAuthenticationProvider.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteUser(final String user) throws AccountNotFoundException
{
    final ManagedUser authUser = getUser(user);
    if(authUser != null)
    {
        authUser.delete();
    }
    else
    {
        throw new AccountNotFoundException("No such user: '" + user + "'");
    }
}
 
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 testFailsUserNotInFileWithCommaSeparator() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

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

    c.setUsername("fds");
    c.setPassword("rutgers");
    this.authenticationHandler.authenticate(c);
}
 
Example #23
Source File: QueryDatabaseAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test(expected = AccountNotFoundException.class)
public void verifyAuthenticationFailsToFindUser() throws Exception {
    final QueryDatabaseAuthenticationHandler q = new QueryDatabaseAuthenticationHandler();
    q.setDataSource(this.dataSource);
    q.setSql(SQL);
    q.authenticateUsernamePasswordInternal(
            TestUtils.getCredentialsWithDifferentUsernameAndPassword("usernotfound", "psw1"));

}
 
Example #24
Source File: UsernamePasswordSystemAuthenticationHandler.java    From sso with MIT License 5 votes vote down vote up
@Override
protected HandlerResult doAuthentication(Credential credential) throws GeneralSecurityException, PreventedException {
    //当用户名为admin,并且system为sso即允许通过
    UsernamePasswordSysCredential sysCredential = (UsernamePasswordSysCredential) credential;
    if ("admin".equals(sysCredential.getUsername()) && "sso".equals(sysCredential.getSystem())) {
        //这里可以自定义属性数据
        return createHandlerResult(credential, this.principalFactory.createPrincipal(((UsernamePasswordSysCredential) credential).getUsername(), Collections.emptyMap()), null);
    } else {
        throw new AccountNotFoundException("必须是admin用户才允许通过");
    }
}
 
Example #25
Source File: SimpleAuthenticationManager.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public void setPassword(final String username, final String password) throws AccountNotFoundException
{
    if (_users.containsKey(username))
    {
        _users.put(username, password);
    }
    else
    {
        throw new AccountNotFoundException("No such user: '" + username + "'");
    }
}
 
Example #26
Source File: SimpleAuthenticationManager.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteUser(final String username) throws AccountNotFoundException
{
    if (_users.remove(username) == null)
    {
        throw new AccountNotFoundException("No such user: '" + username + "'");
    }
}
 
Example #27
Source File: PrincipalDatabaseAuthenticationManager.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
protected ListenableFuture<Void> onDelete()
{
    try
    {
        String userName = _user.getName();
        deleteUserFromDatabase(userName);
    }
    catch (AccountNotFoundException e)
    {
        // pass
    }
    return super.onDelete();
}
 
Example #28
Source File: PrincipalDatabaseAuthenticationManager.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public void setPassword(String username, String password) throws AccountNotFoundException
{
    Principal principal = new UsernamePrincipal(username, this);
    User user = _userMap.get(principal);
    if (user != null)
    {
        user.setPassword(password);
    }
}
 
Example #29
Source File: PrincipalDatabaseAuthenticationManager.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteUser(String username) throws AccountNotFoundException
{
    UsernamePrincipal principal = new UsernamePrincipal(username, this);
    PrincipalAdapter user = _userMap.get(principal);
    if(user != null)
    {
        user.delete();
    }
    else
    {
        throw new AccountNotFoundException("No such user: '" + username + "'");
    }
}
 
Example #30
Source File: AccountNotFoundExceptionHandler.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Exception fired from AuthenticationResource
 */
@Override
public Response toResponse(AccountNotFoundException exception) {
    logger.warn("Login access failure: {}", exception.getMessage());
    return Response.status(Status.FORBIDDEN).type(MediaType.APPLICATION_JSON)
            .entity(ErrorEntity.with().message(exception.getMessage()).build()).build();

}