主机认证:授权访问的有效方式 (主机的认证方式)

随着网络安全问题日益突出,保障服务器的安全性显得尤为重要。在服务器权限管理中,主机认证是授权访问的有效方式。主机认证可以有效地限制用户对服务器的访问权限,保障服务器的安全性。

什么是主机认证?

主机认证是服务器上的一种安全措施,用于验证用户身份并识别合法用户。主机认证需要用户输入用户名和密码,才能访问需要授权的资源。这种方法可以有效地防止未经授权的访问,进而保障服务器的安全性。

主机认证的类型有哪些?

主机认证通常包括以下几种类型,不同的认证方法适用于不同类型服务器或应用。

1.基于密码的认证

基于密码的认证是主机认证的基础,是最常见的认证方式。用户需要输入正确的用户名和密码才能访问服务器或资源。这种方式在很大程度上保证了服务器的安全性,但是需要用户不定期更改密码,以确保密码不被他人猜测或破解。

2.基于证书的认证

基于证书的认证需要用户生成公钥和私钥,将公钥发送给服务器,服务器将公钥保存在合适的位置进行认证。这种方式是一种更加复杂的认证方式,但是安全性也更高。

3.指纹识别认证

指纹识别认证是用指纹来验证用户身份的主机认证方式。该方式需要相关设备的支持,并且使用和管理起来较为复杂,但对于高安全性的服务器和系统而言,是一种较为理想的认证方式。

4.智能卡认证

智能卡认证需要用户插入智能卡,通过PIN码来验证用户身份。这种方式实现了电子身份认证,对于从事敏感业务或对安全性要求极高的服务器而言,是一种不错的认证方式。

主机认证的优点

1. 提高服务器安全性

主机认证可以限制服务器被未经授权的人员访问,进而保障服务器的安全性。特别是在企业等单位中,重要的数据资料经常存储在服务器中,防止数据泄露和损坏至关重要。

2. 精确定制用户权限

主机认证可以灵活设置用户权限,可以针对不同的用户和不同的资源进行不同的访问控制。这种方法非常适合在公司等组织中,为不同的用户设置不同的权限,以更大程度地保护服务器的安全性。

3. 实现身份认证

主机认证不仅能够限制用户访问服务器,还能够实现身份认证。只有身份得到认证的用户才能访问服务器,有效保证了数据的安全性和机密性。

主机认证的缺点

1. 安全性依赖于密码的复杂性

主机认证的密码安全性很大程度上取决于密码的复杂度。如果用户使用简单的密码,安全性将大大降低。因此,需要用户定期更新密码,增加密码复杂度,提高主机认证的安全性。

2. 管理和维护比较繁琐

主机认证需要安全管理员负责管理和维护,包括创建和修改用户账户、分配和撤销用户权限、密码更新、监控系统日志等,需要耗费大量的时间和精力。

3. 不支持第三方应用

主机认证对第三方应用的支持不足,可能需要对每个应用程序进行独立的设置。这意味着在应用程序不同的服务器上,需要为不同的应用程序设置不同的认证方式。

主机认证是一种有效的安全措施,可以保障服务器的安全性,实现身份认证、精确定制用户权限等功能。然而,主机认证需要合理的管理和维护,需要定期更新密码,确保密码复杂性等,才能起到更好的效果。

相关问题拓展阅读:

以下哪个不属于ssh登陆认证方式

1. 使用 SSH 访问远程命令行

1.1 OpenSSH 简介

1.2 SSH 认证方式

1.3 openSSH 的工作模式

1.4 Secure Shell 示例

1.5 SSH 主机密钥

2. 配置基于 SSH 密钥瞎敬雹的身份验证

3. 自定义 SSH 服务配置

4. SSH 安全注意事项

作业

1. 使用 SSH 访问远程命令行

1.1 OpenSSH 简介

OpenSSH这一术语指系统中使用的Secure Shell软件的软件实施。用于在远程系统上安全运行shell。如果您在可提供ssh服务的远程Linux系统中拥有用户帐户,则ssh是通常用来远程登录到该系统的命令。ssh命令也可用于在远程系统中运行命令。

常见的远程登录工具有:

telnet

ssh

dropbear

telnet //远程登录协议,23/TCP

认证明文

数据传输明文

ssh //Secure SHell,应用层协议,22/TCP

通信过程及认证过程是加密的,主机认证

用户认证过程加密

数据传输过程加密

