Java 类javax.naming.AuthenticationException 实例源码

项目:Alpine    文件:JwtAuthenticationService.java   
/**
 * {@inheritDoc}
 */
public Principal authenticate() throws AuthenticationException {
    final KeyManager keyManager = KeyManager.getInstance();
    if (bearer != null) {
        final JsonWebToken jwt = new JsonWebToken(keyManager.getSecretKey());
        final boolean isValid = jwt.validateToken(bearer);
        if (isValid) {
            try (AlpineQueryManager qm = new AlpineQueryManager()) {
                if (jwt.getSubject() == null || jwt.getExpiration() == null) {
                    throw new AuthenticationException("Token does not contain a valid subject or expiration");
                }
                final ManagedUser managedUser = qm.getManagedUser(jwt.getSubject());
                if (managedUser != null) {
                    return managedUser;
                }
                final LdapUser ldapUser =  qm.getLdapUser(jwt.getSubject());
                if (ldapUser != null) {
                    return ldapUser;
                }
            }
        }
    }
    return null;
}
项目:Twitch-Streamer    文件:IRC.java   
/**
 * @param response is the first line read after the user logs in. If it fails, close the socket, writer, and reader.
 * @throws AuthenticationException Invalid oauth key.
 * @throws IOException
 */
private void checkAuth(final String response) throws AuthenticationException, IOException {
    if (response.endsWith(Constants.AUTH_FAILED)) {
        closeAll();
        throw new AuthenticationException(Constants.AUTH_FAILED);
    }

    if (response.endsWith(Constants.BAD_AUTH_FORMAT)) {
        closeAll();
        throw new AuthenticationException(Constants.BAD_AUTH_FORMAT);
    }

    if (!response.endsWith(Constants.VALID_AUTH)) {
        closeAll();
        throw new AuthenticationException(Constants.AUTH_FAILED_GENERIC);
    }
}
项目:incubator-pulsar    文件:AuthenticationService.java   
public String authenticateHttpRequest(HttpServletRequest request) throws AuthenticationException {
    // Try to validate with any configured provider
    AuthenticationDataSource authData = new AuthenticationDataHttps(request);
    for (AuthenticationProvider provider : providers.values()) {
        try {
            return provider.authenticate(authData);
        } catch (AuthenticationException e) {
            // Ignore the exception because we don't know which authentication method is expected here.
        }
    }

    // No authentication provided
    if (!providers.isEmpty()) {
        if (StringUtils.isNotBlank(anonymousUserRole)) {
            return anonymousUserRole;
        }
        // If at least a provider was configured, then the authentication needs to be provider
        throw new AuthenticationException("Authentication required");
    } else {
        // No authentication required
        return "<none>";
    }
}
项目:incubator-pulsar    文件:WebSocketWebResource.java   
/**
 * Gets a caller id (IP + role)
 *
 * @return the web service caller identification
 */
