Spring Security框架使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhengzhaoyang122/article/details/82733419

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

二、Spring Security入门小Demo。
     1、创建Maven工程(war):spring-security-demo。
     2、修改pom.xml目录。

           <dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<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>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<!-- java编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<configuration>
					<!-- 指定端口 -->
					<port>9090</port>
					<!-- 请求路径 -->
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
	</build>

  注意:如果只是给自己的项目中嵌入Spring Security安全框架,只需要添加如下两个jar包即可。 

		<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>

      3、创建web.xml文件(通过Spring Security拦截需要处理的请求和引入Spring Security的配置文件)。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">	
	<!-- 引入spring-security框架的配置文件 -->
  	 <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-security.xml</param-value>
	 </context-param>
	 <listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	 </listener>
	<!-- 通过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>

     4、创建Spring Security配置文件:spring-security.xml(与web.xml中引入的配置文件对应),代码中有配置的详细说明注解。

<?xml version="1.0" encoding="UTF-8"?>
<!-- 此配置将Spring Seucrity设置成了默认标签,其他使用时,需要添加如下前缀beans或dubbo等 -->
<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">

	<!-- 登录页面不能拦截  none任何角色都可访问
	如果你没有设置登录页security="none"  ,将会出现以下错误 :"重定向次数过多"因为登录页会被反复重定向-->
	<http pattern="/*.html" security="none"></http>
	<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>
	<!-- 拦截页面 -->
	<!-- use-expressions -为是否使用使用 Spring 表达式语言( SpEL ),默认为true ,如果开启,则拦截的配置应该写成以下形式
	     <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
	-->
	<http use-expressions="false">
	    <!-- 
	         /*  表示的是该目录下的资源,只包括本级目录不包括下级目录
			 /** 表示的是该目录以及该目录下所有级别子目录的资源
		 -->
		<intercept-url pattern="/**" access="ROLE_SELLER" />
		<!-- form-login:开启表单登录,默认登录请求/login可以通过配置修改默认请求
		     always-use-default-target:指定了是否在身份验证通过后总是跳转到default-target-url属性指定的URL。
		     authentication-failure-url:登录失败,跳转页面 -->
		<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"  关闭csrf ,如果不加会出现错403    
		CSRF(Cross-site request forgery)跨站请求伪造,
		也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。-->
		<csrf disabled="true" />
		<!-- 当页面中存在嵌入式iframe时,需要配置hears -->
		<headers>
			<frame-options policy="SAMEORIGIN" />
		</headers>
		<!-- 登出,页面只需要发送/logout请求就可会触发 也可以修改默认的处理,例如logout-url=""可以修改登出的请求-->
		<logout />
	</http>
	<!-- Spring Security中 用户登录时认证管理器 -->
	<!-- Spring Security是如何完成身份认证的?
               ①、用户名和密码被过滤器获取到,封装成Authentication,通常情况下是UsernamePasswordAuthenticationToken这个实现类。
               ②、AuthenticationManager 身份管理器负责验证这个Authentication。
               ③、认证成功后,AuthenticationManager身份管理器返回一个被填充满了信息的(包括上面提到的权限信息,身份信息,细节信息,但密码通常会被移除)Authentication实例。
               ④、SecurityContextHolder安全上下文容器将第3步填充了信息的Authentication,
                             通过SecurityContextHolder.getContext().setAuthentication(…)方法,设置到其中。 -->
	<authentication-manager>
	    <!-- user-service-ref 指向用户认证业务处理类,需要实现UserDetailsService接口-->
	    <!-- 如果测试,不想从数据库中获取用户,可以直接配置一个用户名和密码 ,特换掉如下authentication-provider内的配置即可。
	    	<authentication-provider>
		  		<user-service>
		  			<user name="admin" password="123456" authorities="ROLE_USER"/>
		  		</user-service>
		  	</authentication-provider>
	    -->
		<authentication-provider user-service-ref="userDetailServiceImpl">
		    <!-- 对密码进行bcrypt加密,比较时需要解密后处理,bcrypt与MD5不同,
		         MD5加密后相同的密码生成相同的16位字符创,bcrybt相同的密码加密后生成不同的30位字符串,
		         相当于MD5+盐 -->
			<password-encoder hash="bcrypt"></password-encoder>
		</authentication-provider>
	</authentication-manager>
	<beans:bean id="userDetailServiceImpl" class="com.pinyougou.shop.service.UserDetailServiceImpl">
		<!-- 当自己的项目需要使用另一个项目中的服务类时 ,需要通过dubbo引入项目  dubbo标签-->
		<beans:property name="sellerService" ref="sellerService"></beans:property>
	</beans:bean>


	<!-- 引用dubbo sellerService服务:供登录用户业务处理类使用 -->
	<dubbo:application name="pinyougou-shop-web" />
	<dubbo:registry address="zookeeper://192.168.159.129:2181" />
	<dubbo:reference id="sellerService"
		interface="com.pinyougou.sellergoods.service.SellerService"></dubbo:reference>
</beans:beans>

    5、配置文件中配置的,登录时用户名和密码的业务逻辑处理类(实现UserDetailsService:框架自带的接口)

public class UserDetailServiceImpl implements UserDetailsService {
	//当通过配置文件的形式,引入服务类时需要设置set方法。
	private SellerService sellerService;
	
	public void setSellerService(SellerService sellerService) {
		this.sellerService = sellerService;
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//GrantedAuthority : 定义用户角色,需要实现的接口
		List<GrantedAuthority> list =new ArrayList<>();
		//用户添加角色,SimpleGrantedAuthority可以定义用户角色,实现了GrantedAuthority接口,格式必须以(ROLE_)开头
		list.add(new SimpleGrantedAuthority("ROLE_SELLER"));
		//从数据库中获取用户信息。
		TbSeller seller = sellerService.findOne(username);
		if(seller != null) {
			//返回username:传过来的参数。seller.getPassword:数据库中获取到的用户密码。list:用户的所有角色,可以从数据库中获取
			return new User(username, seller.getPassword(), list);
		}else {
			return null;
		}
	}

}

   6、BCrypt加密过程(配置中说明了BCrypt与MD5的区别)。

	@RequestMapping("/add")
	public Result add(@RequestBody TbSeller seller){
		try {
			//BCrypt加密使用的对象BCryptPasswordEncoder
			BCryptPasswordEncoder cryptPasswordEncoder = new BCryptPasswordEncoder();
			//使用encode方法对传入的密码加密,返回30位的字符串
			String encode = cryptPasswordEncoder.encode(seller.getPassword());
			//业务处理:接入对象中
			seller.setPassword(encode);
			//调用服务层,入库
			sellerService.add(seller);
			return new Result(true, "增加成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "增加失败");
		}
	}

三、当程序中需要用户名时,可通过SecurityContextHolder对象获取。
      ☏SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保存在SecurityContextHolder中。SecurityContextHolder默认使用ThreadLocal 策略来存储认证信息。看到ThreadLocal 也就意味着,这是一种与线程绑定的策略。Spring Security在用户登录时自动绑定认证信息到当前线程,在用户退出时,自动清除当前线程的认证信息。但这一切的前提,是你在web场景下使用Spring Security。
      ☏因为身份信息是与线程绑定的,所以可以在程序的任何地方使用静态方法获取用户信息。一个典型的获取当前登录用户的姓名的例子如下所示:getAuthentication()返回了认证信息。

	@RequestMapping("/name")
	public Map<String, String> getName(){
		//获取登录名
		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		Map<String, String> map = new HashMap<>();
		map.put("loginName", name);
		return map;
	}

      ☏Authentication源码:

package org.springframework.security.core;// <1>
public interface Authentication extends Principal, Serializable { // <1>
    Collection<? extends GrantedAuthority> getAuthorities(); // <2>
    Object getCredentials();// <2>
    Object getDetails();// <2>
    Object getPrincipal();// <2>
    boolean isAuthenticated();// <2>
    void setAuthenticated(boolean var1) throws IllegalArgumentException;
}

<1> Authentication是spring security包中的接口,直接继承自Principal类,而Principal是位于java.security包中的。可以见得,Authentication在spring security中是最高级别的身份/认证的抽象。
<2> 由这个顶级接口,我们可以得到用户拥有的权限信息列表,密码,用户细节信息,用户身份信息,认证信息。
authentication.getPrincipal()返回了一个Object,我们将Principal强转成了Spring Security中最常用的UserDetails,这在Spring Security中非常常见,接口返回Object,使用instanceof判断类型,强转成对应的具体实现类。接口详细解读如下:
→ getAuthorities(),权限信息列表,默认是GrantedAuthority接口的一些实现类,通常是代表权限信息的一系列字符串。
→ getCredentials(),密码信息,用户输入的密码字符串,在认证过后通常会被移除,用于保障安全。
→ getDetails(),细节信息,web应用中的实现接口通常为 WebAuthenticationDetails,它记录了访问者的ip地址和sessionId的值。
getPrincipal(),最重要的身份信息,大部分情况下返回的是UserDetails接口的实现类,也是框架中的常用接口之一。

猜你喜欢

转载自blog.csdn.net/zhengzhaoyang122/article/details/82733419