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的源码注释中看到,原文如下:

 

    

/**
 * 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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值