public String clientAppId() {
    if (isBlank(clientId)) {
        try {
            clientId = service().getAuthenticationService().authenticateHttpRequest(httpRequest);
        } catch (AuthenticationException e) {
            if (service().getConfig().isAuthenticationEnabled()) {
                throw new RestException(Status.UNAUTHORIZED, "Failed to get clientId from request");
            }
        }

        if (isBlank(clientId) && service().getConfig().isAuthenticationEnabled()) {
            throw new RestException(Status.UNAUTHORIZED, "Failed to get auth data from the request");
        }
    }
    return clientId;
}
项目:incubator-pulsar    文件:AuthenticationFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {
        String role = authenticationService.authenticateHttpRequest((HttpServletRequest) request);
        request.setAttribute(AuthenticatedRoleAttributeName, role);

        if (LOG.isDebugEnabled()) {
            LOG.debug("[{}] Authenticated HTTP request with role {}", request.getRemoteAddr(), role);
        }
    } catch (AuthenticationException e) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication required");
        LOG.warn("[{}] Failed to authenticate HTTP request: {}", request.getRemoteAddr(), e.getMessage());
        return;
    }

    chain.doFilter(request, response);
}
项目:incubator-pulsar    文件:ServerCnxTest.java   
@Test(timeOut = 30000)
public void testConnectCommandWithAuthenticationNegative() throws Exception {
    AuthenticationException e = new AuthenticationException();
    AuthenticationService authenticationService = mock(AuthenticationService.class);
    doReturn(authenticationService).when(brokerService).getAuthenticationService();
    doThrow(e).when(authenticationService).authenticate(new AuthenticationDataCommand(Mockito.anyString()),
            Mockito.anyString());
    doReturn(true).when(brokerService).isAuthenticationEnabled();

    resetChannel();
    assertTrue(channel.isActive());
    assertEquals(serverCnx.getState(), State.Start);

    // test server response to CONNECT
    ByteBuf clientCommand = Commands.newConnect("none", "", null);
    channel.writeInbound(clientCommand);

    assertEquals(serverCnx.getState(), State.Start);
    assertTrue(getResponse() instanceof CommandError);
    channel.finish();
}
项目:incubator-pulsar    文件:AuthenticationProviderAthenzTest.java   
@Test
public void testAuthenticateUnsignedToken() throws Exception {

    List<String> roles = new ArrayList<String>() {
        {
            add("test_role");
        }
    };
    RoleToken token = new RoleToken.Builder("Z1", "test_provider", roles).principal("test_app").build();
    AuthenticationDataSource authData = new AuthenticationDataCommand(token.getUnsignedToken(),
            new InetSocketAddress("localhost", PortManager.nextFreePort()), null);
    try {
        provider.authenticate(authData);
        fail("Unsigned token should not be authenticated");
    } catch (AuthenticationException e) {
        // OK, expected
    }
}
项目:incubator-pulsar    文件:AuthenticationProviderAthenzTest.java   
@Test
public void testAuthenticateSignedTokenWithDifferentDomain() throws Exception {

    List<String> roles = new ArrayList<String>() {
        {
            add("test_role");
        }
    };
    RoleToken token = new RoleToken.Builder("Z1", "invalid", roles).principal("test_app").build();
    String privateKey = new String(Files.readAllBytes(Paths.get("./src/test/resources/zts_private.pem")));
    token.sign(privateKey);
    AuthenticationDataSource authData = new AuthenticationDataCommand(token.getSignedToken(),
            new InetSocketAddress("localhost", PortManager.nextFreePort()), null);
    try {
        provider.authenticate(authData);
        fail("Token which has different domain should not be authenticated");
    } catch (AuthenticationException e) {
        // OK, expected
    }
}
项目:rabbitframework    文件:JndiLdapContextFactory.java   
/**
 * Validates the configuration in the JNDI <code>environment</code> settings and throws an exception if a problem
 * exists.
 * <p/>
 * This implementation will throw a {@link AuthenticationException} if the authentication mechanism is set to
 * 'simple', the principal is non-empty, and the credentials are empty (as per
 * <a href="http://tools.ietf.org/html/rfc4513#section-5.1.2">rfc4513 section-5.1.2</a>).
 *
 * @param environment the JNDI environment settings to be validated
 * @throws AuthenticationException if a configuration problem is detected
 */
protected void validateAuthenticationInfo(Hashtable<String, Object> environment)
    throws AuthenticationException
{
    // validate when using Simple auth both principal and credentials are set
    if(SIMPLE_AUTHENTICATION_MECHANISM_NAME.equals(environment.get(Context.SECURITY_AUTHENTICATION))) {

        // only validate credentials if we have a non-empty principal
        if( environment.get(Context.SECURITY_PRINCIPAL) != null &&
            StringUtils.hasText( String.valueOf( environment.get(Context.SECURITY_PRINCIPAL) ))) {

            Object credentials = environment.get(Context.SECURITY_CREDENTIALS);

            // from the FAQ, we need to check for empty credentials:
            // http://docs.oracle.com/javase/tutorial/jndi/ldap/faq.html
            if( credentials == null ||
                (credentials instanceof byte[] && ((byte[])credentials).length <= 0) || // empty byte[]
                (credentials instanceof char[] && ((char[])credentials).length <= 0) || // empty char[]
                (String.class.isInstance(credentials) && !StringUtils.hasText(String.valueOf(credentials)))) {

                throw new javax.naming.AuthenticationException("LDAP Simple authentication requires both a "
                                                                   + "principal and credentials.");
            }
        }
    }
}
项目:rabbitframework    文件:DefaultLdapContextFactory.java   
/**
 * Validates the configuration in the JNDI <code>environment</code> settings and throws an exception if a problem
 * exists.
 * <p/>
 * This implementation will throw a {@link AuthenticationException} if the authentication mechanism is set to
 * 'simple', the principal is non-empty, and the credentials are empty (as per
 * <a href="http://tools.ietf.org/html/rfc4513#section-5.1.2">rfc4513 section-5.1.2</a>).
 *
 * @param environment the JNDI environment settings to be validated
 * @throws AuthenticationException if a configuration problem is detected
 */
