关于springSecurity简易入门使用

简介

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

1.创建一个maven工程

添加springSecurity所需依赖

<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-INF中配置web.xml文件

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:applicationContext.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>

如上filter会拦截所有请求,其中<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>是一个代理类,注意:<filter-name>springSecurityFilterChain</filter-name>不能随便改,只能是springSecurityFilterChain。

3.编辑applicationContext.xml配置文件

<?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">
	<!-- 配置页面拦截规则 -->
	<!-- use-expressions表示是否启用spel表达式 ,当前为不启用,如果不配置默认为true,access要写成access="hasRole('ROLE_USER')"-->
	<http use-expressions="false">
		<!-- /*表示当前目录 下的资源,不包括目录下的子资源,/**表示当前目录和子目录下的资源-->
		<!-- access表示角色,当前用户必须有ROLE_USER的角色才能访问/**的资源,access配置必须要以‘ROLE_’开头 -->
		<intercept-url pattern="/**" access="ROLE_USER"/>
		<!-- 开启表单登陆功能 -->
		<form-login/>
	</http>	
	
	<!-- 认证管理器 -->
	<authentication-manager>
		<authentication-provider>
			<user-service>
				<!-- 配置用户, 当前用户为admin,角色为ROLE_USER-->
				<user name="admin" password="123456" authorities="ROLE_USER"/>
			</user-service>
		</authentication-provider>
	</authentication-manager>
</beans:beans>

如上,配置为ROLE_USER角色才能访问目录下的所有资源,认证管理器中配置用户admin为ROLE_USER角色

4.启动工程并访问资源

发现显示如下:

这是因为在配置文件中配置了<form-login/>,当然此时可以输入用户名和密码登入,输入刚配置的用户名和密码将会成功登陆并跳转到请求的资源(当然第一次请求会出现404,重新输入用户名和密码就好了)

猜你喜欢

转载自blog.csdn.net/u010689849/article/details/83019044