Java Code Examples for java.net.PasswordAuthentication

The following are top voted examples for showing how to use java.net.PasswordAuthentication. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: NetworkSettingsTest.java   Source Code and License 6 votes vote down vote up
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]);
}
 
Example 2
Project: jdk8u-jdk   File: NegotiateCallbackHandler.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
}
 
Example 3
Project: jdk8u-jdk   File: NTLMAuthentication.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 4
Project: openjdk-jdk10   File: NTLMAuthentication.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 5
Project: incubator-netbeans   File: HgKenaiAccessor.java   Source Code and License 6 votes vote down vote up
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;
    }
}
 
Example 6
Project: oryx2   File: SecureAPIConfigIT.java   Source Code and License 6 votes vote down vote up
@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);
  }
}
 
Example 7
Project: probe   File: HttpProxyClient.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 8
Project: OpenJSharp   File: HttpURLConnection.java   Source Code and License 6 votes vote down vote up
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;
            }
        });
}
 
Example 9
Project: OpenJSharp   File: NegotiateCallbackHandler.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
}
 
Example 10
Project: OpenJSharp   File: NTLMAuthentication.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 11
Project: LoRaWAN-Smart-Parking   File: HttpAuthenticator.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 12
Project: LoRaWAN-Smart-Parking   File: HttpAuthenticator.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 13
Project: GitHub   File: RecordingAuthenticator.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 14
Project: GitHub   File: JavaNetAuthenticator.java   Source Code and License 5 votes vote down vote up
@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!
}
 
Example 15
Project: jdk8u-jdk   File: HttpsProxyStackOverflow.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 16
Project: GitHub   File: RecordingAuthenticator.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 17
Project: openjdk-jdk10   File: NTLMAuthenticationProxy.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 18
Project: GitHub   File: JavaNetAuthenticator.java   Source Code and License 5 votes vote down vote up
@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!
}
 
Example 19
Project: BiglyBT   File: SESecurityManager.java   Source Code and License 5 votes vote down vote up
public static PasswordAuthentication
getPasswordAuthentication(
	String		realm,
	URL			tracker )
{
	return( SESecurityManagerImpl.getSingleton().getPasswordAuthentication(realm, tracker));
}
 
Example 20
Project: openjdk-jdk10   File: AuthenticationFilter.java   Source Code and License 5 votes vote down vote up
synchronized void store(String authscheme,
                        URI domain,
                        boolean proxy,
                        PasswordAuthentication value) {
    remove(authscheme, domain, proxy);
    entries.add(new CacheEntry(authscheme, domain, proxy, value));
}
 
Example 21
Project: incubator-netbeans   File: TeamAccessorUtils.java   Source Code and License 5 votes vote down vote up
/**
 * @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;
}
 
Example 22
Project: jdk8u-jdk   File: NTLMAuthentication.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 23
Project: incubator-netbeans   File: RemoteRepository.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 24
Project: incubator-netbeans   File: RemoteRepository.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 25
Project: incubator-netbeans   File: RepositoryStep.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 26
Project: incubator-netbeans   File: Subversion.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 27
Project: incubator-netbeans   File: SvnClientCallback.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 28
Project: openjdk-jdk10   File: DefaultAuthenticator.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 29
Project: incubator-netbeans   File: NbAuthenticator.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 30
Project: incubator-netbeans   File: NbAuthenticatorTest.java   Source Code and License 5 votes vote down vote up
public void testUserInfoInUrl () throws Exception {
    NbAuthenticator.install4test();
    PasswordAuthentication auth = Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http",
            new URL("http://user:[email protected]/resource"), Authenticator.RequestorType.SERVER);
    
    assertNotNull(auth);
    assertEquals("user", auth.getUserName());
    assertEquals("password", new String(auth.getPassword()));
}
 
Example 31
Project: openjdk-jdk10   File: HttpsProxyStackOverflow.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 32
Project: jdk8u-jdk   File: NTLMAuthenticationProxy.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 33
Project: Android_Code_Arbiter   File: ConstantPasswords.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 34
Project: openjdk-jdk10   File: DigestAuthentication.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 35
Project: incubator-netbeans   File: HgCommand.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 36
Project: jdk8u-jdk   File: BasicAuthentication.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 37
Project: rapidminer   File: GlobalAuthenticator.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 38
Project: openjdk-jdk10   File: NoNTLM.java   Source Code and License 5 votes vote down vote up
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");
}
 
Example 39
Project: openjdk-jdk10   File: SmokeTest.java   Source Code and License 5 votes vote down vote up
@Override
protected PasswordAuthentication getPasswordAuthentication() {
    if (count++ == 0) {
        return new PasswordAuthentication("user", "passwd".toCharArray());
    } else {
        return new PasswordAuthentication("user", "goober".toCharArray());
    }
}
 
Example 40
Project: jdk8u-jdk   File: BasicAuthentication.java   Source Code and License 5 votes vote down vote up
/**
 * Create a BasicAuthentication
 */
public BasicAuthentication(boolean isProxy, URL url, String realm,
                               PasswordAuthentication pw) {
    super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
          AuthScheme.BASIC, url, 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;
}