private void validateAuthenticationInfo(Hashtable<String, Object> environment)
    throws AuthenticationException
{
    // validate when using Simple auth both principal and credentials are set
    if(SIMPLE_AUTHENTICATION_MECHANISM_NAME.equals(environment.get(Context.SECURITY_AUTHENTICATION))) {

        // only validate credentials if we have a non-empty principal
        if( environment.get(Context.SECURITY_PRINCIPAL) != null &&
            StringUtils.hasText( String.valueOf( environment.get(Context.SECURITY_PRINCIPAL) ))) {

            Object credentials = environment.get(Context.SECURITY_CREDENTIALS);

            // from the FAQ, we need to check for empty credentials:
            // http://docs.oracle.com/javase/tutorial/jndi/ldap/faq.html
            if( credentials == null ||
                (credentials instanceof byte[] && ((byte[])credentials).length <= 0) || // empty byte[]
                (credentials instanceof char[] && ((char[])credentials).length <= 0) || // empty char[]
                (String.class.isInstance(credentials) && !StringUtils.hasText(String.valueOf(credentials)))) {

                throw new javax.naming.AuthenticationException("LDAP Simple authentication requires both a "
                                                                   + "principal and credentials.");
            }
        }
    }
}
项目:zeppelin    文件:LdapRealm.java   
private Set<String> getRoles(PrincipalCollection principals, 
      final LdapContextFactory ldapContextFactory)
    throws NamingException {
  final String username = (String) getAvailablePrincipal(principals);

  LdapContext systemLdapCtx = null;
  try {
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    return rolesFor(principals, username, systemLdapCtx,
      ldapContextFactory, SecurityUtils.getSubject().getSession());
  } catch (AuthenticationException ae) {
    ae.printStackTrace();
    return Collections.emptySet();
  } finally {
    LdapUtils.closeContext(systemLdapCtx);
  }
}
项目:dropwizard-auth-ldap    文件:LdapAuthenticator.java   
public Optional<User> authenticateAndReturnPermittedGroups(BasicCredentials credentials) throws io.dropwizard.auth.AuthenticationException {
    final String sanitizedUsername = sanitizeEntity(credentials.getUsername());
    try {
        try (AutoclosingLdapContext context = buildContext(sanitizedUsername, credentials.getPassword())) {
            Set<String> groupMemberships = getGroupMembershipsIntersectingWithRestrictedGroups(context, sanitizedUsername);
            if (!groupMemberships.isEmpty()) {
                return Optional.of(new User(sanitizedUsername, groupMemberships));
            }
        }
    } catch (AuthenticationException ae) {
        LOG.debug("{} failed to authenticate. {}", sanitizedUsername, ae);
    } catch (IOException | NamingException err) {
        throw new io.dropwizard.auth.AuthenticationException(String.format("LDAP Authentication failure (username: %s)",
                sanitizedUsername), err);
    }
    return Optional.empty();
}
项目:tomee    文件:JNDIContext.java   
public void authenticate(final String userID, final String psswrd) throws AuthenticationException {

        final AuthenticationRequest req = new AuthenticationRequest(String.class.cast(env.get("openejb.authentication.realmName")), userID, psswrd);

        final AuthenticationResponse res;
        try {
            res = requestAuthorization(req);
        } catch (RemoteException e) {
            throw new AuthenticationException(e.getLocalizedMessage());
        }

        switch (res.getResponseCode()) {
            case ResponseCodes.AUTH_GRANTED:
                client = res.getIdentity();
                break;
            case ResponseCodes.AUTH_REDIRECT:
                client = res.getIdentity();
                server = res.getServer();
                break;
            case ResponseCodes.AUTH_DENIED:
                throw (AuthenticationException) new AuthenticationException("This principle is not authorized.").initCause(res.getDeniedCause());
        }
    }
