微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.net.PasswordAuthentication的实例源码

项目:incubator-netbeans    文件NetworkSettingsTest.java   
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]);
}
项目:incubator-netbeans    文件RemoteRepository.java   
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();
}
项目: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();
        }
    }
}
项目:jdk8u-jdk    文件NTLMAuthentication.java   
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();
}
项目:openjdk-jdk10    文件NTLMAuthentication.java   
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();
}
项目:incubator-netbeans    文件HgKenaiAccessor.java   
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;
    }
}
项目:oryx2    文件SecureAPIConfigIT.java   
@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);
  }
}
项目:probe    文件HttpProxyClient.java   
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();
}
项目:Openjsharp    文件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;
            }
        });
}
项目:Openjsharp    文件NegotiateCallbackHandler.java   
private void getAnswer() {
    if (!answered) {
        answered = true;
        PasswordAuthentication passAuth =
                Authenticator.requestPasswordAuthentication(
                hci.host,username and
         * password are assigned null. No exception is thrown.
         */
        if (passAuth != null) {
            username = passAuth.getUserName();
            password = passAuth.getpassword();
        }
    }
}
项目:Openjsharp    文件NTLMAuthentication.java   
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();
}
项目:LoRaWAN-Smart-Parking    文件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(),Authenticator.RequestorType.PROXY);
    if (auth != null) {
      return Credential.basic(auth.getUserName(),new String(auth.getpassword()));
    }
  }
  return null;
}
项目:boohee_v5.6    文件AuthenticatorAdapter.java   
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(),url
                                    .scheme(),url.url(),RequestorType.PROXY);
            if (auth != null) {
                return request.newBuilder().header("Proxy-Authorization",Credentials.basic
                        (auth.getUserName(),new String(auth.getpassword()))).build();
            }
        }
    }
    return null;
}
项目:LoRaWAN-Smart-Parking    文件HttpAuthenticator.java   
@Override public Credential authenticate(
    Proxy proxy,List<Challenge> challenges) throws IOException {
  for (Challenge challenge : challenges) {
    if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
      continue;
    }

    PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(url.getHost(),url.getPort(),Authenticator.RequestorType.SERVER);
    if (auth != null) {
      return Credential.basic(auth.getUserName(),new String(auth.getpassword()));
    }
  }
  return null;
}
项目:GitHub    文件RecordingAuthenticator.java   
@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;
}
项目:GitHub    文件JavaNetAuthenticator.java   
@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(),url.scheme(),challenge.realm(),challenge.scheme(),RequestorType.PROXY);
    } else {
      auth = java.net.Authenticator.requestPasswordAuthentication(
          url.host(),url.port(),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!
}
项目:jdk8u-jdk    文件HttpsProxyStackOverflow.java   
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;
}
项目:openjdk-jdk10    文件NTLMAuthenticationProxy.java   
/**
 * 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,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;
}
项目:GitHub    文件JavaNetAuthenticator.java   
@Override public Request authenticate(Route route,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!
}
项目:BiglyBT    文件SESecurityManager.java   
public static PasswordAuthentication
getpasswordAuthentication(
    String      realm,URL         tracker )
{
    return( SESecurityManagerImpl.getSingleton().getpasswordAuthentication(realm,tracker));
}
项目:openjdk-jdk10    文件AuthenticationFilter.java   
synchronized void store(String authscheme,URI domain,boolean proxy,PasswordAuthentication value) {
    remove(authscheme,domain,proxy);
    entries.add(new CacheEntry(authscheme,proxy,value));
}
项目:incubator-netbeans    文件TeamAccessorUtils.java   
/**
 * @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;
}
项目:jdk8u-jdk    文件NTLMAuthentication.java   
/**
 * 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,PasswordAuthentication pw) {
    super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,AuthScheme.NTLM,"");
    init (pw);
}
项目:incubator-netbeans    文件RemoteRepository.java   
@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);
}
项目:incubator-netbeans    文件RepositoryStep.java   
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();
}
项目:incubator-netbeans    文件Subversion.java   
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);
}
项目:incubator-netbeans    文件SvnClientCallback.java   
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;
}
项目:openjdk-jdk10    文件DefaultAuthenticator.java   
@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;
}
项目:incubator-netbeans    文件NbAuthenticator.java   
@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;
}
项目:openjdk-jdk10    文件HttpsProxyStackOverflow.java   
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;
}
项目:jdk8u-jdk    文件NTLMAuthenticationProxy.java   
/**
 * Loads the NTLM authentiation implementation through reflection. If
 * the class is present,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,null);
        if (cl != null) {
            threeArg = cl.getConstructor(boolean.class,PasswordAuthentication.class);
            fiveArg = cl.getConstructor(boolean.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;
}
项目:Android_Code_Arbiter    文件ConstantPasswords.java   
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,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);
}
项目:openjdk-jdk10    文件DigestAuthentication.java   
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,realm,Objects.requireNonNull(authenticatorKey));
    this.authMethod = authMethod;
    this.pw = pw;
    this.params = params;
}
项目:incubator-netbeans    文件HgCommand.java   
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,support);
            // try to login
            credentials = handleKenaiAuthorisation(support,url);
        } else {
            credentials = credentialsSupport.getUsernamePasswordCredentials(repository,userName);
        }
    }
    return credentials;
}
项目:jdk8u-jdk    文件BasicAuthentication.java   
/**
 * Create a BasicAuthentication
 */
public BasicAuthentication(boolean isProxy,AuthScheme.BASIC,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,concat,nameBytes.length);
    System.arraycopy(passwdBytes,nameBytes.length,passwdBytes.length);
    this.auth = "Basic " + Base64.getEncoder().encodetoString(concat);
    this.pw = pw;
}
项目:rapidminer    文件GlobalAuthenticator.java   
@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(),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;
}
项目:openjdk-jdk10    文件NoNTLM.java   
public static void main(String[] args) throws Exception {
    try {
        Class<?> ntlmProxyClass = Class.forName("sun.net.www.protocol.http.NTLMAuthenticationProxy",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");
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。