dropbear //嵌入式系统专用的SSH服务器端和客户端工磨帆具

1.2 SSH 认证方式

openssh有两种认证方式,分别是:

基于口令认证

基于密钥认证

1.3 openSSH 的工作模式

openSSH是基于C/S架构工作的。

服务器端 //sshd,配置文件在/etc/ssh/sshd_config

客户端 //ssh,配置文件在/etc/ssh/ssh_config

ssh-keygen //密钥生成器

ssh-copy-id //将公钥传输至远程服稿塌务器

scp //跨主机安全复制工具

1.4 Secure Shell 示例

//以当前用户身份创建远程交互式shell,然后在结束时使用exit命令返回到之前的shell

# ssh 172.16.12.138

‘s password:

Last login: Tue Jul 10 07:34:from 172.16.12.136

# exit

logout

Connection to 172.16.12.138 closed.

//以其他用户身份(remoteuser)在选定主机(remotehost)上连接到远程`shell`

# ssh

‘s password:

$ exit

logout

Connection to 172.16.12.138 closed.

//以远程用户身份(remoteuser)在远程主机(remotehost)上通过将输出返回到本地显示器的方式来执行单一命令

# ip a s ens332: ens33: mtu 1500 qdisc pfifo_fast state UP qlen 1000

link/ether 00:0c:29:0e:70:22 brd ff:ff:ff:ff:ff:ff

inet 172.16.12.136/24 brd 172.16.12.255 scope global dynamic ens33

valid_lft 1422sec preferred_lft 1422sec

inet6 fe80::20c:29ff:fe0e:7022/64 scope link

valid_lft forever preferred_lft forever

# ssh ‘/usr/in/ip a s ens33’

‘s password:

2: ens33: mtu 1500 qdisc pfifo_fast state UP qlen 1000

link/ether 00:0c:29:f4:5b:87 brd ff:ff:ff:ff:ff:ff

inet 172.16.12.138/24 brd 172.16.12.255 scope global dynamic ens33

valid_lft 1666sec preferred_lft 1666sec

inet6 fe80::20c:29ff:fef4:5b87/64 scope link

valid_lft forever preferred_lft forever

//w命令可以显示当前登录到计算机的用户列表。这对于显示哪些用户使用ssh从哪些远程位置进行了登录以及执行了何种操作等内容特别有用

# w

07:49:18 up 18 min, 2 users, load average: 0.02, 0.02, 0.05

USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT

root pts/0 172.16.12.1 07:31 6.00s 0.02s 0.00s w

user1 pts/1 172.16.12.136 07:49 5.00s 0.00s 0.00s -bash

1.5 SSH 主机密钥

ssh通过公钥加密的方式保持通信安全。当某一ssh客户端连接到ssh服务器时,在该客户端登录之前,服务器会向其发送公钥副本。这可用于为通信渠道设置安全加密,并可验证客户端的服务器。

当用户之一次使用ssh连接到特定服务器时,ssh命令可在用户的~/.ssh/known_hosts文件中存储该服务器的公钥。在此之后每当用户进行连接时,客户端都会通过对比~/.ssh/known_hosts文件中的服务器条目和服务器发送的公钥,确保从服务器获得相同的公钥。如果公钥不匹配,客户端会假定网络通信已遭劫持或服务器已被入侵,并且中断连接。

这意味着,如果服务器的公钥发生更改(由于硬盘出现故障导致公钥丢失,或者出于某些正当理由替换公钥),用户则需要更新其~/.ssh/known_hosts文件并删除旧的条目才能够进行登录。

//主机ID存储在本地客户端系统上的 ~/.ssh/known_hosts 中

# cat ~/.ssh/known_hosts172.16.12.138 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHpBYg+C0GDiBU9mHsy8S3ju31OdfTq6cr6oprIsE/MM8yZdTrRh4gum8IXiVFchUelPD5R9IuTjsy8Eqy8l+Lc=

//主机密钥存储在SSH服务器上的 /etc/ssh/ssh_host_key* 中

# ls /etc/ssh/*key*

/etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_ed25519_key.pub

/etc/ssh/ssh_host_ecdsa_key.pub /etc/ssh/ssh_host_rsa_key

/etc/ssh/ssh_host_ed25519_key /etc/ssh/ssh_host_rsa_key.pub

2. 配置基于 SSH 密钥的身份验证

