Spring Security Basic Authentication

来源:互联网 发布:linux kmod oracleasm 编辑:程序博客网 时间:2024/04/27 02:10

原文地址:http://www.javaarch.net/jiagoushi/696.htm

Spring Security Basic Authenticationspring security 配置<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:beans="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <http use-expressions="true"><intercept-url pattern="/**" access="isAuthenticated()" /> <http-basic /></http> <authentication-manager><authentication-provider><user-service><user name="user1" password="user1Pass" authorities="ROLE_USER" /></user-service></authentication-provider></authentication-manager> </beans:beans> <http-basic>打开basic验证,  如果我们访问:curl -i http://localhost:8080/spring-security-basic-auth/homepage.html  会返回401 HTTP/1.1 401 UnauthorizedServer: Apache-Coyote/1.1Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-basic-auth/; HttpOnlyWWW-Authenticate: Basic realm="Spring Security Application"Content-Type: text/html;charset=utf-8Content-Length: 1061Date: Wed, 29 May 2013 15:14:08 GMT如果我们使用下面的url访问:curl -i --user user1:user1Pass http://localhost:8080/spring-security-basic-auth/homepage.html则返回200HTTP/1.1 200 OKServer: Apache-Coyote/1.1Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-basic-auth/; HttpOnlyContent-Type: text/html;charset=ISO-8859-1Content-Language: en-USContent-Length: 90Date: Wed, 29 May 2013 15:19:38 GMT我们也可以使用spring提供的扩展接口来实现验证结果自定义<http-basic entry-point-ref="myBasicAuthenticationEntryPoint" />@Componentpublic class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { @Overridepublic void commence  (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)   throws IOException, ServletException {response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);PrintWriter writer = response.getWriter();writer.println("HTTP Status 401 - " + authEx.getMessage());} @Overridepublic void afterPropertiesSet() throws Exception {setRealmName("Baeldung");super.afterPropertiesSet();}}


原创粉丝点击