类java.net.Authenticator源码实例Demo

下面列出了怎么用java.net.Authenticator的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cxf   文件: ReferencingAuthenticator.java
private void remove() {
    try {
        for (final Field f : Authenticator.class.getDeclaredFields()) {
            if (f.getType().equals(Authenticator.class)) {
                try {
                    f.setAccessible(true);
                    Authenticator o = (Authenticator)f.get(null);
                    if (o == this) {
                        //this is at the root of any chain of authenticators
                        Authenticator.setDefault(wrapped);
                    } else {
                        removeFromChain(o);
                    }
                } catch (Exception e) {
                    //ignore
                }
            }
        }
    } catch (Throwable t) {
        //ignore
    }
}
 
@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 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;
}
 
源代码4 项目: TencentKona-8   文件: HttpURLConnection.java
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;
            }
        });
}
 
@Bean
public DefaultBotOptions defaultBotOptions() {
    if (properties.hasAuthData()) {
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getUser(), properties.getPassword().toCharArray());
            }
        });
    }
    DefaultBotOptions botOptions = new DefaultBotOptions();
    botOptions.setProxyHost(properties.getHost());
    botOptions.setProxyPort(properties.getPort());
    botOptions.setProxyType(properties.getType());
    return botOptions;
}
 
源代码6 项目: onetwo   文件: HttpProxy.java
public Authenticator getAuthenticator() {
	if (this.authenticator == null && StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
		this.authenticator = new Authenticator() {

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				if (this.getRequestorType().equals(RequestorType.PROXY))
					return new PasswordAuthentication(user, password.toCharArray());
				else
					return null;
			}

		};
	}
	return authenticator;
}
 
源代码7 项目: jdk8u-dev-jdk   文件: HttpURLConnection.java
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;
            }
        });
}
 
源代码8 项目: jdk8u60   文件: NegotiateCallbackHandler.java
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();
        }
    }
}
 
源代码9 项目: phonegapbootcampsite   文件: HttpAuthenticator.java
@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;
}
 
源代码10 项目: reader   文件: HttpAuthenticator.java
@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;
}
 
源代码11 项目: che   文件: ProxyAuthenticatorTest.java
@Test
public void shouldInitHttpsProxyAuthenticator() throws Exception {
  // when
  ProxyAuthenticator.initAuthenticator(HTTPS_URL);
  PasswordAuthentication testAuthentication =
      Authenticator.requestPasswordAuthentication(null, 0, null, null, null);

  // then
  assertEquals(testAuthentication.getUserName(), "user2");
  assertEquals(String.valueOf(testAuthentication.getPassword()), "paswd2");

  // when
  ProxyAuthenticator.resetAuthenticator();

  // then
  testAuthentication = Authenticator.requestPasswordAuthentication(null, 0, null, null, null);
  assertEquals(testAuthentication, null);
}
 
源代码12 项目: mangooio   文件: TestResponse.java
/**
 * Sets Basic HTTP Authentication the request
 *
 * @param username The username
 * @param password The password
 * 
 * @return TestResponse instance
 */
public TestResponse withBasicAuthentication(String username, String password) {
    Objects.requireNonNull(username, Required.USERNAME.toString());
    Objects.requireNonNull(password, Required.PASSWORD.toString());

    this.authenticator = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(
            username, 
            password.toCharArray());
        }
    };
    
    return this;
}
 
源代码13 项目: IoTgo_Android_App   文件: HttpAuthenticator.java
@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;
}
 
源代码14 项目: jdk8u-jdk   文件: NegotiateCallbackHandler.java
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();
        }
    }
}
 
源代码15 项目: jiguang-java-client-common   文件: Http2Client.java
public Http2Client(String authCode, HttpProxy proxy, ClientConfig config) {
    _maxRetryTimes = config.getMaxRetryTimes();
    _connectionTimeout = config.getConnectionTimeout();
    _readTimeout = config.getReadTimeout();
    _sslVer = config.getSSLVersion();

    _authCode = authCode;
    _proxy = proxy;
    _encryptType = config.getEncryptType();
    String message = MessageFormat.format("Created instance with "
                    + "connectionTimeout {0}, readTimeout {1}, maxRetryTimes {2}, SSL Version {3}",
            _connectionTimeout, _readTimeout, _maxRetryTimes, _sslVer);
    LOG.info(message);

    if (null != _proxy && _proxy.isAuthenticationNeeded()) {
        Authenticator.setDefault(new NativeHttpClient.SimpleProxyAuthenticator(
                _proxy.getUsername(), _proxy.getPassword()));
    }
}
 