项目:tomee    文件:JNDIContext.java   
private void logout() throws AuthenticationException {
    final LogoutRequest request = new LogoutRequest(client.getClientIdentity());

    final LogoutResponse response;
    try {
        response = LogoutResponse.class.cast(Client.request(request, new LogoutResponse(), server));
    } catch (final RemoteException e) {
        throw new AuthenticationException(e.getLocalizedMessage());
    }

    switch (response.getResponseCode()) {
        case ResponseCodes.AUTH_DENIED:
            throw AuthenticationException.class.cast(new AuthenticationException("Can't logout").initCause(response.getDeniedCause()));
        case ResponseCodes.LOGOUT_SUCCESS:
        default:
    }
}
项目:tomee    文件:LocalInitialContext.java   
private void login() throws AuthenticationException {
    final String user = (String) properties.get(Context.SECURITY_PRINCIPAL);
    final String pass = (String) properties.get(Context.SECURITY_CREDENTIALS);
    final String realmName = (String) properties.get("openejb.authentication.realmName");

    if (user != null && pass != null) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Logging in: " + user);
            }
            final SecurityService securityService = SystemInstance.get().getComponent(SecurityService.class);
            if (realmName == null) {
                clientIdentity = securityService.login(user, pass);
            } else {
                clientIdentity = securityService.login(realmName, user, pass);
            }
            ClientSecurity.setIdentity(clientIdentity);
        } catch (final LoginException e) {
            throw (AuthenticationException) new AuthenticationException("User could not be authenticated: " + user).initCause(e);
        }
    }
}
项目:Alpine    文件:LoginResource.java   
/**
 * Processes login requests.
 * @param username the asserted username
 * @param password the asserted password
 * @return a Response
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(
        value = "Assert login credentials",
        notes = "Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be enabled.",
        response = String.class
)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Success"),
        @ApiResponse(code = 401, message = "Unauthorized")
})
@AuthenticationNotRequired
public Response validateCredentials(@FormParam("username") String username, @FormParam("password") String password) {
    final Authenticator auth = new Authenticator(username, password);
    try {
        final Principal principal = auth.authenticate();
        if (principal != null) {
            LOGGER.info(SecurityMarkers.SECURITY_AUDIT, "Login succeeded (username: " + username
                    + " / ip address: " + super.getRemoteAddress()
                    + " / agent: " + super.getUserAgent() + ")");

            final JsonWebToken jwt = new JsonWebToken();
            final String token = jwt.createToken(principal);
            return Response.ok(token).build();
        }
    } catch (AuthenticationException e) {
        LOGGER.warn(SecurityMarkers.SECURITY_AUDIT, "Unauthorized login attempt (username: "
                + username + " / ip address: " + super.getRemoteAddress()
                + " / agent: " + super.getUserAgent() + ")");
    }
    return Response.status(Response.Status.UNAUTHORIZED).build();
}
项目:Alpine    文件:ApiKeyAuthenticationService.java   
/**
 * Authenticates the API key (if it was specified in the X-Api-Key header)
 * and returns a Principal if authentication is successful. Otherwise,
 * returns an AuthenticationException.
 * @return a Principal of which ApiKey is an instance of
 * @throws AuthenticationException upon an authentication failure
 * @since 1.0.0
 */
public Principal authenticate() throws AuthenticationException {
    try (AlpineQueryManager qm = new AlpineQueryManager()) {
        final ApiKey apiKey = qm.getApiKey(assertedApiKey);
        if (apiKey == null) {
            throw new AuthenticationException();
        } else {
            return apiKey;
        }
    }
}
项目:Alpine    文件:LdapAuthenticationService.java   
/**
 * Authenticates the username/password combo against the directory service
 * and returns a Principal if authentication is successful. Otherwise,
 * returns an AuthenticationException.
 *
 * @return a Principal if authentication was successful
 * @throws AuthenticationException when authentication is unsuccessful
 * @since 1.0.0
 */
public Principal authenticate() throws AuthenticationException {
    if (validateCredentials()) {
        try (AlpineQueryManager qm = new AlpineQueryManager()) {
            final LdapUser user = qm.getLdapUser(username);
            if (user != null) {
                return user;
            }
        }
    }
    throw new AuthenticationException();
}
项目:Alpine    文件:Authenticator.java   
/**
 * Attempts to authenticate the credentials internally first and if not  successful,
 * checks to see if LDAP is enabled or not. If enabled, a second attempt to authenticate
 * the credentials will be made, but this time against the directory service.
 * @return a Principal upon successful authentication
 * @throws AuthenticationException upon authentication failure
 * @since 1.0.0
 */
public Principal authenticate() throws AuthenticationException {
    final ManagedUserAuthenticationService userService = new ManagedUserAuthenticationService(username, password);
    try {
        final Principal principal = userService.authenticate();
        if (principal != null) {
            return principal;
        }
    } catch (AuthenticationException e) { }
    if (LDAP_ENABLED) {
        final LdapAuthenticationService ldapService = new LdapAuthenticationService(username, password);
        return ldapService.authenticate();
    }
    throw new AuthenticationException("Username or password is not valid, or the account is suspended.");
}
项目:Alpine    文件:ManagedUserAuthenticationService.java   
/**
 * Authenticates the username/password combo against the directory service
 * and returns a Principal if authentication is successful. Otherwise,
 * returns an AuthenticationException.
 *
 * @return a Principal if authentication was successful
 * @throws AuthenticationException when authentication is unsuccessful
 * @since 1.0.0
 */
public Principal authenticate() throws AuthenticationException {
    try (AlpineQueryManager qm = new AlpineQueryManager()) {
        final ManagedUser user = qm.getManagedUser(username);
        if (user != null && !user.isSuspended()) {
            if (PasswordService.matches(password.toCharArray(), user)) {
                return user;
            }
        }
    }
    throw new AuthenticationException();
}
项目:tomcat7    文件:JNDIRealm.java   
/**
 * Check credentials by binding to the directory as the user
 *
 * @param context The directory context
 * @param user The User to be authenticated
 * @param credentials Authentication credentials
 *
 * @exception NamingException if a directory server error occurs
 */
 protected boolean bindAsUser(DirContext context,
                              User user,
                              String credentials)
     throws NamingException {

     if (credentials == null || user == null)
         return (false);

     String dn = user.getDN();
     if (dn == null)
         return (false);

     // Validate the credentials specified by the user
     if (containerLog.isTraceEnabled()) {
         containerLog.trace("  validating credentials by binding as the user");
    }

    userCredentialsAdd(context, dn, credentials);

    // Elicit an LDAP bind operation
    boolean validated = false;
    try {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  binding as "  + dn);
        }
        context.getAttributes("", null);
        validated = true;
    }
    catch (AuthenticationException e) {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  bind attempt failed");
        }
    }

    userCredentialsRemove(context);

    return validated;
}
项目:Twitch-Streamer    文件:IRC.java   
/**
 * Connect to the IRC server, send authentication, and verify connection.
 *
 * @throws IOException             if the writer/reader fails
 * @throws AuthenticationException if the server failed to authenticate the user
 */