用户可通过使用公钥身份验证进行ssh登录身份验证。ssh允许用户使用私钥-公钥方案进行身份验证。这意味着将生成私钥和公钥这两个密钥。私钥文件用作身份验证凭据,像密码一样,必须妥善保管。公钥复制到用户希望登录的系统,用于验证私钥。公钥并不需要保密。拥有公钥的ssh服务器可以发布仅持有您私钥的系统才可解答的问题。因此,可以根据所持有的密钥进行验证。如此一来,就不必在每次访问系统时键入密码,但安全性仍能得到保证。

使用ssh-keygen命令生成密码。将会生成私钥~/.ssh/id_rsa和公钥~/.ssh/id_rsa.pub。

注意:

生成密钥时,系统将提供指定密码的选项,在访问私钥时必须提供该密码。如果私钥被偷,除颁发者之外的其他任何人很难使用该私钥,因为已使用密码对其进行保护。这样,在攻击者破解并使用私钥前,会有足够的时间生成新的密钥对并删除所有涉及旧密钥的内容。

生成ssh密钥后,密钥将默认存储在家目录下的.ssh/目录中。私钥和公钥的权限就分别为600和644。.ssh目录权限必须是700。

在可以使用基于密钥的身份验证前,需要将公钥复制到目标系统上。可以使用ssh-copy-id完成这一操作

# ssh-copy-id remoteuser@remotehost

通过ssh-copy-id将密钥复制到另一系统时,它默认复制~/.ssh/id_rsa.pub文件

//SSH密钥演示//使用 ssh-keygen 创建公钥-私钥对

# ssh-keygen -t rsa

Generating public/private rsa key pair.

Enter file in which to save the key (/root/.ssh/id_rsa):

Created directory ‘/root/.ssh’.

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /root/.ssh/id_rsa.

Your public key has been saved in /root/.ssh/id_rsa.pub.

The key fingerprint is:

SHA256:8VyY3c3UEQvk1Pn95tYIF7sx9enlwG78hDjlX0entN0

The key’s randomart image is:

+——-+

| .+.o*|

| +o..*o|

| . o o…=|

| + . . +|

| S o .o+*|

| .=BBB|

| o=*XE|

| .*+B|

| . oo|

+———+

//使用 ssh-copy-id 将公钥复制到远程系统上的正确位置

# ls .ssh/

id_rsa id_rsa.pub

# ssh-copy-id -i ~/.ssh/id_rsa.pub

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”

The authenticity of host ‘172.16.12.138 (172.16.12.138)’ can’t be established.

ECDSA key fingerprint is SHA256:JK5WwrX8hynl3dyWO43e6+lcs6zn9oZn74z1H5X8F90.

ECDSA key fingerprint is MD5:01:4f:4f:4b:0e:45:a9:10:bb:d0:c0:dd:19:9a:9f:96.

Are you sure you want to continue connecting (yes/no)? yes

/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys

‘s password:

Number of key(s) added: 1

Now try logging into the machine, with: “ssh ‘”and check to make sure that only the key(s) you wanted were added.

//使用 ssh 命令无命令登录远程主机

# ssh

Last login: Tue Jul 10 18:37:from 172.16.12.1

# ip a s ens332: ens33: mtu 1500 qdisc pfifo_fast state UP qlen 1000

link/ether 00:0c:29:f4:5b:87 brd ff:ff:ff:ff:ff:ff

inet 172.16.12.138/24 brd 172.16.12.255 scope global dynamic ens33

valid_lft 1377sec preferred_lft 1377sec

inet6 fe80::20c:29ff:fef4:5b87/64 scope link

valid_lft forever preferred_lft forever

//使用 scp 命令传送文件到远程主机

# scp test.sh :/tmp

‘s password:

test.sh 100% 45 29.8KB/s 00:00

//使用 scp 命令从远程主机上下载文件到本地

# ls

a anaconda-ks.cfg b nginx-1.12.2 nginx-1.12.2.tar.gz nohup.out outfile test.sh

# rm -f test.sh

# ls

a anaconda-ks.cfg b nginx-1.12.2 nginx-1.12.2.tar.gz nohup.out outfile

# scp :/tmp/test.sh .

‘s password:

test.sh 100% 45 39.1KB/s 00:00

# ls

a anaconda-ks.cfg b nginx-1.12.2 nginx-1.12.2.tar.gz nohup.out outfile test.sh

//scp命令常用选项

-r //递归复制

-p //保持权限

-P //端口

-q //静默模式

