javax.security.sasl.AuthenticationException Java Examples
The following examples show how to use
javax.security.sasl.AuthenticationException.
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: Wso2EventClient.java From product-cep with Apache License 2.0 | 6 votes |
public static void publish(String protocol, String host, String port, String username, String password, String streamId,String dataFileName, String testCaseFolderName, StreamDefinition streamDefinition, int events, int delay) throws MalformedStreamDefinitionException, StreamDefinitionException, DifferentStreamDefinitionAlreadyDefinedException, MalformedURLException, NoStreamDefinitionExistException, AuthenticationException, TransportException, SocketException, DataEndpointAgentConfigurationException, DataEndpointException, DataEndpointAuthenticationException, DataEndpointConfigurationException { String relativeFilePath = getTestDataFileLocation(testCaseFolderName, dataFileName); KeyStoreUtil.setTrustStoreParams(); //create data publisher DataPublisher dataPublisher = new DataPublisher(protocol, "tcp://" + host + ":" + port, null, username, password); //Publish event for a valid stream publishEvents(dataPublisher, streamDefinition, relativeFilePath, events, delay); dataPublisher.shutdown(); }
Example #2
Source File: ProtonClientSaslTest.java From vertx-proton with Apache License 2.0 | 6 votes |
@Test(timeout = 20000) public void testRestrictSaslMechanisms(TestContext context) throws Exception { ProtonClientOptions options = new ProtonClientOptions(); // Try with the wrong password, with anonymous access disabled, expect connect to fail doConnectWithGivenCredentialsTestImpl(context, options, USERNAME_GUEST, "wrongpassword", AuthenticationException.class); // Try with the wrong password, with anonymous access enabled, expect connect still to fail anonymousAccessAllowed = true; restartBroker(); doConnectWithGivenCredentialsTestImpl(context, options, USERNAME_GUEST, "wrongpassword", AuthenticationException.class); // Now restrict the allows SASL mechanisms to ANONYMOUS, then expect connect to succeed as it wont use the invalid // credentials options.addEnabledSaslMechanism(ProtonSaslAnonymousImpl.MECH_NAME); doConnectWithGivenCredentialsTestImpl(context, options, USERNAME_GUEST, "wrongpassword", null); }
Example #3
Source File: JWTLoginFilter.java From opscenter with Apache License 2.0 | 6 votes |
@Override public Authentication attemptAuthentication( HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException { // JSON反序列化成 AccountCredentials AccountCredentials creds = new AccountCredentials(); creds.setUsername(String.valueOf(req.getParameter("username"))); creds.setPassword(String.valueOf(req.getParameter("password"))); // 返回一个验证令牌 return getAuthenticationManager().authenticate( new UsernamePasswordAuthenticationToken( creds.getUsername(), creds.getPassword() ) ); }
Example #4
Source File: JwtHelper.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
/** * Performs verifications on a JWT token, then parses it into a {@link AuthenticationException} instance * * @param jwt the base64-encoded JWT token from the request * @return the {@link Authentication} derived from the information in the token * @throws AuthenticationException */ public Authentication verifyAndParseJwtAccessToken(String jwt) throws AuthenticationException { JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30) .setRequireSubject().setExpectedIssuer(ISSUER_NAME).setExpectedAudience(AUDIENCE) .setVerificationKey(jwtWebKey.getKey()) .setJwsAlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256).build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String username = jwtClaims.getSubject(); List<String> roles = jwtClaims.getStringListClaimValue("role"); Authentication auth = new Authentication(username, roles.toArray(new String[roles.size()])); return auth; } catch (Exception e) { logger.error("Error while processing JWT token", e); throw new AuthenticationException(e.getMessage()); } }
Example #5
Source File: ProtonSaslClientAuthenticatorImpl.java From vertx-proton with Apache License 2.0 | 5 votes |
private void handleSaslFail() throws SaslException { switch(sasl.getOutcome()) { case PN_SASL_AUTH: throw new AuthenticationException("Failed to authenticate"); case PN_SASL_SYS: case PN_SASL_TEMP: throw new SaslSystemException(false, "SASL handshake failed due to a transient error"); case PN_SASL_PERM: throw new SaslSystemException(true, "SASL handshake failed due to an unrecoverable error"); default: throw new SaslException("SASL handshake failed"); } }
Example #6
Source File: LdapAuthenticationProviderImpl.java From incubator-retired-blur with Apache License 2.0 | 5 votes |
@Override public void authenticate(String username, String password, InetSocketAddress address) throws AuthenticationException { Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, _ldapURL); // If the domain is supplied, then append it. LDAP providers // like Active Directory use a fully qualified user name like [email protected]. if (_ldapDomain != null) { username = username + "@" + _ldapDomain; } // setup the security principal final String bindDN; if (_baseDN != null) { bindDN = "uid=" + username + "," + _baseDN; } else { bindDN = username; } env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDN); env.put(Context.SECURITY_CREDENTIALS, password); try { // Create initial context DirContext ctx = new InitialDirContext(env); ctx.close(); } catch (NamingException e) { throw new AuthenticationException("Error validating LDAP user", e); } return; }
Example #7
Source File: StockQuoteClient.java From product-cep with Apache License 2.0 | 5 votes |
public static void publish(String host, String port, String username, String password, int events) throws MalformedStreamDefinitionException, StreamDefinitionException, DifferentStreamDefinitionAlreadyDefinedException, MalformedURLException, AuthenticationException, NoStreamDefinitionExistException, org.wso2.carbon.databridge.commons.exception.AuthenticationException, TransportException, SocketException, DataEndpointAgentConfigurationException, DataEndpointException, DataEndpointAuthenticationException, DataEndpointConfigurationException { System.out.println("Starting Stock quote Agent"); KeyStoreUtil.setTrustStoreParams(); //create data publisher DataPublisher dataPublisher = new DataPublisher("tcp://" + host + ":" + port, username, password); String streamId = DataBridgeCommonsUtils.generateStreamId(STREAM_NAME1, VERSION1); //Publish event for a valid stream if (!streamId.isEmpty()) { System.out.println("Stream ID: " + streamId); while (sentEventCount < events) { dataPublisher.publish(streamId, null, null, getPayload()); sentEventCount++; System.out.println("Events published : " + sentEventCount); } try { Thread.sleep(3000); } catch (InterruptedException e) { //ignore } dataPublisher.shutdown(); } }
Example #8
Source File: ProtonClientSaslTest.java From vertx-proton with Apache License 2.0 | 5 votes |
@Test(timeout = 20000) public void testConnectAnonymousWithoutUserPass(TestContext context) throws Exception { doConnectWithGivenCredentialsTestImpl(context, null, null, AuthenticationException.class); anonymousAccessAllowed = true; restartBroker(); doConnectWithGivenCredentialsTestImpl(context, null, null, null); }
Example #9
Source File: ClientUtils.java From enmasse with Apache License 2.0 | 5 votes |
private boolean canConnectWithAmqpAddress(ResourceManager resourceManager, AddressSpace addressSpace, UserCredentials credentials, AddressType addressType, String address, boolean defaultValue) throws Exception { Set<AddressType> brokeredAddressTypes = new HashSet<>(Arrays.asList(AddressType.QUEUE, AddressType.TOPIC)); if (AddressSpaceUtils.isBrokered(addressSpace) && !brokeredAddressTypes.contains(addressType)) { return defaultValue; } try (AmqpClient client = resourceManager.getAmqpClientFactory().createAddressClient(addressSpace, addressType)) { client.getConnectOptions().setCredentials(credentials); ProtonClientOptions protonClientOptions = client.getConnectOptions().getProtonClientOptions(); protonClientOptions.setLogActivity(true); client.getConnectOptions().setProtonClientOptions(protonClientOptions); try { Future<List<Message>> received = client.recvMessages(address, 1); Future<Integer> sent = client.sendMessages(address, Collections.singletonList("msg1")); int numReceived = received.get(1, TimeUnit.MINUTES).size(); int numSent = sent.get(1, TimeUnit.MINUTES); return (numSent == numReceived); } catch (ExecutionException | SecurityException | UnauthorizedAccessException ex) { Throwable cause = ex; if (ex instanceof ExecutionException) { cause = ex.getCause(); } if (cause instanceof AuthenticationException || cause instanceof SaslSystemException || cause instanceof SecurityException || cause instanceof UnauthorizedAccessException || cause instanceof MechanismMismatchException) { LOGGER.info("canConnectWithAmqpAddress {} ({}): {}", address, addressType, ex.getMessage()); return false; } else { LOGGER.warn("canConnectWithAmqpAddress {} ({}) exception", address, addressType, ex); throw ex; } } } }
Example #10
Source File: AuthenticationServerClient.java From hono with Eclipse Public License 2.0 | 5 votes |
private ServiceInvocationException mapConnectionFailureToServiceInvocationException(final Throwable connectionFailureCause) { final ServiceInvocationException exception; if (connectionFailureCause == null) { exception = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "failed to connect to Authentication service"); } else if (connectionFailureCause instanceof AuthenticationException) { exception = new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "failed to authenticate with Authentication service"); } else if (connectionFailureCause instanceof MechanismMismatchException) { exception = new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "Authentication service does not support SASL mechanism"); } else { exception = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "failed to connect to Authentication service", connectionFailureCause); } return exception; }
Example #11
Source File: HonoConnectionImpl.java From hono with Eclipse Public License 2.0 | 5 votes |
private void failConnectionAttempt(final Throwable connectionFailureCause, final Handler<AsyncResult<HonoConnection>> connectionHandler) { log.info("stopping connection attempt to server [{}:{}, role: {}] due to terminal error", connectionFactory.getHost(), connectionFactory.getPort(), connectionFactory.getServerRole(), connectionFailureCause); final ServiceInvocationException serviceInvocationException; if (connectionFailureCause == null) { serviceInvocationException = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "failed to connect"); } else if (connectionFailureCause instanceof AuthenticationException) { // wrong credentials? serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "failed to authenticate with server"); } else if (connectionFailureCause instanceof MechanismMismatchException) { serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "no suitable SASL mechanism found for authentication with server"); } else if (connectionFailureCause instanceof SSLException) { serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "TLS handshake with server failed: " + connectionFailureCause.getMessage(), connectionFailureCause); } else { serviceInvocationException = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "failed to connect", connectionFailureCause); } connectionHandler.handle(Future.failedFuture(serviceInvocationException)); }
Example #12
Source File: HonoConnectionImpl.java From hono with Eclipse Public License 2.0 | 5 votes |
private boolean isNoteworthyError(final Throwable connectionFailureCause) { return connectionFailureCause instanceof SSLException || connectionFailureCause instanceof AuthenticationException || connectionFailureCause instanceof MechanismMismatchException || (connectionFailureCause instanceof SaslSystemException && ((SaslSystemException) connectionFailureCause).isPermanent()); }
Example #13
Source File: PermissionInterceptor.java From jim-framework with Apache License 2.0 | 5 votes |
@Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { if(StringUtils.isEmpty(httpServletRequest.getHeader("token"))){ throw new AuthenticationException("未授权用户不允许操作"); } return true; }
Example #14
Source File: StringUtilities.java From neoscada with Eclipse Public License 1.0 | 5 votes |
/** * A directive is a parameter of the digest authentication process. * Returns the value of a directive from the map. If mandatory is true and the * value is null, then it throws an {@link AuthenticationException}. * * @param directivesMap the directive's map * @param directive the name of the directive we want to retrieve * @param mandatory is the directive mandatory * @return the mandatory value as a String * @throws AuthenticationException if mandatory is true and if * directivesMap.get(directive) == null */ public static String getDirectiveValue(HashMap<String, String> directivesMap, String directive, boolean mandatory) throws AuthenticationException { String value = directivesMap.get(directive); if (value == null) { if (mandatory) { throw new AuthenticationException("\"" + directive + "\" mandatory directive is missing"); } return ""; } return value; }
Example #15
Source File: customAuthenticator.java From Apache-Hive-Essentials-Second-Edition with MIT License | 5 votes |
@Override public void Authenticate(String user, String password) throws AuthenticationException { String storedPasswd = authHashTable.get(user); if (storedPasswd != null && storedPasswd.equals(password)) return; throw new AuthenticationException("customAuthenticator Exception: Invalid user"); }
Example #16
Source File: ProtonClientSaslTest.java From vertx-proton with Apache License 2.0 | 4 votes |
@Test(timeout = 20000) public void testConnectWithInvalidUserPassFails(TestContext context) throws Exception { doConnectWithGivenCredentialsTestImpl(context, USERNAME_GUEST, "wrongpassword", AuthenticationException.class); }
Example #17
Source File: DigestUtilities.java From neoscada with Eclipse Public License 1.0 | 4 votes |
/** * Computes the response to the DIGEST challenge. * * @param session the current session * @param map the map holding the directives sent by the proxy * @param method the HTTP verb * @param pwd the password * @param charsetName the name of the charset used for the challenge * @param body the html body to be hashed for integrity calculations */ public static String computeResponseValue(IoSession session, HashMap<String, String> map, String method, String pwd, String charsetName, String body) throws AuthenticationException, UnsupportedEncodingException { byte[] hA1; StringBuilder sb; boolean isMD5Sess = "md5-sess".equalsIgnoreCase(StringUtilities.getDirectiveValue(map, "algorithm", false)); if (!isMD5Sess || (session.getAttribute(SESSION_HA1) == null)) { // Build A1 sb = new StringBuilder(); sb.append(StringUtilities.stringTo8859_1(StringUtilities.getDirectiveValue(map, "username", true))).append( ':'); String realm = StringUtilities.stringTo8859_1(StringUtilities.getDirectiveValue(map, "realm", false)); if (realm != null) { sb.append(realm); } sb.append(':').append(pwd); if (isMD5Sess) { byte[] prehA1; synchronized (md5) { md5.reset(); prehA1 = md5.digest(sb.toString().getBytes(charsetName)); } sb = new StringBuilder(); sb.append(ByteUtilities.asHex(prehA1)); sb.append(':').append( StringUtilities.stringTo8859_1(StringUtilities.getDirectiveValue(map, "nonce", true))); sb.append(':').append( StringUtilities.stringTo8859_1(StringUtilities.getDirectiveValue(map, "cnonce", true))); synchronized (md5) { md5.reset(); hA1 = md5.digest(sb.toString().getBytes(charsetName)); } session.setAttribute(SESSION_HA1, hA1); } else { synchronized (md5) { md5.reset(); hA1 = md5.digest(sb.toString().getBytes(charsetName)); } } } else { hA1 = (byte[]) session.getAttribute(SESSION_HA1); } sb = new StringBuilder(method); sb.append(':'); sb.append(StringUtilities.getDirectiveValue(map, "uri", false)); String qop = StringUtilities.getDirectiveValue(map, "qop", false); if ("auth-int".equalsIgnoreCase(qop)) { ProxyIoSession proxyIoSession = (ProxyIoSession) session.getAttribute(ProxyIoSession.PROXY_SESSION); byte[] hEntity; synchronized (md5) { md5.reset(); hEntity = md5.digest(body.getBytes(proxyIoSession.getCharsetName())); } sb.append(':').append(hEntity); } byte[] hA2; synchronized (md5) { md5.reset(); hA2 = md5.digest(sb.toString().getBytes(charsetName)); } sb = new StringBuilder(); sb.append(ByteUtilities.asHex(hA1)); sb.append(':').append(StringUtilities.getDirectiveValue(map, "nonce", true)); sb.append(":00000001:"); sb.append(StringUtilities.getDirectiveValue(map, "cnonce", true)); sb.append(':').append(qop).append(':'); sb.append(ByteUtilities.asHex(hA2)); byte[] hFinal; synchronized (md5) { md5.reset(); hFinal = md5.digest(sb.toString().getBytes(charsetName)); } return ByteUtilities.asHex(hFinal); }
Example #18
Source File: AnalyticStatClient.java From product-cep with Apache License 2.0 | 4 votes |
public static void publish(String host, String port, String username, String password, int events) throws MalformedStreamDefinitionException, StreamDefinitionException, DifferentStreamDefinitionAlreadyDefinedException, MalformedURLException, AuthenticationException, NoStreamDefinitionExistException, org.wso2.carbon.databridge.commons.exception.AuthenticationException, TransportException, SocketException, DataEndpointAgentConfigurationException, DataEndpointException, DataEndpointAuthenticationException, DataEndpointConfigurationException { System.out.println("Starting Statistics Agent"); KeyStoreUtil.setTrustStoreParams(); //create data publisher DataPublisher dataPublisher = new DataPublisher("tcp://" + host + ":" + port, username, password); // StreamDefinition streamDefinition = new StreamDefinition(STREAM_NAME1, VERSION1); // streamDefinition.addMetaData("ipAdd", AttributeType.STRING); // streamDefinition.addMetaData("index", AttributeType.LONG); // streamDefinition.addMetaData("timestamp", AttributeType.LONG); // streamDefinition.addMetaData("nanoTime", AttributeType.LONG); // streamDefinition.addPayloadData("userID", AttributeType.STRING); // streamDefinition.addPayloadData("searchTerms", AttributeType.STRING); // String streamId = dataPublisher.defineStream(streamDefinition); String streamId = DataBridgeCommonsUtils.generateStreamId(STREAM_NAME1, VERSION1); //Publish event for a valid stream if (!streamId.isEmpty()) { System.out.println("Stream ID: " + streamId); while (sentEventCount < events) { dataPublisher.publish(streamId, getMeta(), null, getPayload()); sentEventCount++; System.out.println("Events published : " + sentEventCount); } try { Thread.sleep(3000); } catch (InterruptedException e) { //ignore } dataPublisher.shutdown(); } }
Example #19
Source File: CustomAuthenticationProviderImpl.java From incubator-retired-blur with Apache License 2.0 | 4 votes |
@Override public void authenticate(String username, String password, InetSocketAddress address) throws AuthenticationException { _provider.authenticate(username, password, address); }
Example #20
Source File: PasswordAuthenticationProvider.java From incubator-retired-blur with Apache License 2.0 | 4 votes |
public abstract void authenticate(String username, String password, InetSocketAddress address) throws AuthenticationException;
Example #21
Source File: JWTLoginFilter.java From opscenter with Apache License 2.0 | 4 votes |
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().println(JSONResult.fillResultString(500, "Internal Server Error!!!", "")); }
Example #22
Source File: AnonymousAuthenticationProviderImpl.java From incubator-retired-blur with Apache License 2.0 | 2 votes |
@Override public void authenticate(String username, String password, InetSocketAddress address) throws AuthenticationException { }