IRC() throws IOException, AuthenticationException {
    LOGGER.info("Connecting to IRC server. Host={}, Port={}", Constants.HOST, Constants.PORT);
    socket = new Socket(Constants.HOST, Constants.PORT);
    reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
    sendAuth();
    checkAuth(reader.readLine());
}
项目:Twitch-Streamer    文件:IRC.java   
/**
 * Sends the username and password to Twitch.
 * TODO: create a random NICK if one is not provided,
 * TODO: allow user to enter username and password in the java client as opposed to a file
 *
 * @throws IOException             if writer fails
 * @throws AuthenticationException if password is invalid
 */
private void sendAuth() throws IOException, AuthenticationException {
    StringBuilder sb = new StringBuilder();
    String password = System.getProperty(Constants.PASSWORD);
    String username = System.getProperty(Constants.USERNAME);
    sb.append(Constants.PASS).append(Constants.SPACE).append(password).append(Constants.DELIMITER)
            .append(Constants.NICK).append(Constants.SPACE).append(username).append(Constants.DELIMITER);
    write(sb.toString());
}
项目:Equella    文件:LDAP.java   
private DirContext _bind(String username, String password, boolean canBeAnonymous, boolean pool)
    throws NamingException
{
    if( !canBeAnonymous && password.length() == 0 )
    {
        throw new BadCredentialsException("Couldn't authenticate with LDAP");
    }

    // We'll ignore Sonar's advice to replace Hashtable with java.util.Map
    Hashtable<String, String> map = new Hashtable<String, String>(env); // NOSONAR
    map.put("com.sun.jndi.ldap.connect.pool", Boolean.toString(pool));
    map.put(Context.SECURITY_PRINCIPAL, username);
    map.put(Context.SECURITY_CREDENTIALS, password);
    map.put(Context.SECURITY_AUTHENTICATION, "simple");

    ClassLoader oldLoader = null;
    try
    {
        if( blind )
        {
            oldLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(LDAP.class.getClassLoader());
        }
        return new InitialDirContext(map);
    }
    catch( AuthenticationException e )
    {
        throw new BadCredentialsException("Couldn't authenticate with LDAP");
    }
    finally
    {
        if( oldLoader != null )
        {
            Thread.currentThread().setContextClassLoader(oldLoader);
        }
    }
}
项目:ranch2git    文件:RancherInstance.java   
/** fetch stacks from server **/
public ArrayList<RancherStack> fetchRancherStacks() throws UnirestException, AuthenticationException {
    HttpResponse<JsonNode> jsonResponse = null;

    if(apiPw != null && apiUser != null)
        jsonResponse = Unirest.get(apiURL).header("accept", "application/json").basicAuth(apiUser,apiPw).asJson();

    if(apiUser == null && apiPw == null)
        jsonResponse = Unirest.get(apiURL).header("accept", "application/json").asJson();

    if (jsonResponse != null) {
        if(jsonResponse.getStatus() == 401)
            throw new AuthenticationException("Rancher Server returned 401 (Unauthorized).");

        JSONArray jsonStacks = jsonResponse.getBody().getObject().getJSONArray("data");

        for(int i = 0; i<jsonStacks.length();i++){
            JSONObject rStack = (JSONObject) jsonStacks.get(i);
            RancherStack newStack = new RancherStack();
            newStack.setId(rStack.getString("id"));
            newStack.setName(rStack.getString("name"));
            this.stacks.add(newStack);
        }
    }else{
        System.err.println("Could not fetch stacks from server.");
        return null;
    }
    return this.stacks;
}
项目:apache-tomcat-7.0.73-with-comment    文件:JNDIRealm.java   
/**
 * Check credentials by binding to the directory as the user
 *
 * @param context The directory context
 * @param user The User to be authenticated
 * @param credentials Authentication credentials
 *
 * @exception NamingException if a directory server error occurs
 */
 protected boolean bindAsUser(DirContext context,
                              User user,
                              String credentials)
     throws NamingException {

     if (credentials == null || user == null)
         return (false);

     String dn = user.getDN();
     if (dn == null)
         return (false);

     // Validate the credentials specified by the user
     if (containerLog.isTraceEnabled()) {
         containerLog.trace("  validating credentials by binding as the user");
    }

    userCredentialsAdd(context, dn, credentials);

    // Elicit an LDAP bind operation
    boolean validated = false;
    try {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  binding as "  + dn);
        }
        context.getAttributes("", null);
        validated = true;
    }
    catch (AuthenticationException e) {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  bind attempt failed");
        }
    }

    userCredentialsRemove(context);

    return validated;
}
项目:uavstack    文件:GUISSOLdapClient.java   
private boolean ldapApiCheck(String loginId, String password) {

        boolean result = false;
        String action = "login";
        try {
            initLdapContext(action);
            LdapContext ldapCtx = ldapContexts.get(action);

            ldapCtx.addToEnvironment(Context.SECURITY_PRINCIPAL, loginId);
            ldapCtx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            // 密码验证,不报错则为验证成功
            ldapCtx.reconnect(null);
            result = true;
            loggerInfo("LDAP信息", "校验", "成功", loginId);
        }
        catch (AuthenticationException e) {
            // 此异常为用户验证失败,因此不做ldapContext清除
            loggerError("LDAP信息校验", loginId + " (业务意义为验证失败,异常信息可以忽略)", e);
        }
        catch (Exception e1) {
            loggerError("LDAP信息校验", loginId, e1);
            clearLdapContext(action);
        }

        return result;

    }