-a //全部复制

3. 自定义 SSH 服务配置

虽然OpenSSH服务器通常无需修改,但会提供其他安全措施,可以在配置文件/etc/ssh/sshd_config中修改OpenSSH服务器的各个方面。

PermitRootLogin {yes|no} //是否允许root用户远程登录系统

PermitRootLogin without-password //仅允许root用户基于密钥方式远程登录

PasswordAuthentication {yes|no} //是否启用密码身份验证,默认开启

4. SSH 安全注意事项

密码应该经常换且足够复杂

# tr -dc A-Za-z0-9_

H9cbirdT6E_hbColMFjZNf9Kd6If

# openssl rand 20 -base64

Di9ry+dyV40xVvBHirsc3XpBOzg= //生成20位随机密码

使用非默认端口

限制登录客户端地址

仅监听特定的IP地址

禁止管理员直接登录

仅允许有限制用户登录

AllowUsers

AllowGroups

使用基于密钥的认证

禁止使用空密码

禁止使用SSHv1版本

设定空闲会话超时时长

利用防火墙设置ssh访问策略

限制ssh的访问频度和并发在线数

做好日志的备份,经常分析(集中于某台服务器)

如何使用HttpClient认证机制

1.服务器认证(Server Authentication)

HttpClient处理服务器认证几乎是透明的,仅需要开发人员提供登录信息(login credentials)。登录信息保存在HttpState类的实例中,可以丛裂通过 setCredentials(String realm, Credentials cred)和getCredentials(String realm)来获取或设置。

HttpClient内建的自动认证,可以通过HttpMethod类的setDoAuthentication(boolean doAuthentication)方派郑肆法关闭,而且这次关闭只影响HttpMethod当前的实例。

2.代理认证(proxy authentication)

  除了登录信息需单独存放以外,代理认证与服务器认证几乎一致。用 setProxyCredentials(String realm, Credentials cred)和 getProxyCredentials(String realm)设、取登录信息。

3.认证方案(authentication schemes)

是HTTP中规定最早的也是最兼容的方案,遗憾的尘轿是也是最不安全的一个方案,因为它以明码传送用户名和密码。它要求一个UsernamePasswordCredentials实例,可以指定服务器端的访问空间或采用默认的登录信息。

本文出自 “子 孑” 博客,请务必保留此出处

英文版(无代码示例):

HttpClient三种不同的认证方案: Basic, Digest and NTLM. 这些方案可用于服务器或代理对客户端的认证,简称服务器认证或代理认证。

1.服务器认证(Server Authentication)

HttpClient处理服务器认证几乎是透明的,仅需要开发人员提供登录信息(login credentials)。登录信息保存在HttpState类的实例中,可以通过 setCredentials(String realm, Credentials cred)和getCredentials(String realm)来获取或设置。

HttpClient内建的自动认证,可以通过HttpMethod类的setDoAuthentication(boolean doAuthentication)方法关闭,而且这次关闭只影响HttpMethod当前的实例。

1.1抢先认证(Preemptive Authentication)

在这种模式时,HttpClient会主动将basic认证应答信息传给服务器,即使在某种情况下服务器可能返回认证失败的应答,这样做主要是为了减少连接的建立。使用该机制如下所示:

client.getParams().setAuthenticationPreemptive(true);

抢先腔键认证模式也提供对于特定目标或代理的缺省认证。如果没有提供缺省的伍世巧认证信息,则该模式会失效。

Credentials defaultcreds = new UsernamePasswordCredentials(“username”, “password”);

client.getState().setCredentials(new AuthScope(“myhost”, 80, AuthScope.ANY_REALM), defaultcreds);

Httpclient实现的抢先认证遵循rfc2617.

A client SHOULD assume that all paths at or deeper than the depth of the last symbolic element in the path field of the Request-URI also are within the protection space specified by the Basic realm value of the current challenge. A client MAY preemptively send the corresponding Authorization header with requests for resources in that space without receipt of another challenge from the server. Similarly, when a client sends a request to a proxy, it may reuse a userid and password in the Proxy-Authorization header field without receiving another challenge from the proxy server.

1.2服务器认证的安全方面考虑

当需要与不被信任的站点或web应用通信时,应该谨慎使用缺省的认证机制返贺。当启动(activate)抢先认证模式,或者认证中没有明确给出认证域,主机的HttpClient将使用缺省的认证机制去试图获得目标站点的授权。

