2012-06-07 96 views
0

我想要做簡單的HTTP認證的Java小程序,其中我想是這樣的:Java程序不支持Authenticator.setDefault

static class MyAuthenticator extends Authenticator 
     { 
      public PasswordAuthentication getPasswordAuthentication() 
       { 
      // I haven't checked getRequestingScheme() here, since for NTLM 
      // and Negotiate, the usrname and password are all the same. 
      System.err.println("Feeding username and password for " + getRequestingScheme()); 
      return (new PasswordAuthentication(kuser, kpass.toCharArray())); 
      } 
     } 
    public void paint(Graphics g) { 
     try 
     { 
     // String authenticate=Authenticator.getPasswordAuthentication(); 
      Authenticator.setDefault(new MyAuthenticator()); 
      URL url = new URL("http://Ip_address/jpg/image.jpg"); 
      InputStream ins = url.openConnection().getInputStream(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(ins)); 
      String str; 
       while((str = reader.readLine()) != null) 
        System.out.println(str); 

      //int s=2+2; 

      g.drawString("hello world", 50, 60); 
     } 
     catch (Exception e) 
     { 
      System.out.println("Exception : "+ e); 
     } 
    } 

但我在這行

Authenticator.setDefault(new MyAuthenticator()); 
得到錯誤

唯一的例外是:

Exception : java.security.AccessControlException: access denied 
    (java.net.NetPermission setDefaultAuthenticator) 

誰能告訴我,現在給辦,或者如何將網站的內部認證來自Java小程序?

回答

1

您已遇到安全沙箱限制。顯然,不可信任的小程序需要更改默認的身份驗證程序,這是一個安全問題。 (我想這是因爲一個令人討厭的小程序可能會使用它來竊取用戶提供的認證細節。)

無論限制的原因是什麼,一種解決方案是爲applet簽名JAR文件。有關詳細信息,請參閱Oracle教程的this page

+0

是否有任何可以更改特定小程序的安全參數的命令/方法/類? –

+0

不在applet內。這將破壞安全沙箱的目的。 (問:什麼是令人討厭的applet的第一件事?答:關閉安全檢查,以防止它做噁心的事情!) –

+0

那麼是否有任何其他方法可以在java applet中進行基本的Http身份驗證? –