源代码16 项目: tutorials   文件: HttpClientUnitTest.java
@Test
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/basic-auth"))
        .GET()
        .build();
    HttpResponse<String> response = HttpClient.newBuilder()
        .authenticator(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("postman", "password".toCharArray());
            }
        })
        .build()
        .send(request, HttpResponse.BodyHandlers.ofString());

    assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
 
源代码17 项目: ripme   文件: Proxy.java
/**
 * Set a HTTP Proxy.
 * WARNING: Authenticated HTTP Proxy won't work from jdk1.8.111 unless
 * passing the flag -Djdk.http.auth.tunneling.disabledSchemes="" to java
 * see https://stackoverflow.com/q/41505219
 *
 * @param fullproxy the proxy, using format [user:password]@host[:port]
 */
public static void setHTTPProxy(String fullproxy) {
    Map<String, String> proxyServer = parseServer(fullproxy);

    if (proxyServer.get("user") != null && proxyServer.get("password") != null) {
        Authenticator.setDefault(new Authenticator(){
            protected PasswordAuthentication  getPasswordAuthentication(){
                PasswordAuthentication p = new PasswordAuthentication(proxyServer.get("user"), proxyServer.get("password").toCharArray());
                return p;
            }
        });
        System.setProperty("http.proxyUser", proxyServer.get("user"));
        System.setProperty("http.proxyPassword", proxyServer.get("password"));
        System.setProperty("https.proxyUser", proxyServer.get("user"));
        System.setProperty("https.proxyPassword", proxyServer.get("password"));
    }

    if (proxyServer.get("port") != null) {
        System.setProperty("http.proxyPort", proxyServer.get("port"));
        System.setProperty("https.proxyPort", proxyServer.get("port"));
    }

    System.setProperty("http.proxyHost", proxyServer.get("server"));
    System.setProperty("https.proxyHost", proxyServer.get("server"));
}
 
源代码18 项目: ripme   文件: Proxy.java
/**
 * Set a Socks Proxy Server (globally).
 *
 * @param fullsocks the socks server, using format [user:password]@host[:port]
 */
public static void setSocks(String fullsocks) {

    Map<String, String> socksServer = parseServer(fullsocks);
    if (socksServer.get("user") != null && socksServer.get("password") != null) {
        Authenticator.setDefault(new Authenticator(){
            protected PasswordAuthentication  getPasswordAuthentication(){
                PasswordAuthentication p = new PasswordAuthentication(socksServer.get("user"), socksServer.get("password").toCharArray());
                return p;
            }
        });
        System.setProperty("java.net.socks.username", socksServer.get("user"));
        System.setProperty("java.net.socks.password", socksServer.get("password"));
    }
    if (socksServer.get("port") != null) {
        System.setProperty("socksProxyPort", socksServer.get("port"));
    }

    System.setProperty("socksProxyHost", socksServer.get("server"));
}
 
源代码19 项目: hottub   文件: HttpURLConnection.java
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;
            }
        });
}
 
源代码20 项目: webi   文件: Webi.java
public Webi setProxy(String host, int port, final String username, final String password) {
    webService.is_proxy_seted = true;
    webService.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", String.valueOf(port));
    System.setProperty("http.proxyUser", username);
    System.setProperty("http.proxyPassword", password);

    Authenticator.setDefault(
            new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password.toCharArray());
                }
            }
    );
    return this;
}
 
源代码21 项目: webi   文件: WebiConfig.java
public WebiConfig setDefaultProxy(String host, int port, final String username, final String password) {
    WebiConfig.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", String.valueOf(port));
    System.setProperty("http.proxyUser", username);
    System.setProperty("http.proxyPassword", password);

    Authenticator.setDefault(
            new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password.toCharArray());
                }
            }
    );

    return this;
}
 
源代码22 项目: cxf   文件: ReferencingAuthenticator.java
@Override
protected PasswordAuthentication getPasswordAuthentication() {
    Authenticator cxfauth = auth.get();
    if (cxfauth == null) {
        remove();
    }
    PasswordAuthentication pauth = null;
    if (wrapped != null) {
        try {
            pauth = tryWith(wrapped);
            if (pauth != null) {
                return pauth;
            }
        } catch (Exception e) {
            pauth = null;
        }
    }
    if (cxfauth != null) {
        try {
            pauth = tryWith(cxfauth);
        } catch (Exception e1) {
            pauth = null;
        }
    }
    return pauth;
}
 
源代码23 项目: phonegapbootcampsite   文件: HttpAuthenticator.java
@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;
}
 
源代码24 项目: jdk8u-dev-jdk   文件: NegotiateCallbackHandler.java
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();
        }
    }
}
 
源代码25 项目: Bytecoder   文件: HttpCallerInfo.java
/**
 * Constructor an un-schemed object for site access.
 */
