首页 > 代码库 > Spring Security应用开发(04)HTTP basic认证

Spring Security应用开发(04)HTTP basic认证

Spring Security默认是使用form-login表单认证方式。

 <!-- 默认使用表单认证 -->

 <sec:form-login />

 

Spring Security还提供了HTTP basic认证的配置的方式,只要在http标签中使用空的http-basic标签即可启用HTTP basic认证方式。

 

<!-- 角色和URL模式的对应关系 -->

 <sec:http auto-config="true" use-expressions="true">

 <sec:intercept-url pattern="/admin/**" access="hasRole(‘ROLE_ADMIN‘)" />

 <sec:intercept-url pattern="/user/**" access="hasRole(‘ROLE_USER‘)" />

 <sec:intercept-url pattern="/home/**" access="hasRole(‘ROLE_USER‘) or hasRole(‘ROLE_ADMIN‘)" />

 

 <!-- 使用HTTP basic认证 -->

 <sec:http-basic />

 

 

在需要登录时,浏览器会打开HTTP basic认证对话框。

 技术分享

 

其中服务器提示后面的文字Spring Security Application”是Spring Security默认给出的realm(领域)信息,可以在http-basic标签中通过配置entry-point-ref属性来指定。

 

 

<sec:http-basic  

  entry-point-ref="basicAuthenticationEntryPoint"

 />

 

 

需要增加一个bean然后指定名字为realmName的属性的值为想要显示的文字。

 <beans:bean

 id="basicAuthenticationEntryPoint"   class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">

   <beans:property name="realmName" value="http basic authentication by coe2coe@qq.com" />

 </beans:bean>

 

 

访问一个需要登录的页面/home,则浏览器出现如下登录画面:

 技术分享

 

 

发起请求后,会收到一个WWW-Authenticate的头信息。响应数据如下:

HTTP/1.1 401

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

Pragma: no-cache

Expires: 0

X-XSS-Protection: 1; mode=block

X-Frame-Options: DENY

X-Content-Type-Options: nosniff

Set-Cookie: JSESSIONID=E7BEB2393FB9910DFD5D4D82728AF4EB;path=/SpringSecurity;HttpOnly

WWW-Authenticate: Basic realm="http basic authentication by coe2coe@qq.com"

Content-Type: text/html;charset=utf-8

Content-Language: en

Content-Length: 1110

Date: Sat, 06 May 2017 15:46:02 GMT

 

在看到401状态码和WWW-Authenticate头信息后,浏览器出现登录画面。

如果在浏览器给出的身份认证画面中输入错误的用户名和密码, 则会继续要求输入正确的用户名和密码。

如果取消登录,则会跳转到认证失败页面。

技术分享 

 

取消登录后,请求和响应数据如下:

请求:

GET /SpringSecurity/home/ HTTP/1.1

Host: localhost:8080

Connection: keep-alive

Pragma: no-cache

Cache-Control: no-cache

Authorization: Basic emhhbmdzYW46MTIzNA==

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Upgrade-Insecure-Requests: 1

User-Agent: Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36

Referer: http://localhost:8080/SpringSecurity/

Accept-Encoding: gzip, deflate, sdch

Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

Cookie: JSESSIONID=BBC492A01845324E6B28DC1CCE77CCF7

 

响应:

HTTP/1.1 401 OK

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

Pragma: no-cache

Expires: 0

X-XSS-Protection: 1; mode=block

X-Frame-Options: DENY

X-Content-Type-Options: nosniff

WWW-Authenticate: Basic realm="http basic authentication by coe2coe@qq.com"

Content-Type: text/html;charset=utf-8

Content-Language: en

Content-Length: 1030

Date: Sat, 06 May 2017 14:45:12 GMT

 

 

在登录成功后,则需要关闭浏览器才能退出登录。

Spring Security应用开发(04)HTTP basic认证