SpringSecurity

本文介绍了SpringSecurity框架的基本概念,并详细讲述了如何在项目中配置SpringSecurity进行权限控制,包括加入依赖、配置过滤器链、创建配置类等步骤。在实际操作中遇到的`springSecurityFilterChain`找不到bean的问题,通过分析Web组件加载顺序和Spring IOC容器的关系,找到了问题根源在于ContextLoaderListener的IOC容器未扫描SpringSecurity配置。解决方案是让DispatcherServlet负责读取Spring配置,从而解决异常。

springSecurityFilterChain 找不到异常

1、SpringSecurity 框架简介

在这里插入图片描述

用户登录系统时我们协助 SpringSecurity把用户对应的角色、权限组装好,同时把各个 ​
资源所要求的权限信息设定好,剩下的“登录验证”、“权限验证”等等工作都交给SpringSecurity

2、在项目中加入SpringSecurity权限控制

在这里插入图片描述

2.1、加入依赖

2.1.1、建议在父工程的pom.xml文件中对子工程的jar包版本统一管理
        <!-- 统一管理jar包版本 -->
        <properties>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.security.version>5.0.1.RELEASE</spring.security.version>
        </properties>
        
        <!-- 锁定jar包版本 ${spring.security.version}引用前面统一的版本-->
        <dependencyManagement>
            <dependencies>
               <dependency>
                    <groupId>org.springframework.security</groupId>
                    <artifactId>spring-security-web</artifactId>
                    <version>${spring.security.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework.security</groupId>
                    <artifactId>spring-security-config</artifactId>
                    <version>${spring.security.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework.security</groupId>
                    <artifactId>spring-security-core</artifactId>
                    <version>${spring.security.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework.security</groupId>
                    <artifactId>spring-security-taglibs</artifactId>
                    <version>${spring.security.version}</version>
                </dependency>
            </dependencies>
        </dependencyManagement>
2.1.2、子工程不填jar包版本会向上引用父工程的版本
        <!-- SpringSecurityWeb 应用进行权限管理 -->
        <dependencies>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
            </dependency>
            <!-- SpringSecurity 配置 -->
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
            </dependency>
            <!-- SpringSecurity 标签库 -->
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-taglibs</artifactId>
            </dependency>
        </dependencies>

2.2、在web.xml文件中添加springSecurity的过滤器链

        <!--springSecurity过滤链 在spring ioc容器后初始化 在spring MVC容器前初始化-->
        <?xml version="1.0" encoding="UTF-8"?>
        <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
                 version="4.0">
        <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>
        </web-app>

2.3、创建配置类

// 注意!这个类一定要放在自动扫描的包下(springmvc注解扫描),否则所有配置都不会生效!

/**
 * // @Configuration 将当前类标记为配置类
 * // @EnableWebSecurity 启用Web环境下权限控制功能
 * // @EnableGlobalMethodSecurity(prePostEnabled=true)启用全局方法权限管理功能
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter{
}

2.4、扫描web层的包建议配置 springmvc配置文件

<!--开启注解扫描 include-filter表示扫描 exclude-filter表示不扫描-->
<context:component-scan base-package="cn.tt">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>

3、遇到的问题 多个 IOC 容器之间的关系

3.1、问题描述:

项目启动时控制台抛异常说找不到“springSecurityFilterChain”的 bean

在这里插入图片描述

3.2、问题分析:

Web 组件加载顺序:Listener→Filter→Servlet

Spring IOC 容器:ContextLoaderListener 创建

SpringMVC IOC 容器:DispatcherServlet 创建
SpringSecurityFilterChain:从 IOC 容器中找到对应的 bean

ContextLoaderListener 初始化后,springSecurityFilterChain 就在ContextLoaderListener 创建的 IOC 容器中查找所需要的 bean,但是我们没有在ContextLoaderListener 的 IOC 容 器中扫描 SpringSecurity 的配置类,所以springSecurityFilterChain 对应的 bean 找不到

在这里插入图片描述

3.3、问题解决:

将 ContextLoaderListener 取消,原本由 ContextLoaderListener 读取的 Spring配置文件交给 DispatcherServlet 负责读取

    <!-- 注释掉让springmvc的ioc容器读取Spring配置文件  配置Spring的监听器,默认只加载WEB-INF目录下的      applicationContext.xml配置文件
     <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
     <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:applicationContext.xml</param-value>
     </context-param>  -->

    <!--前端控制器 spring mvc的ioc容器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载springmvc-config.xml配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml,classpath:applicationContext.xml</param-value>
        </init-param>
        <!--启动服务器,创建该servlet-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!-- url-pattern配置方式一:/表示拦截所有请求 -->
        <!-- <url-pattern>/</url-pattern>-->
    </servlet-mapping>

4、出现如图页面表示springSecurity加入成功

在这里插入图片描述

5、权限的放行请参考springSecurity教程

/**
 * // @Configuration 将当前类标记为配置类
 * // @EnableWebSecurity 启用Web环境下权限控制功能
 * // @SuppressWarnings("all") 压制所有警告
 */
@Configuration
@EnableWebSecurity
@SuppressWarnings("all")
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private DataSource dataSource;

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    private MyPasswordEncoder passwordEncoder;

    @Bean
    public BCryptPasswordEncoder getBCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {

       /*builder
                .inMemoryAuthentication() // 在内存中完成账号、密码的检查
                .withUser("tom") // 指定账号
                .password("123456") // 指定密码
                .roles("ADMIN", "学徒") // 指定当前用户的角色
                .and()
                .withUser("et") // 指定账号
                .password("123123") // 指定密码
                .authorities("UPDATE", "内门弟子") // 指定当前用户的权限
        ;*/

        // 装配userDetailsService对象
        builder
                .userDetailsService(userDetailsService).passwordEncoder(getBCryptPasswordEncoder());
    }


    /**
     * 源码鉴赏 区分角色与权限
     * private static String hasRole(String role) {
     * Assert.notNull(role, "role cannot be null");
     * if (role.startsWith("ROLE_")) {
     * throw new IllegalArgumentException(
     * "role should not start with 'ROLE_' since it is automatically inserted. Got '"
     * + role + "'");
     * }
     * return "hasRole('ROLE_" + role + "')";*     }
     *
     * @param security
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity security) throws Exception {

        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);

        security.authorizeRequests() // 对请求进行授权
                .antMatchers("/layui/**", "/index.jsp") // 使用Ant风格设置要授权的URL地址
                .permitAll() //允许上面使用Ant风格设置的全部请求
                .antMatchers("/level1/**")        // 针对/level1/**路径设置访问要求
                .hasRole("学徒") // 要求用户具备“学徒”角色才可以访问
                .antMatchers("/level2/**") // 针对/level2/**路径设置访问要求
                .hasAnyAuthority("内门弟子") // 要求用户具备“内门弟子”权限才可以访问
                .and()
                .authorizeRequests() // 对请求进行授权
                .anyRequest() // 其他未设置的全部请求
                .authenticated() // 需要登录以后才可以访问
                .and()
                .formLogin() // 使用表单形式登录
                /*
                 关于loginPage()方法的特殊说明
                 指定登录页的同时会影响到:“提交登录表单的地址”、“退出登录地址”、“登录失败地址”
                 /index.jsp GET - the login form 去登录页面
                 /index.jsp POST - process the credentials and if valid authenticate the user 提交登录表单
                 /index.jsp?error GET - redirect here for failed authentication attempts 登录失败
                 /index.jsp?logout GET - redirect here after successfully logging out 退出登录
                */
                .loginPage("/index.jsp") //// 指定登录页面(如果没有指定会访问SpringSecurity自带的登录页)
                .permitAll() // 为登录页设置所有人都可以访问


                // loginProcessingUrl()方法指定了登录地址,就会覆盖loginPage()方法中设置的默认值/index.jsp POST
                .loginProcessingUrl("/do/login.html") // 指定提交登录表单的地址
                .usernameParameter("loginAcct") // 定制登录账号的请求参数名
                .passwordParameter("userPswd") // 定制登录密码的请求参数名
                .defaultSuccessUrl("/main.html") // 登录成功后前往的URL地址
                .and()
                //.csrf()
                //.disable() // 禁用CSRF功能
                .logout() // 开启退出功能
                .logoutUrl("/do/logout.html") // 指定处理退出功能请求的URL地址
                .logoutSuccessUrl("/index.jsp") // 退出成功后前往的地址
                .and()
                .exceptionHandling() // 指定异常处理器
                //.accessDeniedPage("/to/no/auth/page.html"); // 访问被拒绝403时前往的页面
                .accessDeniedHandler(new AccessDeniedHandler() {

                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        request.setAttribute("message", "自定义异常提示");
                        request.getRequestDispatcher("/WEB-INF/views/no_auth.jsp").forward(request, response);
                    }
                })
                .and()
                .rememberMe() // 开启记住我功能
                .tokenRepository(tokenRepository) // 开启数据库记住我功能(服务器重启也可以记住)
        ;
    }


     request.getRequestDispatcher("/WEB-INF/views/no_auth.jsp").forward(request, response);
                    }
                })
                .and()
                .rememberMe() // 开启记住我功能
                .tokenRepository(tokenRepository) // 开启数据库记住我功能(服务器重启也可以记住)
        ;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值