public HttpCallerInfo(URL url, Authenticator a) {
    this.url= url;
    prompt = "";
    host = url.getHost();

    int p = url.getPort();
    if (p == -1) {
        port = url.getDefaultPort();
    } else {
        port = p;
    }

    InetAddress ia;
    try {
        ia = InetAddress.getByName(url.getHost());
    } catch (Exception e) {
        ia = null;
    }
    addr = ia;

    protocol = url.getProtocol();
    authType = RequestorType.SERVER;
    scheme = "";
    authenticator = a;
}
 
源代码26 项目: components   文件: SalesforceProxyTestIT.java
private static void setProxySettingForClient() {
    System.setProperty("http.proxySet", "true");
    System.setProperty("http.proxyHost", "127.0.0.1");
    System.setProperty("http.proxyPort", "" + proxyPort);
    System.setProperty("http.proxyUser", proxyUsername);
    System.setProperty("http.proxyPassword", proxyPassword);

    Authenticator.setDefault(new Authenticator() {

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray());
        }

    });
}
 
源代码27 项目: openjdk-jdk9   文件: HttpCallerInfo.java
/**
 * Constructor an un-schemed object for site access.
 */
public HttpCallerInfo(URL url, Authenticator a) {
    this.url= url;
    prompt = "";
    host = url.getHost();

    int p = url.getPort();
    if (p == -1) {
        port = url.getDefaultPort();
    } else {
        port = p;
    }

    InetAddress ia;
    try {
        ia = InetAddress.getByName(url.getHost());
    } catch (Exception e) {
        ia = null;
    }
    addr = ia;

    protocol = url.getProtocol();
    authType = RequestorType.SERVER;
    scheme = "";
    authenticator = a;
}
 
源代码28 项目: jdk8u_jdk   文件: SocksIPv6Test.java
@BeforeClass
public void setUp() throws Exception {
    shouldRun = ensureInet6AddressFamily() && ensureIPv6OnLoopback();

    server = HttpServer.create(new InetSocketAddress(0), 0);
    server.createContext("/", ex -> {
        ex.sendResponseHeaders(200, response.length());
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(ex.getResponseBody(), "UTF-8"))) {
            writer.write(response);
        }
        ex.close();
    });
    server.start();

    socks = new SocksServer(0, false);
    socks.addUser("user", "pass");
    socks.start();

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected java.net.PasswordAuthentication getPasswordAuthentication() {
            return new java.net.PasswordAuthentication(
                    "user", "pass".toCharArray());
        }
    });
}
 
源代码29 项目: cxf   文件: AbstractCodegenMojo.java
protected void configureProxyServerSettings() throws MojoExecutionException {

        Proxy proxy = mavenSession.getSettings().getActiveProxy();

        if (proxy != null) {

            getLog().info("Using proxy server configured in maven.");

            if (proxy.getHost() == null) {
                throw new MojoExecutionException("Proxy in settings.xml has no host");
            }
            if (proxy.getHost() != null) {
                System.setProperty(HTTP_PROXY_HOST, proxy.getHost());
            }
            if (String.valueOf(proxy.getPort()) != null) {
                System.setProperty(HTTP_PROXY_PORT, String.valueOf(proxy.getPort()));
            }
            if (proxy.getNonProxyHosts() != null) {
                System.setProperty(HTTP_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
            }
            if (!StringUtils.isEmpty(proxy.getUsername())
                && !StringUtils.isEmpty(proxy.getPassword())) {
                final String authUser = proxy.getUsername();
                final String authPassword = proxy.getPassword();
                Authenticator.setDefault(new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(authUser, authPassword.toCharArray());
                    }
                });

                System.setProperty(HTTP_PROXY_USER, authUser);
                System.setProperty(HTTP_PROXY_PASSWORD, authPassword);
            }

        }
    }
 
源代码30 项目: dragonwell8_jdk   文件: SocksIPv6Test.java
@BeforeClass
public void setUp() throws Exception {
    shouldRun = ensureInet6AddressFamily() && ensureIPv6OnLoopback();

    server = HttpServer.create(new InetSocketAddress(0), 0);
    server.createContext("/", ex -> {
        ex.sendResponseHeaders(200, response.length());
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(ex.getResponseBody(), "UTF-8"))) {
            writer.write(response);
        }
        ex.close();
    });
    server.start();

    socks = new SocksServer(0, false);
    socks.addUser("user", "pass");
    socks.start();

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected java.net.PasswordAuthentication getPasswordAuthentication() {
            return new java.net.PasswordAuthentication(
                    "user", "pass".toCharArray());
        }
    });
}
 
 类所在包
 同包方法