二初始化Spring Security

Posted 上善若水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二初始化Spring Security相关的知识,希望对你有一定的参考价值。

一、初始化Spring Security

1.1、Spring Security概念

Spring Security是spring采用AOP思想,基于servlet过滤器实现的安全框架。它提供了完善的认证机制和方法级的授权功能。是一款非常优秀的权限管理框架。

1.2、Spring Security简单入门

Spring Security博大精深,设计巧妙,功能繁杂,一言难尽,我们还是直接上代码吧!

1.2.1、创建web工程并导入jar包

Spring Security主要jar包功能介绍
spring-security-core.jar
核心包,任何Spring Security功能都需要此包。
spring-security-web.jar
web工程必备,包含过滤器和相关的Web安全基础结构代码。
spring-security-config.jar
用于解析xml配置文件,用到Spring Security的xml配置文件的就要用到此包。
spring-security-taglibs.jar
Spring Security提供的动态标签库,jsp页面可以用。

<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-taglibs</artifactId>
	<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-config</artifactId>
	<version>5.1.5.RELEASE</version>
</dependency>


最终的依赖树效果

1.2.2、配置web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
	<display-name>Archetype Created Web Application</display-name>

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <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 Security 过滤器链,注意过滤器名称必须叫springSecurityFilterChain-->
    <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>

1.2.3、配置spring-security.xml

src/main/resources/spring-security.xml

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security.xsd">
    <!--
        设置可以用spring的el表达式配置Spring Security并自动生成对应配置组件(过滤器)
        auto-config="true"  表示自动加载Spring Security的配置文件
        use-expressions="true"  表示使用Spring的el表达式来配置Spring Security
    -->
    <security:http auto-config="true" use-expressions="true">
        <!--
            使用spring的el表达式来指定项目所有资源访问都必须有ROLE_USER或ROLE_ADMIN角色
            pattern="/**" 表示拦截所有资源
            access="hasAnyRole('ROLE_USER')" 表示只有ROLE_USER角色才能访问资源
         -->
        <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')"/>
    </security:http>
    
    <!--设置Spring Security认证用户信息的来源-->
    <!--Spring Security默认的认证必须是加密的,加上{noop}表示不加密认证-->
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="{noop}user"
                               authorities="ROLE_USER" />
                <security:user name="admin" password="{noop}admin"
                               authorities="ROLE_ADMIN" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

1.2.4、将spring-security.xml配置文件引入到applicationContext.xml

<!--引入SpringSecurity主配置文件-->
<import resource="classpath:spring-security.xml"/>

1.2.5、运行结果

好了!开始启动项目了,万众期待看到index.jsp中的内容了!

唉!?说好的首页呢!?为何生活不是我想象!?
地址栏中login处理器谁写的!?这个带有外国人文字的页面哪来的!?这么丑!?我可以换了它吗!?
稍安勿躁……咱们先看看这个页面源代码,真正惊心动魄的还在后面呢……
这不就是一个普通的form表单吗?除了那个_csrf的input隐藏文件!
注意!这可是你想使用自定义页面时,排查问题的一条重要线索!

我们再去看看控制台发生了什么,这里我偷偷在项目中加了日志包和配置文件……
惊不惊喜!?意不意外!?哪来这么多过滤器啊!?

从启动日志中可以看到:

2021-08-22 13:20:23,724 2290 [on(3)-127.0.0.1] INFO web.DefaultSecurityFilterChain - Creating filter chain: any request, [org.springframework.security.web.context.SecurityContextPersistenceFilter@73b374c5, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4846458f, org.springframework.security.web.header.HeaderWriterFilter@38eda60e, org.springframework.security.web.csrf.CsrfFilter@673c635e, org.springframework.security.web.authentication.logout.LogoutFilter@fc13620, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@75d1606a, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@20596508, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@247bd4ce, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@220d9657, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@5c21704c, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@37bb3fe5, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@4d9c4078, org.springframework.security.web.session.SessionManagementFilter@36dc8b2, org.springframework.security.web.access.ExceptionTranslationFilter@54196b83, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@3ab332f2]

最后,我们在这个登录页面上输入用户名user,密码user,点击Sign in,好了,总算再次看到首页了!

1.2.6、Spring Security过滤器链查看



以上是关于二初始化Spring Security的主要内容,如果未能解决你的问题,请参考以下文章

spring boot整合 spring security之认证从数据库查询

Spring Security:无法让真正的用户使用显示过期的 SessionRegistry 登录

在运行时延迟初始化 Spring Security + 重新加载 Spring Security 配置

spring security 学习二

初始spring security

springboot集成spring security实现restful风格的登录认证 附代码