Spring Security 之 Basic Authentication

       Spring Security实现Basic Authentication

       配置Security文件

   

      

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">

    <security:http auto-config="true">
        <security:http-basic entry-point-ref="basicAuthenticationEntryPoint"/>

        <security:logout invalidate-session="true" logout-url="/logout" logout-success-url="/welcome.jsp"/>

        <security:intercept-url pattern="/welcome.jsp" filters="none"/>
        <security:intercept-url pattern="/*" access="ROLE_ADMIN"/>
    </security:http>

    <bean id="basicAuthenticationEntryPoint"
          class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
        <property name="realmName" value="Voter"/>
    </bean>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="ZhongGang" authorities="ROLE_ADMIN" password="123"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

   

    这里为了简便,专注于Basic Authentication,这里使用的用户是通过配置文件配置的方式, 用户最终是放置在内存中的。

     这里有一点需要特别注意,通过Basic Authentication登录的方式,如果用户想要退出, 要么关闭浏览器,要么就需要在退出时向客户端发送一个HttpServletResponse.SC_UNAUTHORIZED 401错误才可以实现用户的退出功能。这点可以在BasicAuthenticationEntryPoint的源码注释中看到,原文如下:

    

扫描二维码关注公众号,回复: 776020 查看本文章
/**
 * Used by the <code>ExceptionTraslationFilter</code> to commence authentication via the {@link BasicAuthenticationFilter}.
 * <p>
 * Once a user agent is authenticated using BASIC authentication, logout requires that
 * the browser be closed or an unauthorized (401) header be sent. The simplest way of achieving the latter is to call
 * the {@link #commence(HttpServletRequest, HttpServletResponse, AuthenticationException)} method below. This will indicate to
 * the browser its credentials are no longer authorized, causing it to prompt the user to login again.
 *
 * @author Ben Alex
 */

  

    与Basic Authentication主要相关的两个类是BasicAuthenticationFilter 和 BasicAuthenticationEntryPoint, BasicAuthenticationEntryPoint负责当用户访问一个需要授权的链接时,如果当前没有登录, 向用户展示BasicAuthenticationForm认证表单, BasicAuthenticationFilter负责处理用户的认证请求。

    当用户登录成功后, 访问任意链接地址时, 都可以发现在请求头中包括Authorization这个属性, 里面的加密字符串就是用户名:密码的加密后的字符串,加密方式是Base64。

猜你喜欢

转载自dreamzhong.iteye.com/blog/1759450