如果你提供的认证信息是敏感的,你应该指定认证域。不推荐将认证域指定为AuthScope.ANY。(只有在debugging情况下,才使用)

// To be avoided unless in debug mode

Credentials defaultcreds = new UsernamePasswordCredentials(“username”, “password”);

client.getState().setCredentials(AuthScope.ANY, defaultcreds);

2.代理认证(proxy authentication)

  除了登录信息需单独存放以外,代理认证与服务器认证几乎一致。用 setProxyCredentials(String realm, Credentials cred)和 getProxyCredentials(String realm)设、取登录信息。

3.认证方案(authentication schemes)

3.1Basic

是HTTP中规定最早的也是最兼容的方案,遗憾的是也是最不安全的一个方案,因为它以明码传送用户名和密码。它要求一个UsernamePasswordCredentials实例,可以指定服务器端的访问空间或采用默认的登录信息。

3.2 Digest

是在HTTP1.1 中增加的一个方案,虽然不如Basic得到的软件支持多,但还是有广泛的使用。Digest方案比Basic方案安全得多,因它根本就不通过网络传送实际的密码,传送的是利用这个密码对从服务器传来的一个随机数(nonce)的加密串。

它要求一个UsernamePasswordCredentials实例,可以指定服务器端的访问空间或采用默认的登录信息。

3.3 NTLM

这是HttpClient支持的最复杂的认证协议。它Microsoft设计的一个私有协议,没有公开的规范说明。一开始由于设计的缺陷,NTLM的安全性比 Digest差,后来经过一个ServicePack补丁后,安全性则比较Digest高。

NTLM需要一个NTCredentials实例。 注意,由于NTLM不使用访问空间(realms)的概念,HttpClient利用服务器的域名作访问空间的名字。还需要注意,提供给 NTCredentials的用户名,不要用域名的前缀 – 如: “adrian” 是正确的,而 “DOMAIN\adrian” 则是错的。

NTLM认证的工作机制与basic和digest有很大的差别。这些差别一般由HttpClient处理,但理解这些差别有助避免在使用NTLM认证时出现错误。

从HttpClientAPI的角度来看,NTLM与其它认证方式一样的工作,差别是需要提供’NTCredentials’实例而不是’UsernamePasswordCredentials'(其实,前者只是扩展了后者)

对NTLM认证,访问空间是连接到的机器的域名,这对多域名主机会有一些麻烦。只有HttpClient连接中指定的域名才是认证用的域名。建议将realm设为null以使用默认的设置。

NTLM只是认证了一个连接而不是一请求,所以每当一个新的连接建立就要进行一次认证,且在认证的过程中保持连接是非常重要的。 因此,NTLM不能同时用于代理认证和服务器认证,也不能用于HTTP1.0连接或服务器不支持持久连接(keep-alives)的情况。

关于NTLM认证机制更详细的研究,可参考

3.4选择认证

一些服务器支持多种认证方案。假设一次只能使用一种认证方案,HttpClient必须选择使用哪种。HttpClient选择是基于NTLM, Digest, Basic顺序的。

在具体情况下,可以更改该顺序。可通过参数’http.auth.scheme-priority’来实现,该参数值应该被存放在一个String类型的List中。选择优先级是按插入顺序确定的。

HttpClient client = new HttpClient();

List authPrefs = new ArrayList(2);

authPrefs.add(AuthPolicy.DIGEST);

authPrefs.add(AuthPolicy.BASIC);

// This will exclude the NTLM authentication scheme

client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

3.5定制认证方案

HttpClient本身支持basic, digest, and NTLM这三种认证方案。同时,它也提供了加载额外定制的认证方案的功能(通过AuthScheme接口实现)。需要使用定制的认证方案,必须实现下面的步骤:

实现AuthScheme接口。

通过AuthPolicy.registerAuthScheme() 注册定制的AuthScheme。

将定制的AuthScheme加入到AuthPolicy.AUTH_SCHEME_PRIORITY中。

4.示例

4.1Basic authentication

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.UsernamePasswordCredentials;

import org.apache.commons.httpclient.auth.AuthScope;

import org.apache.commons.httpclient.methods.GetMethod;

/**

* A simple example that uses HttpClient to perform a GET using Basic

* Authentication. Can be run standalone without parameters.

*

* You need to have SE on your classpath for JDK prior to 1.4

*

* @author Michael Becke

*/

