欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Security的使用

程序员文章站 2024-03-19 14:48:04
...

一.Spring Security简介

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

二.Spring Security的使用步骤(固定用户名和密码)

1.在maven中引入spring security坐标
<!-- 引入springSecrity依赖 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>4.1.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.1.0.RELEASE</version>
</dependency>
2.在web.xml中配置spring security拦截器

注意事项 : 过滤器的名称是固定的,不可改变,否则spring找不到

<!-- 配置spring Security -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-security.xml</param-value>
     </context-param>
     <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
     </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
3.在spring配置中配置
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">

    <!-- 配置放行路径 -->
    <http pattern="/*.html" security="none"></http><!-- login.html在根目录下 -->
    <http pattern="/css/**" security="none"></http>
    <http pattern="/img/**" security="none"></http>
    <http pattern="/js/**" security="none"></http>
    <http pattern="/plugins/**" security="none"></http>

    <!-- 配置页面拦截规则 -->
    <http use-expressions="false">
        <!-- 
            /**: 拦截所有?
            access : 配置角色 必须要以ROLE_开头
         -->
        <intercept-url pattern="/**" access="ROLE_ADMIN"/>
        <!-- 
            开启表单登陆功能(默认 username password) 表单action:/login
            login-page:登陆页面
            default-target-url:登陆成功页面
            authentication-failure-url:登陆失败跳转页面
            always-use-default-target:总是跳转到默认的成功页面
         -->
        <form-login login-page="/login.html" default-target-url="/admin/index.html" authentication-failure-url="/login.html" always-use-default-target="true"/>
        <!-- 关闭跨站请求伪造检测 -->
        <csrf disabled="true"/>
        <!-- 关闭对框架页的拦截 -->
        <headers>
            <frame-options policy="SAMEORIGIN"/>
        </headers>
    </http>

    <!-- 配置安全管理器 -->
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="admin" authorities="ROLE_ADMIN"/>
                <user name="root" password="root" authorities="ROLE_ADMIN"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

三.Spring Security的使用步骤(从数据库中查询用户名和密码)

1.和上述不同点
步骤一:创建UserDetailsServiceImpl实现org.springframework.security.core.userdetails.UserDetailsService接口
import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.pinyougou.pojo.TbSeller;
import com.pinyougou.sellergoods.service.SellerService;

/**
 * 商家认证类
 * 
 * @author Administrator
 *
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    private SellerService sellerService;

    public void setSellerService(SellerService sellerService) {
        this.sellerService = sellerService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户
        TbSeller tbSeller = sellerService.findOne(username);
        // 查询到,判断状态是否审核通过
        if (tbSeller != null) {
            // 审核通过,返会结果(0:正在审核,1:已审核,2:审核未通过,3:关闭)
            if ("1".equals(tbSeller.getStatus())) {
                List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                authorities.add(new SimpleGrantedAuthority("ROLE_SELLER"));
                return new User(username, tbSeller.getPassword(), authorities);
            } else {
                // 审核未通过
                return null;
            }
        } else {
            // 没有查询到,返回null
            return null;
        }

    }

}
步骤二:配置spring security的配置文件

遇到问题:因为在UserDetailsServiceImpl类中注入了SellerService,但是SellerService是使用dubbo远程调用的
解决: 需要注入SellerService的话需要配置

    <!-- 引用dubbo 服务 --> 
    <dubbo:application name="pinyougou-shop-web" />
    <dubbo:registry address="zookeeper://192.168.25.128:2181"/>
    <dubbo:reference id="sellerService" interface="com.pinyougou.sellergoods.service.SellerService"/>

Spring Security配置文件 :

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

    <!-- 配置放行路径 -->
    <http pattern="/*.html" security="none"></http><!-- login.html在根目录下 -->
    <http pattern="/css/**" security="none"></http>
    <http pattern="/img/**" security="none"></http>
    <http pattern="/js/**" security="none"></http>
    <http pattern="/plugins/**" security="none"></http>
    <!-- 放行商家入驻 -->
    <http pattern="/seller/add.do" security="none"></http>

    <!-- 配置页面拦截规则 -->
    <http use-expressions="false">
        <intercept-url pattern="/**" access="ROLE_SELLER"/>
        <form-login login-page="/shoplogin.html" default-target-url="/admin/index.html" authentication-failure-url="/shoplogin.html" always-use-default-target="true"/>
        <!-- 关闭跨站请求伪造检测 -->
        <csrf disabled="true"/>
        <!-- 关闭对框架页的拦截 -->
        <headers>
            <frame-options policy="SAMEORIGIN"/>
        </headers>
        <!-- 开启用户退出 默认访问地址: /logout -->
        <logout/>
    </http>

    <!-- 配置安全管理器 -->
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
        </authentication-provider>
    </authentication-manager>

    <!-- 配置认证类 -->
    <beans:bean id="userDetailsService" class="com.pinyougou.shop.service.UserDetailsServiceImpl">
        <beans:property name="sellerService" ref="sellerService"/>
    </beans:bean>

    <!-- 引用dubbo 服务 --> 
    <dubbo:application name="pinyougou-shop-web" />
    <dubbo:registry address="zookeeper://192.168.25.128:2181"/>
    <dubbo:reference id="sellerService" interface="com.pinyougou.sellergoods.service.SellerService"/>
</beans:beans>

其他配置大同小异,参考Spring Security的第一种使用方式

相关标签: 安全框架