项目:lazycat    文件:JNDIRealm.java   
/**
 * Check credentials by binding to the directory as the user
 *
 * @param context
 *            The directory context
 * @param user
 *            The User to be authenticated
 * @param credentials
 *            Authentication credentials
 *
 * @exception NamingException
 *                if a directory server error occurs
 */
protected boolean bindAsUser(DirContext context, User user, String credentials) throws NamingException {

    if (credentials == null || user == null)
        return (false);

    String dn = user.getDN();
    if (dn == null)
        return (false);

    // Validate the credentials specified by the user
    if (containerLog.isTraceEnabled()) {
        containerLog.trace("  validating credentials by binding as the user");
    }

    userCredentialsAdd(context, dn, credentials);

    // Elicit an LDAP bind operation
    boolean validated = false;
    try {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  binding as " + dn);
        }
        context.getAttributes("", null);
        validated = true;
    } catch (AuthenticationException e) {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  bind attempt failed");
        }
    }

    userCredentialsRemove(context);

    return validated;
}
项目:parking-api    文件:ActiveDirectoryAliasLdapAuthenticationProvider.java   
private DirContext bindAsUser(String username, String password) {
    // TODO. add DNS lookup based on domain
    final String bindUrl = url;

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    String bindPrincipal = createBindPrincipal(username);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipal);
    env.put(Context.PROVIDER_URL, bindUrl);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());

    try {
        return contextFactory.createContext(env);
    }
    catch (NamingException e) {
        if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
            handleBindException(bindPrincipal, e);
            throw badCredentials(e);
        }
        else {
            throw LdapUtils.convertLdapException(e);
        }
    }
}
项目:incubator-pulsar    文件:ServerConnection.java   
/**
 * handles connect request and sends {@code State.Connected} ack to client
 */
