HTTP基础认证(BA)是一种简单的认证机制。当一个web客户端需要保护任何web资源的时候,服务器会发送一个带有401状态码(未授权)的HTTP回应,还有类似WWW-Authenticate: Basic realm="realm here" 的 WWW-Authenticate HTTP头。而浏览器这时候就会弹出一个登录对话框,提示输入用户名和密码。
这个示例展示了如何使用Spring Security框架配置HTTP基础认证。
在这篇文章中使用到的工具和技术有:
- Spring Framework 3.1.4
- Spring Security 3.1.4
- Spring Tool Suite 3.2
- JDK 1.6
- Tomcat 7
我们将修改我们前面发布的Spring Security 3 Hello World 示例,为其加入配置HTTP 基础认证的内容。
注意:HTTP基础认证并不是一个安全的用户认证方法,要是Web客户端和服务器之间的链接不安全的话。在传输的过程中,用户的认证凭据是用BASE64编码的,但没有采取加密或者散列化措施。因此如果凭据存在被截获的可能,那么绕过HTTPS的基础认证也能够被使用。
1. 修改Spring Security 配置
在Spring Security xml配置文件中,仅仅添加<http-basic/> 就可配置HTTP基本认证。 File : WEB-INF/spring-security.xml
01 |
< beans:beans xmlns = "http://www./schema/security" |
02 |
xmlns:beans = "http://www./schema/beans" xmlns:xsi = "http://www./2001/XMLSchema-instance" |
03 |
xsi:schemaLocation="http://www./schema/beans |
04 |
http://www./schema/beans/spring-beans-3.2.xsd |
05 |
http://www./schema/security |
06 |
http://www./schema/security/spring-security-3.1.xsd"> |
09 |
< intercept-url pattern = "/secured/*" access = "ROLE_USER" /> |
11 |
<!-- Adds Support for basic authentication --> |
15 |
< authentication-manager > |
16 |
< authentication-provider > |
18 |
< user name = "srccodes" password = "password" authorities = "ROLE_USER" /> |
20 |
</ authentication-provider > |
21 |
</ authentication-manager > |
2. 总体工程结构
3. 演示
启动服务端并部署web应用。尝试打开页面http://:/spring-security-http-basic-authentication/secured/mypage. HTTP Response Header sent by the server
1 |
HTTP/1.1 401 Unauthorized |
2 |
Server: Apache-Coyote/1.1 |
3 |
WWW-Authenticate: Basic realm= "Spring Security Application" |
4 |
Content-Type: text/html;charset=utf-8 |
6 |
Date: Mon, 09 Sep 2013 10:47:14 GMT | 浏览器会打开认证对话框提示输入用户名和密码。
对于错误的凭证,下面的认证失败的消息也会显示出来。
输入正确的用户名和密码,你可以访问受保护的页面。
发送给服务器的HTTP 请求头部
01 |
GET /spring-security-http-basic-authentication/secured/mypage HTTP/1.1 |
03 |
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0 |
04 |
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 |
05 |
Accept-Language: en-US,en;q=0.5 |
06 |
Accept-Encoding: gzip , deflate |
08 |
Connection: keep-alive |
09 |
Cookie: JSESSIONID=896331E26095C95449516FCBF2E0E93C; __atuvc=28%7C31%2C0%7C32%2C0%7C33%2C215%7C34%2C59%7C35 |
10 |
Authorization: Basic c3JjY29kZXM6cGFzc3dvcmQ= |
注意: 'c3JjY29kZXM6cGFzc3dvcmQ=' 是 'username:password'的BASE64的编码的版本。即 'srccodes:password'.
注意: 基本认证不提供登出功能。关闭浏览器就是登出。
下载源代码
spring-security-http-basic-authentication: GitHub or zip
|