public class BasicAuthenticationExample {

/**

* Constructor for BasicAuthenticatonExample.

*/

public BasicAuthenticationExample() {

super();

}

public static void main(String args) throws Exception {

HttpClient client = new HttpClient();

// pass our credentials to HttpClient, they will only be used for

// authenticating to servers with realm “realm” on the host

// “

www.verisign.com

“, to authenticate against

// an arbitrary realm or host change the appropriate argument to null.

client.getState().setCredentials(

new AuthScope(“

www.verisign.com

“, 443, “realm”),

new UsernamePasswordCredentials(“username”, “password”)

);

// create a GET method that reads a file over HTTPS, we’re assuming

// that this file requires basic authentication using the realm above.

GetMethod get = new GetMethod(“

www.verisign.com

/products/index.html”);

// Tell the GET method to automatically handle authentication. The

// method will use any appropriate credentials to handle basic

// authentication requests. Setting this value to false will cause

// any request for authentication to return with a status of 401.

// It will then be up to the client to handle the authentication.

get.setDoAuthentication( true );

try {

// execute the GET

int status = client.executeMethod( get );

// print the status and response

System.out.println(status + “\n” + get.getResponseBodyAsString());

} finally {

// release any connection resources used by the method

get.releaseConnection();

}

}

}

4.2 Alternate authentication

import java.util.ArrayList;

import java.util.List;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.UsernamePasswordCredentials;

import org.apache.commons.httpclient.auth.AuthPolicy;

import org.apache.commons.httpclient.auth.AuthScope;

import org.apache.commons.httpclient.methods.GetMethod;

/**

* A simple example that uses alternate authentication scheme selection

* if several authentication challenges are returned.

*

*

* Per default HttpClient picks the authentication challenge in the following

* order of preference: NTLM, Digest, Basic. In certain cases it may be desirable to

* force the use of a weaker authentication scheme.

*

*

* @author Oleg Kalnichevski

*/

public class AlternateAuthenticationExample {

/**

* Constructor for BasicAuthenticatonExample.

*/

public AlternateAuthenticationExample() {

super();

}

public static void main(String args) throws Exception {

HttpClient client = new HttpClient();

client.getState().setCredentials(

new AuthScope(“myhost”, 80, “myrealm”),

new UsernamePasswordCredentials(“username”, “password”));

// Suppose the site supports several authetication schemes: NTLM and Basic

// Basic authetication is considered inherently insecure. Hence, NTLM authentication

// is used per default

// This is to make HttpClient pick the Basic authentication scheme over NTLM & Digest

List authPrefs = new ArrayList(3);

authPrefs.add(AuthPolicy.BASIC);

authPrefs.add(AuthPolicy.NTLM);

authPrefs.add(AuthPolicy.DIGEST);

client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

GetMethod httpget = new GetMethod(“

“);

try {

int status = client.executeMethod(httpget);

// print the status and response

System.out.println(status);

System.out.println(httpget.getStatusLine());

System.out.println(httpget.getResponseBodyAsString());

} finally {

// release any connection resources used by the method

httpget.releaseConnection();

}

}

}

4.3 Custom authentication

import java.util.ArrayList;

import java.util.Collection;

import org.apache.commons.httpclient.Credentials;

import org.apache.commons.httpclient.HttpMethod;

import org.apache.commons.httpclient.auth.AuthPolicy;

import org.apache.commons.httpclient.auth.AuthScheme;

import org.apache.commons.httpclient.auth.AuthenticationException;

import org.apache.commons.httpclient.auth.MalformedChallengeException;

import org.apache.commons.httpclient.params.DefaultHttpParams;

import org.apache.commons.httpclient.params.HttpParams;

/**

* A simple custom AuthScheme example. The included auth scheme is meant

* for demonstration purposes only. It does not actually implement a usable

* authentication method.

*/

public class CustomAuthenticationExample {

@SuppressWarnings(“unchecked”)

public static void main(String args) {

// register the auth scheme

AuthPolicy.registerAuthScheme(SecretAuthScheme.NAME, SecretAuthScheme.class);

// include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference,

// this can be done on a per-client or per-method basis but we’ll do it

// globally for this example

HttpParams params = DefaultHttpParams.getDefaultParams();

ArrayList schemes = new ArrayList();

schemes.add(SecretAuthScheme.NAME);

schemes.addAll( (Collection) params.getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY));

params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);

// now that our scheme has been registered we can execute methods against

// servers that require “Secret” authentication…

}