@Override
protected void handleConnect(CommandConnect connect) {
    checkArgument(state == State.Start);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Received CONNECT from {}", remoteAddress);
    }
    if(service.getConfiguration().isAuthenticationEnabled()) {
        try {
            String authMethod = "none";
            if (connect.hasAuthMethodName()) {
                authMethod = connect.getAuthMethodName();
            } else if (connect.hasAuthMethod()) {
                // Legacy client is passing enum
                authMethod = connect.getAuthMethod().name().substring(10).toLowerCase();
            }
            String authData = connect.getAuthData().toStringUtf8();
            ChannelHandler sslHandler = ctx.channel().pipeline().get(TLS_HANDLER);
            SSLSession sslSession = null;
            if (sslHandler != null) {
                sslSession = ((SslHandler) sslHandler).engine().getSession();
            }
            authRole = service.getAuthenticationService()
                    .authenticate(new AuthenticationDataCommand(authData, remoteAddress, sslSession), authMethod);
            LOG.info("[{}] Client successfully authenticated with {} role {}", remoteAddress, authMethod, authRole);
        } catch (AuthenticationException e) {
            String msg = "Unable to authenticate";
            LOG.warn("[{}] {}: {}", remoteAddress, msg, e.getMessage());
            ctx.writeAndFlush(Commands.newError(-1, ServerError.AuthenticationError, msg));
            close();
            return;
        }
    }
    ctx.writeAndFlush(Commands.newConnected(connect.getProtocolVersion()));
    state = State.Connected;
    remoteEndpointProtocolVersion = connect.getProtocolVersion();
}
项目:incubator-pulsar    文件:AuthenticationService.java   
public String authenticate(AuthenticationDataSource authData, String authMethodName)
        throws AuthenticationException {
    AuthenticationProvider provider = providers.get(authMethodName);
    if (provider != null) {
        return provider.authenticate(authData);
    } else {
        if (StringUtils.isNotBlank(anonymousUserRole)) {
            return anonymousUserRole;
        }
        throw new AuthenticationException("Unsupported authentication mode: " + authMethodName);
    }
}
项目:incubator-pulsar    文件:ProxyConnection.java   
private boolean verifyAuthenticationIfNeeded(CommandConnect connect) {
    if (!service.getConfiguration().isAuthenticationEnabled()) {
        return true;
    }

    try {
        String authMethod = "none";
        if (connect.hasAuthMethodName()) {
            authMethod = connect.getAuthMethodName();
        } else if (connect.hasAuthMethod()) {
            // Legacy client is passing enum
            authMethod = connect.getAuthMethod().name().substring(10).toLowerCase();
        }
        String authData = connect.getAuthData().toStringUtf8();
        ChannelHandler sslHandler = ctx.channel().pipeline().get("tls");
        SSLSession sslSession = null;
        if (sslHandler != null) {
            sslSession = ((SslHandler) sslHandler).engine().getSession();
        }
        clientAuthRole = service.getAuthenticationService()
                .authenticate(new AuthenticationDataCommand(authData, remoteAddress, sslSession), authMethod);
        LOG.info("[{}] Client successfully authenticated with {} role {}", remoteAddress, authMethod,
                clientAuthRole);
        return true;
    } catch (AuthenticationException e) {
        LOG.warn("[{}] Unable to authenticate: {}", remoteAddress, e.getMessage());
        return false;
    }
}
项目:dr-elephant    文件:ExceptionFinder.java   
/**
 * Constructor for ExceptionFinder class
 * @param url The url of the workflow to analyze
 * @param scheduler The scheduler where the workflow was run.
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public ExceptionFinder(String url, String scheduler)
    throws URISyntaxException, MalformedURLException, AuthenticationException, IOException {

  // create a new MRClient
  _mrClient = new MRClient();

  // create a new workflow client
  _workflowClient = InfoExtractor.getWorkflowClientInstance(scheduler, url);

  // get the schedulerData
  SchedulerConfigurationData schedulerData = InfoExtractor.getSchedulerData(scheduler);


  if(schedulerData==null) {
    throw new RuntimeException(String.format("Cannot find scheduler %s", scheduler));
  }

  if(!schedulerData.getParamMap().containsKey(USERNAME)) {
    throw new RuntimeException(String.format("Cannot find username for login"));
  }

  String username = schedulerData.getParamMap().get(USERNAME);

  if(schedulerData.getParamMap().containsKey(PRIVATE_KEY)) {
    _workflowClient.login(username, new File(schedulerData.getParamMap().get(PRIVATE_KEY)));
  } else if (schedulerData.getParamMap().containsKey(PASSWORD)) {
    _workflowClient.login(username, schedulerData.getParamMap().get(PASSWORD));
  } else {
    throw new RuntimeException("Neither private key nor password was specified");
  }
  _exception = analyzeFlow(url);
}
项目:dr-elephant    文件:ExceptionFinder.java   
/**
  * Analyzes a Flow and returns a HadoopException object which captures all the exception in the flow.
  * @param execUrl the execution URL of the flow
  * @return HadoopException object which captures all the exceptions in the given Flow
  */
 private HadoopException analyzeFlow(final String execUrl) throws AuthenticationException, IOException {
   HadoopSecurity _hadoopSecurity = HadoopSecurity.getInstance();

   return _hadoopSecurity.doAs(new PrivilegedAction<HadoopException>() {
     @Override
     public HadoopException run() {
       HadoopException flowLevelException = new HadoopException();
       List<HadoopException> childExceptions = new ArrayList<HadoopException>();
       Map<String, String> jobIdStatus = _workflowClient.getJobsFromFlow();

       // Find exceptions in all the unsuccessful jobs of the workflow
       for (String unsuccessfulJobId : jobIdStatus.keySet()) {
         if (jobIdStatus.get(unsuccessfulJobId).toLowerCase().equals("failed")) {
           HadoopException jobLevelException = analyzeJob(unsuccessfulJobId);
           childExceptions.add(jobLevelException);
         }
       }

       flowLevelException.setType(HadoopException.HadoopExceptionType.FLOW);
       flowLevelException.setId(execUrl);
       flowLevelException.setLoggingEvent(null); // No flow level exception
       flowLevelException.setChildExceptions(childExceptions);
       return flowLevelException;
     }
   });
}
项目:ksql    文件:KsqlRestClient.java   
public RestResponse<ServerInfo> makeRootRequest() {
  Response response = makeGetRequest("/");
  try {
    if (response.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) {
      return RestResponse.erroneous(new ErrorMessage(
              new AuthenticationException("Could not authenticate successfully with the supplied credentials.")));
    }
    ServerInfo result = response.readEntity(ServerInfo.class);
    return RestResponse.successful(result);
  } finally {
    response.close();
  }
}
项目:zeppelin    文件:LdapRealm.java   
@Override

  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws org.apache.shiro.authc.AuthenticationException {
    try {
      return super.doGetAuthenticationInfo(token);
    } catch (org.apache.shiro.authc.AuthenticationException ae) {
      throw ae;
    }
  }
