热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Java中的Java.net.Authenticator类

Java中的Java.net.Authenticator类

Java 中的 Java.net.Authenticator 类

原文:https://www . geesforgeks . org/Java-net-authenticator-class-Java/

认证器类用于需要认证才能访问某个网址的情况。一旦知道需要进行身份验证,它就会提示用户输入相同的内容,或者使用一些硬编码的用户名和密码。
要使用该类,请遵循以下步骤-


  1. 创建一个扩展验证器的类。让我们将其命名为 customAuth。

  2. 重写 getPasswordAuthentication()方法。此方法包含获取请求身份验证的实体的详细信息的几种方法。所有这些方法将在后面详细讨论。

  3. Set the newly created subclass as the default authenticator to be used when a http server asks for authentcation, with setDefault(Authenticator a) method of Authenticator class.

    方法:


    1. 设置默认值(认证者 a) : 设置当 HTTP 服务器需要认证时使用的认证者。

      ```java
      Syntax : public static void setDefault(Authenticator a)
      throws SecurityException
      Parameter :
      a : authenticator to be set as default
      Throws :
      SecurityException : if security manager doesn't allow
      setting default authenticator

      ```


    2. requestPasswordAuthentication() : Asks the authenticator registered with the system for password. Returns username/password or null if not found.

      ```java
      Syntax :
      public static PasswordAuthentication requestPasswordAuthentication(
      InetAddress addr,
      int port,
      String protocol,
      String prompt,
      String scheme)
      Parameter :
      addr : Inet address of the site asking for authentication
      port : port of requesting site
      protocol : protocol used for connection
      prompt : message for the user
      scheme : authentication scheme
      Throws :
      SecurityException : if security manager doesn't allow
      setting password authentication.

      ```

      另一种重载方法,可以在 inetaddress 不可用时使用主机名的情况下使用。

      ```java
      Syntax :
      public static PasswordAuthentication requestPasswordAuthentication(
      String host,
      InetAddress addr,
      int port,
      String protocol,
      String prompt,
      String scheme)
      Parameter :
      host : hostname of the site asking for authentication
      addr : Inet address of the site asking for authentication
      port : port of requesting site
      protocol : protocol used for connection
      prompt : message for the user
      scheme : authentication scheme
      Throws :
      SecurityException : if security manager doesn't allow
      setting password authentication.

      ```

      另一种重载方法,如果请求身份验证的站点的 URL 是已知的,而不是地址和主机名,则可以使用这种方法。

      ```java
      Syntax :
      public static PasswordAuthentication requestPasswordAuthentication(
      String host,
      InetAddress addr,
      int port,
      String protocol,
      String prompt,
      URL url,
      String scheme)
      Parameter :
      host : hostname of the site asking for authentication
      addr : Inet address of the site asking for authentication
      port : port of requesting site
      protocol : protocol used for connection
      prompt : message for the user
      url : URL of the site requesting authentication
      scheme : authentication scheme
      Throws :
      SecurityException : if security manager doesn't allow
      setting password authentication.

      ```


    3. getRequestingHost() :返回请求身份验证的站点的主机名。

      ```java
      Syntax : protected final String getRequestingHost()

      ```


    4. getRequestingSite() :返回请求认证的站点的地址。

      ```java
      Syntax : protected final InetAddress getRequestingSite()

      ```


    5. getRequestingPort() :返回连接的端口。

      ```java
      Syntax : protected final int getRequestingPort()

      ```


    6. getRequestingProtocol() :返回请求连接的协议。

      ```java
      Syntax : protected final String getRequestingProtocol()

      ```


    7. getrequestingrompt():返回请求者提示的消息。

      ```java
      Syntax : protected final String getRequestingPrompt()

      ```


    8. getRequestingScheme() :返回请求站点的方案。

      ```java
      Syntax : protected final String getRequestingScheme()

      ```


    9. getpassword authentication():需要密码验证时调用此方法。所有子类都必须重写此方法,因为默认方法总是返回 null。

      ```java
      Syntax : protected PasswordAuthentication getPasswordAuthentication()

      ```


    10. getRequestingURL() :返回请求者的 URL。

      ```java
      Syntax : protected final URL getRequestingURL()

      ```


    11. getRequestorType() :如果请求者是代理或者服务器,返回。

      ```java
      Syntax : protected Authenticator.RequestorType getRequestorType()

      ```


    Java 实现:

    ```java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.InetAddress;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;

    public class javanetauthenticator 
    {
        public static void main(String[] args) 
        {

    try {

    // setDefault() method
                // Sets the authenticator that will be used by the networking code
                // when a proxy or an HTTP server asks for authentication.
                Authenticator.setDefault(new CustomAuthenticator());

    URL url = new URL("http://securedwebsite.co.in/index.htm");

    // read text returned by server
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

    String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                in.close();

    } catch (MalformedURLException e) {
                System.out.println("Malformed URL: " + e.getMessage());
            } catch (IOException e) {
                System.out.println("I/O Error: " + e.getMessage());
            }

    }

    public static class CustomAuthenticator extends Authenticator 
        {

    // getPasswordAuthentication() method
            // Called when password authorization is needed
            protected PasswordAuthentication getPasswordAuthentication() 
            {

    // requestPasswordAuthentication() method
                // uncomment this if default authenticator is registered with
                // the system
                // PasswordAuthentication pa=requestPasswordAuthentication
                // (inetaddr, port, protocol, prompt, scheme);

    // getRequestingPrompt() method
                String prompt = getRequestingPrompt();

    // getRequestingHost() method
                String hostname = getRequestingHost();

    // getRequestingSite() method
                InetAddress ipaddr = getRequestingSite();

    // getRequestingPort() method
                int port = getRequestingPort();

    // getRequestingProtocol() method
                String protocol = getRequestingProtocol();

    // getRequestingScheme() method
                String scheme = getRequestingScheme();

    // getRequestingURL() method
                URL u = getRequestingURL();

    // getRequestorType() method
                RequestorType rtype = getRequestorType();

    System.out.println("prompt:" + prompt);
                System.out.println("hostname:" + hostname);
                System.out.println("ipaddress:" + ipaddr);
                System.out.println("port:" + port);
                System.out.println("protocolo:" + protocol);
                System.out.println("scheme:" + scheme);
                System.out.println("URL:" + u);
                System.out.println("Requester Type:" + rtype);

    // hardcoded username and password to be used
                // this part can be replaced by an interactive code
                // to take uid and pwd form user
                String username = "admin";
                String password = "admin1";

    // Return the information (a data holder that is used by
                // Authenticator)
                return new PasswordAuthentication(username, password.toCharArray());

    }

    }
    }
    ```

    注意:这个程序只是为了解释 Authenticator 类程序的流程。程序中使用的网址是随机选择的,不代表任何实际的网址。这个程序只是展示了如何使用 Authenticator 类的方法。通过将网址更改为需要验证才能进入的服务器来测试该程序。

    参考: 官方 Java 文档

    本文由里沙布·马赫塞供稿。如果你喜欢 GeeksforGeeks 并想投稿,你也可以使用contribute.geeksforgeeks.org写一篇文章或者把你的文章邮寄到 contribute@geeksforgeeks.org。看到你的文章出现在极客博客主页上,帮助其他极客。

    如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。



推荐阅读
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • Java在运行已编译完成的类时,是通过java虚拟机来装载和执行的,java虚拟机通过操作系统命令JAVA_HOMEbinjava–option来启 ... [详细]
  • 本文介绍了Python爬虫技术基础篇面向对象高级编程(中)中的多重继承概念。通过继承,子类可以扩展父类的功能。文章以动物类层次的设计为例,讨论了按照不同分类方式设计类层次的复杂性和多重继承的优势。最后给出了哺乳动物和鸟类的设计示例,以及能跑、能飞、宠物类和非宠物类的增加对类数量的影响。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
author-avatar
左边我们画圈圈
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有