/**

* A custom auth scheme that just uses “Open Sesame” as the authentication

* string.

*/

private class SecretAuthScheme implements AuthScheme {

public static final String NAME = “Secret”;

public SecretAuthScheme() {

// All auth schemes must have a no arg constructor.

}

public String authenticate(Credentials credentials, HttpMethod method)

throws AuthenticationException {

return “Open Sesame”;

}

public String authenticate(Credentials credentials, String method,

String uri) throws AuthenticationException {

return “Open Sesame”;

}

public String getID() {

return NAME;

}

public String getParameter(String name) {

// this scheme does not use parameters, see RFC2617Scheme for an example

return null;

}

public String getRealm() {

// this scheme does not use realms

return null;

}

public String getSchemeName() {

return NAME;

}

public boolean isConnectionBased() {

return false;

}

public void processChallenge(String challenge)

throws MalformedChallengeException {

// Nothing to do here, this is not a challenge based

// auth scheme. See NTLMScheme for a good example.

}

public boolean isComplete() {

// again we’re not a challenge based scheme so this is always true

return true;

}

}

}

4.4 Interactive authentication

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import org.apache.commons.httpclient.Credentials;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.NTCredentials;

import org.apache.commons.httpclient.UsernamePasswordCredentials;

import org.apache.commons.httpclient.auth.AuthScheme;

import org.apache.commons.httpclient.auth.CredentialsNotAvailableException;

import org.apache.commons.httpclient.auth.CredentialsProvider;

import org.apache.commons.httpclient.auth.NTLMScheme;

import org.apache.commons.httpclient.auth.RFC2617Scheme;

import org.apache.commons.httpclient.methods.GetMethod;

/**

* A simple example that uses HttpClient to perform interactive

* authentication.

*

* @author Oleg Kalnichevski

*/

public class InteractiveAuthenticationExample {

/**

* Constructor for InteractiveAuthenticationExample.

*/

public InteractiveAuthenticationExample() {

super();

}

public static void main(String args) throws Exception {

InteractiveAuthenticationExample demo = new InteractiveAuthenticationExample();

demo.doDemo();

}

private void doDemo() throws IOException {

HttpClient client = new HttpClient();

client.getParams().setParameter(

CredentialsProvider.PROVIDER, new ConsoleAuthPrompter());

GetMethod httpget = new GetMethod(“

“);

httpget.setDoAuthentication(true);

try {

// execute the GET

int status = client.executeMethod(httpget);

// print the status and response

System.out.println(status);

System.out.println(httpget.getStatusLine().toString());

System.out.println(httpget.getResponseBodyAsString());

} finally {

// release any connection resources used by the method

httpget.releaseConnection();

}

}

public class ConsoleAuthPrompter implements CredentialsProvider {

private BufferedReader in = null;

public ConsoleAuthPrompter() {

super();

this.in = new BufferedReader(new InputStreamReader(System.in));

}

private String readConsole() throws IOException {

return this.in.readLine();

}

public Credentials getCredentials(

final AuthScheme authscheme,

final String host,

int port,

boolean proxy)

throws CredentialsNotAvailableException

{

if (authscheme == null) {

return null;

}

try{

if (authscheme instanceof NTLMScheme) {

System.out.println(host + “:” + port + ” requires Windows authentication”);

System.out.print(“Enter domain: “);

String domain = readConsole();

System.out.print(“Enter username: “);

String user = readConsole();

System.out.print(“Enter password: “);

String password = readConsole();

return new NTCredentials(user, password, host, domain);

} else

if (authscheme instanceof RFC2617Scheme) {

System.out.println(host + “:” + port + ” requires authentication with the realm ‘”

+ authscheme.getRealm() + “‘”);

System.out.print(“Enter username: “);

String user = readConsole();

System.out.print(“Enter password: “);

String password = readConsole();

return new UsernamePasswordCredentials(user, password);

} else {

throw new CredentialsNotAvailableException(“Unsupported authentication scheme: ” +

authscheme.getSchemeName());

}

} catch (IOException e) {

throw new CredentialsNotAvailableException(e.getMessage(), e);

}

}

}

主机的认证方式的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于主机的认证方式,主机认证:授权访问的有效方式,以下哪个不属于ssh登陆认证方式,如何使用HttpClient认证机制的信息别忘了在本站进行查找喔。


数据运维技术 » 主机认证:授权访问的有效方式 (主机的认证方式)