public void testIsAuthenticationDialogSuppressed() throws Exception { final boolean[] suppressed = new boolean[1]; Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { suppressed[0] = NetworkSettings.isAuthenticationDialogSuppressed(); return super.getPasswordAuthentication(); } }); Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http"); return null; } }; NetworkSettings.suppressAuthenticationDialog(callable); assertTrue(suppressed[0]); }
private RemoteRepository(PasswordAuthentication pa, String forPath, boolean fixedUrl) { assert !fixedUrl || forPath != null && !forPath.trim().isEmpty(); this.panel = new RemoteRepositoryPanel(); this.urlFixed = fixedUrl; settingTypes = new ConnectionSettingsType[] { new GitConnectionSettingsType(), new SSHConnectionSettingsType(), new FileConnectionSettingsType(), new DefaultConnectionSettingsType() }; this.activeSettingsType = settingTypes[0]; initHeight(); attachListeners(); initUrlComboValues(forPath, pa); updateCurrentSettingsType(); validateFields(); }
private void getAnswer() { if (!answered) { answered = true; PasswordAuthentication passAuth = Authenticator.requestPasswordAuthentication( hci.host, hci.addr, hci.port, hci.protocol, hci.prompt, hci.scheme, hci.url, hci.authType); /** * To be compatible with existing callback handler implementations, * when the underlying Authenticator is canceled, username and * password are assigned null. No exception is thrown. */ if (passAuth != null) { username = passAuth.getUserName(); password = passAuth.getPassword(); } } }
private void init (PasswordAuthentication pw) { this.pw = pw; if (pw != null) { String s = pw.getUserName(); int i = s.indexOf ('\\'); if (i == -1) { username = s; ntdomain = defaultDomain; } else { ntdomain = s.substring (0, i).toUpperCase(); username = s.substring (i+1); } password = new String (pw.getPassword()); } else { /* credentials will be acquired from OS */ username = null; ntdomain = null; password = null; } init0(); }
public PasswordAuthentication getPasswordAuthentication(String url, boolean forceRelogin) { if(kenaiAccessor != null) { if(forceRelogin && queriedUrls.contains(url)) { // we already queried the authentication for this url, but it didn't // seem to be accepted -> force a new login, the current user // might not be authorized for the given kenai project (url). if(!kenaiAccessor.showLogin()) { return null; } } queriedUrls.add(url); return kenaiAccessor.getPasswordAuthentication(url); } else { return null; } }
@Test public void testUserPassword() throws Exception { startServer(buildUserPasswordConfig()); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("oryx", "pass".toCharArray()); } }); try { String response = Resources.toString( new URL("http://localhost:" + getHTTPPort() + "/helloWorld"), StandardCharsets.UTF_8); assertEquals("Hello, World", response); } finally { Authenticator.setDefault(null); } }
public static void main(String[] args) throws Exception { final String user = "probe"; final String password = "probe"; Proxy proxyTest = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 10779)); java.net.Authenticator.setDefault(new java.net.Authenticator() { private PasswordAuthentication authentication = new PasswordAuthentication(user, password.toCharArray()); @Override protected PasswordAuthentication getPasswordAuthentication() { return authentication; } }); OkHttpClient client = new OkHttpClient.Builder().proxy(proxyTest).build(); Request request = new Request.Builder().url("https://www.baidu.com").build(); Response response = client.newCall(request).execute(); System.out.println("状态码: " + response.code()); System.out.println("响应内容: \n" + response.body().string()); client.dispatcher().executorService().shutdown(); client.connectionPool().evictAll(); }
private static PasswordAuthentication privilegedRequestPasswordAuthentication( final String host, final InetAddress addr, final int port, final String protocol, final String prompt, final String scheme, final URL url, final RequestorType authType) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<PasswordAuthentication>() { public PasswordAuthentication run() { if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("Requesting Authentication: host =" + host + " url = " + url); } PasswordAuthentication pass = Authenticator.requestPasswordAuthentication( host, addr, port, protocol, prompt, scheme, url, authType); if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null")); } return pass; } }); }
@Override public Credential authenticateProxy( Proxy proxy, URL url, List<Challenge> challenges) throws IOException { for (Challenge challenge : challenges) { if (!"Basic".equalsIgnoreCase(challenge.getScheme())) { continue; } InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); PasswordAuthentication auth = Authenticator.requestPasswordAuthentication( proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url, Authenticator.RequestorType.PROXY); if (auth != null) { return Credential.basic(auth.getUserName(), new String(auth.getPassword())); } } return null; }
public Request authenticateProxy(Proxy proxy, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); HttpUrl url = request.httpUrl(); int size = challenges.size(); for (int i = 0; i < size; i++) { Challenge challenge = (Challenge) challenges.get(i); if ("Basic".equalsIgnoreCase(challenge.getScheme())) { InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); PasswordAuthentication auth = java.net.Authenticator .requestPasswordAuthentication(proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url .scheme(), challenge.getRealm(), challenge.getScheme(), url.url(), RequestorType.PROXY); if (auth != null) { return request.newBuilder().header("Proxy-Authorization", Credentials.basic (auth.getUserName(), new String(auth.getPassword()))).build(); } } } return null; }
@Override public Credential authenticate( Proxy proxy, URL url, List<Challenge> challenges) throws IOException { for (Challenge challenge : challenges) { if (!"Basic".equalsIgnoreCase(challenge.getScheme())) { continue; } PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(url.getHost(), getConnectToInetAddress(proxy, url), url.getPort(), url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url, Authenticator.RequestorType.SERVER); if (auth != null) { return Credential.basic(auth.getUserName(), new String(auth.getPassword())); } } return null; }
@Override protected PasswordAuthentication getPasswordAuthentication() { this.calls.add("host=" + getRequestingHost() + " port=" + getRequestingPort() + " site=" + getRequestingSite().getHostName() + " url=" + getRequestingURL() + " type=" + getRequestorType() + " prompt=" + getRequestingPrompt() + " protocol=" + getRequestingProtocol() + " scheme=" + getRequestingScheme()); return authentication; }
@Override public Request authenticate(Route route, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); HttpUrl url = request.url(); boolean proxyAuthorization = response.code() == 407; Proxy proxy = route.proxy(); for (int i = 0, size = challenges.size(); i < size; i++) { Challenge challenge = challenges.get(i); if (!"Basic".equalsIgnoreCase(challenge.scheme())) continue; PasswordAuthentication auth; if (proxyAuthorization) { InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); auth = java.net.Authenticator.requestPasswordAuthentication( proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url.scheme(), challenge.realm(), challenge.scheme(), url.url(), RequestorType.PROXY); } else { auth = java.net.Authenticator.requestPasswordAuthentication( url.host(), getConnectToInetAddress(proxy, url), url.port(), url.scheme(), challenge.realm(), challenge.scheme(), url.url(), RequestorType.SERVER); } if (auth != null) { String credential = Credentials.basic(auth.getUserName(), new String(auth.getPassword())); return request.newBuilder() .header(proxyAuthorization ? "Proxy-Authorization" : "Authorization", credential) .build(); } } return null; // No challenges were satisfied! }
static BadAuthProxyServer startServer() throws IOException { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("xyz", "xyz".toCharArray()); } }); BadAuthProxyServer server = new BadAuthProxyServer(new ServerSocket(0)); Thread serverThread = new Thread(server); serverThread.start(); return server; }
/** * Loads the NTLM authentiation implementation through reflection. If * the class is present, then it must have the required constructors and * method. Otherwise, it is considered an error. */ @SuppressWarnings("unchecked") private static NTLMAuthenticationProxy tryLoadNTLMAuthentication() { Class<? extends AuthenticationInfo> cl; Constructor<? extends AuthenticationInfo> fourArg, sixArg; try { cl = (Class<? extends AuthenticationInfo>)Class.forName(clazzStr, true, null); if (cl != null) { fourArg = cl.getConstructor(boolean.class, URL.class, PasswordAuthentication.class, String.class); sixArg = cl.getConstructor(boolean.class, String.class, int.class, PasswordAuthentication.class, String.class); supportsTA = cl.getDeclaredMethod(supportsTAStr); isTrustedSite = cl.getDeclaredMethod(isTrustedSiteStr, java.net.URL.class); return new NTLMAuthenticationProxy(fourArg, sixArg); } } catch (ClassNotFoundException cnfe) { finest(cnfe); } catch (ReflectiveOperationException roe) { throw new AssertionError(roe); } return null; }
@Override public Request authenticate(Route route, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); HttpUrl url = request.url(); boolean proxyAuthorization = response.code() == 407; Proxy proxy = route.proxy(); for (int i = 0, size = challenges.size(); i < size; i++) { Challenge challenge = challenges.get(i); if (!"Basic".equalsIgnoreCase(challenge.scheme())) continue; PasswordAuthentication auth; if (proxyAuthorization) { InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); auth = java.net.Authenticator.requestPasswordAuthentication( proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url.scheme(), challenge.realm(), challenge.scheme(), url.url(), RequestorType.PROXY); } else { auth = java.net.Authenticator.requestPasswordAuthentication( url.host(), getConnectToInetAddress(proxy, url), url.port(), url.scheme(), challenge.realm(), challenge.scheme(), url.url(), RequestorType.SERVER); } if (auth != null) { String credential = Credentials.basic( auth.getUserName(), new String(auth.getPassword()), challenge.charset()); return request.newBuilder() .header(proxyAuthorization ? "Proxy-Authorization" : "Authorization", credential) .build(); } } return null; // No challenges were satisfied! }
public static PasswordAuthentication getPasswordAuthentication( String realm, URL tracker ) { return( SESecurityManagerImpl.getSingleton().getPasswordAuthentication(realm, tracker)); }
synchronized void store(String authscheme, URI domain, boolean proxy, PasswordAuthentication value) { remove(authscheme, domain, proxy); entries.add(new CacheEntry(authscheme, domain, proxy, value)); }
/** * @param url * @param forceLogin * @return * @see TeamAccessor#getPasswordAuthentication(java.lang.String, boolean) */ public static PasswordAuthentication getPasswordAuthentication(String url, boolean forceLogin) { for (TeamAccessor ka : getTeamAccessors()) { PasswordAuthentication pa = ka.getPasswordAuthentication(url, forceLogin); if (pa != null) { return pa; } } return null; }
/** * Create a NTLMAuthentication: * Username may be specified as domain<BACKSLASH>username in the application Authenticator. * If this notation is not used, then the domain will be taken * from a system property: "http.auth.ntlm.domain". */ public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, AuthScheme.NTLM, url, ""); init (pw); }
@Override protected void populateCredentials(PasswordAuthentication pa) { settingsPanel.userTextField.setText(pa.getUserName()); settingsPanel.userPasswordField.setText(new String(pa.getPassword())); settingsPanel.savePasswordCheckBox.setSelected(true); settingsPanel.savePasswordCheckBox.setEnabled(false); }
public RepositoryStep (CloneWizard wiz, PasswordAuthentication pa, String forPath) { this.wiz = wiz; repository = new RemoteRepository(pa, forPath); repository.addChangeListener(this); panel = new RepositoryStepPanel(repository.getPanel()); panel.txtDestination.getDocument().addDocumentListener(this); validateRepository(); }
public SvnClient getClient(SVNUrl repositoryUrl, SvnProgressSupport progressSupport) throws SVNClientException { Parameters.notNull("repositoryUrl", repositoryUrl); //NOI18N String username = ""; // NOI18N char[] password = null; SvnKenaiAccessor kenaiSupport = SvnKenaiAccessor.getInstance(); if(kenaiSupport.isKenai(repositoryUrl.toString())) { PasswordAuthentication pa = kenaiSupport.getPasswordAuthentication(repositoryUrl.toString(), false); if(pa != null) { username = pa.getUserName(); password = pa.getPassword(); } } else { RepositoryConnection rc = SvnModuleConfig.getDefault().getRepositoryConnection(repositoryUrl.toString()); if(rc != null) { username = rc.getUsername(); password = rc.getPassword(); } else if(!Utilities.isWindows()) { PasswordFile pf = PasswordFile.findFileForUrl(repositoryUrl); if(pf != null) { username = pf.getUsername(); String psswdString = pf.getPassword(); password = psswdString != null ? psswdString.toCharArray() : null; } } } return getClient(repositoryUrl, username, password, progressSupport); }
private void getKenaiAuthData(SvnKenaiAccessor support) { final String urlString = url.toString(); PasswordAuthentication pa = support.getPasswordAuthentication(urlString, true); if(pa == null) { throw new RuntimeException(new InterruptedException(org.openide.util.NbBundle.getMessage(SvnClientExceptionHandler.class, "MSG_ActionCanceledByUser"))); //NOI18N } String user = pa.getUserName(); char[] psswd = pa.getPassword(); username = user != null ? user : ""; password = psswd; }
@Override protected PasswordAuthentication getPasswordAuthentication() { //If user sets proxy user and passwd and the RequestType is from proxy server then create // PasswordAuthentication using proxyUser and proxyPasswd; if ((getRequestorType() == RequestorType.PROXY) && proxyUser != null && proxyPasswd != null) { return new PasswordAuthentication(proxyUser, proxyPasswd.toCharArray()); } for (AuthInfo auth : authInfo) { if (auth.matchingHost(getRequestingURL())) { return new PasswordAuthentication(auth.getUser(), auth.getPassword().toCharArray()); } } return null; }
@Override protected PasswordAuthentication getPasswordAuthentication() { Logger.getLogger(NbAuthenticator.class.getName()).log(Level.FINER, "Authenticator.getPasswordAuthentication() with prompt " + this.getRequestingPrompt()); //NOI18N if (RequestorType.PROXY == getRequestorType() && ProxySettings.useAuthentication()) { Logger.getLogger(NbAuthenticator.class.getName()).log(Level.FINER, "Username set to " + ProxySettings.getAuthenticationUsername() + " while request " + this.getRequestingURL()); //NOI18N return new java.net.PasswordAuthentication(ProxySettings.getAuthenticationUsername(), ProxySettings.getAuthenticationPassword()); } else { if (System.currentTimeMillis() - lastTry > TIMEOUT) { if (getRequestingProtocol().startsWith("SOCKS")&&(ProxySettings.getAuthenticationUsername().length()>0)) { //NOI18N return new java.net.PasswordAuthentication(ProxySettings.getAuthenticationUsername(), ProxySettings.getAuthenticationPassword()); } if (NetworkSettings.isAuthenticationDialogSuppressed()) { return null; } PasswordAuthentication auth = getAuthenticationFromURL(); if (auth != null) { return auth; } NbAuthenticatorPanel ui = new NbAuthenticatorPanel(getRequestingPrompt()); Object result = DialogDisplayer.getDefault().notify( new DialogDescriptor(ui, NbBundle.getMessage(NbAuthenticator.class, "CTL_Authentication"))); //NOI18N if (DialogDescriptor.OK_OPTION == result) { lastTry = 0; return new PasswordAuthentication(ui.getUserName(), ui.getPassword()); } else { lastTry = System.currentTimeMillis(); } } } Logger.getLogger(NbAuthenticator.class.getName()).log(Level.WARNING, "No authentication set while requesting " + this.getRequestingURL()); //NOI18N return null; }
/** * Loads the NTLM authentiation implementation through reflection. If * the class is present, then it must have the required constructors and * method. Otherwise, it is considered an error. */ @SuppressWarnings("unchecked") private static NTLMAuthenticationProxy tryLoadNTLMAuthentication() { Class<? extends AuthenticationInfo> cl; Constructor<? extends AuthenticationInfo> threeArg, fiveArg; try { cl = (Class<? extends AuthenticationInfo>)Class.forName(clazzStr, true, null); if (cl != null) { threeArg = cl.getConstructor(boolean.class, URL.class, PasswordAuthentication.class); fiveArg = cl.getConstructor(boolean.class, String.class, int.class, PasswordAuthentication.class); supportsTA = cl.getDeclaredMethod(supportsTAStr); isTrustedSite = cl.getDeclaredMethod(isTrustedSiteStr, java.net.URL.class); return new NTLMAuthenticationProxy(threeArg, fiveArg); } } catch (ClassNotFoundException cnfe) { finest(cnfe); } catch (ReflectiveOperationException roe) { throw new AssertionError(roe); } return null; }
public void bad7() throws Exception { byte[] bytes = new byte[2]; char[] pwd = "secret7".toCharArray(); new PBEKeySpec(pwd); new PBEKeySpec(pwd, bytes, 1); new PBEKeySpec(pwd, bytes, 1, 1); PasswordAuthentication auth = new PasswordAuthentication("user", pwd); PasswordCallback callback = new PasswordCallback("str", true); callback.setPassword(pwd); KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(pwd); KerberosKey key = new KerberosKey(null, pwd, "alg"); KeyManagerFactory.getInstance("").init(null, pwd); }
public DigestAuthentication(boolean isProxy, String host, int port, String realm, String authMethod, PasswordAuthentication pw, Parameters params, String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, AuthScheme.DIGEST, host, port, realm, Objects.requireNonNull(authenticatorKey)); this.authMethod = authMethod; this.pw = pw; this.params = params; }
private static PasswordAuthentication handleAuthenticationError(List<String> cmdOutput, File repository, String url, String userName, UserCredentialsSupport credentialsSupport, String hgCommand, boolean showLoginDialog) throws HgException { PasswordAuthentication credentials = null; String msg = cmdOutput.get(cmdOutput.size() - 1).toLowerCase(); if (isAuthMsg(msg) && showLoginDialog) { HgKenaiAccessor support = HgKenaiAccessor.getInstance(); if(support.isKenai(url)) { checkKenaiPermissions(hgCommand, url, support); // try to login credentials = handleKenaiAuthorisation(support, url); } else { credentials = credentialsSupport.getUsernamePasswordCredentials(repository, url, userName); } } return credentials; }
/** * Create a BasicAuthentication */ public BasicAuthentication(boolean isProxy, String host, int port, String realm, PasswordAuthentication pw) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, AuthScheme.BASIC, host, port, realm); String plain = pw.getUserName() + ":"; byte[] nameBytes = null; try { nameBytes = plain.getBytes("ISO-8859-1"); } catch (java.io.UnsupportedEncodingException uee) { assert false; } // get password bytes char[] passwd = pw.getPassword(); byte[] passwdBytes = new byte[passwd.length]; for (int i=0; i<passwd.length; i++) passwdBytes[i] = (byte)passwd[i]; // concatenate user name and password bytes and encode them byte[] concat = new byte[nameBytes.length + passwdBytes.length]; System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length); System.arraycopy(passwdBytes, 0, concat, nameBytes.length, passwdBytes.length); this.auth = "Basic " + Base64.getEncoder().encodeToString(concat); this.pw = pw; }
@Override public PasswordAuthentication getAuthentication(URL url) throws PasswordInputCanceledException { if (url.getProtocol().equals(protocol)) { String username = ParameterService.getParameterValue(protocol + ".proxyUsername"); String password = ParameterService.getParameterValue(protocol + ".proxyPassword"); // password is stored encrypted, try to decrypt password if (password != null && CipherTools.isKeyAvailable()) { try { password = CipherTools.decrypt(password); } catch (CipherException e) { // password is in plaintext } } if (username == null || username.isEmpty() || password == null) { // empty // passwords // possibly // valid! PasswordAuthentication passwordAuthentication = PasswordDialog.getPasswordAuthentication("proxy for " + url.toString(), true, false); if (passwordAuthentication == null) { return null; } ParameterService.setParameterValue(protocol + ".proxyUsername", passwordAuthentication.getUserName()); ParameterService.setParameterValue(protocol + ".proxyPassword", new String(passwordAuthentication.getPassword())); ParameterService.saveParameters(); return passwordAuthentication; } return new PasswordAuthentication(username, password.toCharArray()); } return null; }
public static void main(String[] args) throws Exception { try { Class<?> ntlmProxyClass = Class.forName("sun.net.www.protocol.http.NTLMAuthenticationProxy", true, NoNTLM.class.getClassLoader()); Field ntlmSupportedField = ntlmProxyClass.getDeclaredField("supported"); ntlmSupportedField.setAccessible(true); if (ntlmSupportedField.getBoolean(null)) { System.out.println("NTLM is supported. Nothing to do. Exiting."); return; } } catch (ClassNotFoundException okay) { } // setup Authenticator Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("user", "pass".toCharArray()); } }); // test combinations of authentication schemes test("Basic"); test("Digest"); test("Basic", "Digest"); test("Basic", "NTLM"); test("Digest", "NTLM"); test("Basic", "Digest", "NTLM"); // test NTLM only, this should fail with "401 Unauthorized" testNTLM(); System.out.println(); System.out.println("TEST PASSED"); }