项目:activemq-artemis    文件:LDAPLoginModule.java   
protected boolean bindUser(DirContext context, String dn, String password) throws NamingException {
   boolean isValid = false;

   if (logger.isDebugEnabled()) {
      logger.debug("Binding the user.");
   }
   context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
   context.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
   try {
      context.getAttributes("", null);
      isValid = true;
      if (logger.isDebugEnabled()) {
         logger.debug("User " + dn + " successfully bound.");
      }
   } catch (AuthenticationException e) {
      isValid = false;
      if (logger.isDebugEnabled()) {
         logger.debug("Authentication failed for dn=" + dn);
      }
   }

   if (isLoginPropertySet(CONNECTION_USERNAME)) {
      context.addToEnvironment(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
   } else {
      context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
   }
   if (isLoginPropertySet(CONNECTION_PASSWORD)) {
      context.addToEnvironment(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
   } else {
      context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
   }

   return isValid;
}
项目:picketbox    文件:LdapCallbackHandlerUnitTestCase.java   
@Test
public void testFailCBH() throws Exception
{
    LdapCallbackHandler cbh = new LdapCallbackHandler();

    Map<String,String> map = new HashMap<String,String>();
    map.put("bindDN", "cn=Directory Manager");
    map.put("bindCredential", "password");
    map.put("baseFilter", "(uid={0})");
    map.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
    map.put("java.naming.provider.url", "ldap://localhost:10389");
    map.put("baseCtxDN", "ou=People,dc=jboss,dc=org");

       cbh.setConfiguration(map);

    NameCallback ncb = new NameCallback("Enter");
    ncb.setName("jduke");

    VerifyPasswordCallback vpc = new VerifyPasswordCallback();
    vpc.setValue("badDUDE");

    try
    {
        cbh.handle(new Callback[] {ncb,vpc} );
        fail("should have thrown ex");
    }
    catch(IOException ae)
    {
        Throwable cause = ae.getCause();
        assertNotNull(cause);
        assertTrue(cause instanceof AuthenticationException);
    }

    assertFalse(vpc.isVerified());
}
项目:class-guard    文件:JNDIRealm.java   
/**
 * Check credentials by binding to the directory as the user
 *
 * @param context The directory context
 * @param user The User to be authenticated
 * @param credentials Authentication credentials
 *
 * @exception NamingException if a directory server error occurs
 */
 protected boolean bindAsUser(DirContext context,
                              User user,
                              String credentials)
     throws NamingException {

     if (credentials == null || user == null)
         return (false);

     String dn = user.getDN();
     if (dn == null)
         return (false);

     // Validate the credentials specified by the user
     if (containerLog.isTraceEnabled()) {
         containerLog.trace("  validating credentials by binding as the user");
    }

    userCredentialsAdd(context, dn, credentials);

    // Elicit an LDAP bind operation
    boolean validated = false;
    try {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  binding as "  + dn);
        }
        context.getAttributes("", null);
        validated = true;
    }
    catch (AuthenticationException e) {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  bind attempt failed");
        }
    }

    userCredentialsRemove(context);

    return (validated);
}
项目:apache-tomcat-7.0.57    文件:JNDIRealm.java   
/**
 * Check credentials by binding to the directory as the user
 *
 * @param context The directory context
 * @param user The User to be authenticated
 * @param credentials Authentication credentials
 *
 * @exception NamingException if a directory server error occurs
 */
 protected boolean bindAsUser(DirContext context,
                              User user,
                              String credentials)
     throws NamingException {

     if (credentials == null || user == null)
         return (false);

     String dn = user.getDN();
     if (dn == null)
         return (false);

     // Validate the credentials specified by the user
     if (containerLog.isTraceEnabled()) {
         containerLog.trace("  validating credentials by binding as the user");
    }

    userCredentialsAdd(context, dn, credentials);

    // Elicit an LDAP bind operation
    boolean validated = false;
    try {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  binding as "  + dn);
        }
        context.getAttributes("", null);
        validated = true;
    }
    catch (AuthenticationException e) {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  bind attempt failed");
        }
    }

    userCredentialsRemove(context);

    return (validated);
}