SpringSecurity

SpringSecurity

Spring Security

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

1.配置步骤

1.导入依赖

		<!-- 导包 -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>

2.配置web.xml

springSecurityFilterChain 一定不能改

		<!--web.xml-->
<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-security.xml

security=“none” 设置此资源不被拦截.

intercept-url 表示拦截页面

/* 表示的是该目录下的资源,只包括本级目录不包括下级目录

/** 表示的是该目录以及该目录下所有级别子目录的资源

form-login 为开启表单登陆

use-expressions 为是否使用使用 Spring 表达式语言( SpEL ),默认为true ,如果开启,则拦截的配置写成以下形式

csrf disabled=“true” 关闭csrf ,如果不加会出现错误

CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。

如果你在系统中使用了框架页,需要设置框架页的策略为SAMEORIGIN

logout-url:退出的地址,会自动生成,可以省略

​ logout-success-url:退出后跳转的地址,如果不配置,默认是登陆配置指定的登录页

<?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="/login.html" security="none"></http>



	<!-- 拦截规则 -->
	<http>
		<!--要求:所有的路径前都要加/ /的含义就是项目位置 /*当前目录级别的内容   hasRole SPEL-->
		<intercept-url pattern="/**" access="hasRole('ROLE_USER')"></intercept-url>
		<!-- 如果不指定登录页,提供一个默认的登录页
			login-page 指定登录页
			default-target-url 如果不指定,原来访问的是什么页面,登陆成功后就是什么 ,如果指定,登陆成功会跳转到指定的页面
			always-use-default-target 结合上面的属性用的,是一直跳转
			authentication-failure-url 登陆失败后跳转的页面
		-->
		<form-login login-page="/login.html" authentication-failure-url="/login.html"
					default-target-url="/index.jsp" always-use-default-target="true"></form-login>
		<!-- 关闭CSRF校验 -->
		<csrf disabled="true"></csrf>
        <headers>
			<!--iframe 默认是DENY拒绝使用 SAMEORIGIN:同源 协议 IP 端口号 ALLOW-FROM外网-->
			<frame-options policy="SAMEORIGIN"></frame-options>
		</headers>
		<!--会加载LogoutFilter-->
		<logout logout-success-url="/login.html"></logout>
      
	</http>



	<!--  认证管理器方式一 不连接数据库 使用配置的用户名和密码 -->
	<authentication-manager>
		<authentication-provider>
			<user-service>
				<user name="admin" password="123456" authorities="ROLE_USER"></user>
			</user-service>
		</authentication-provider>
	</authentication-manager>
    
    

</beans:beans>
<?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"
             xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
             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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <!--不被拦截的页面-->
    <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="false"  表示不使用spring的EL表达式-->
    <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/>
    </http>


    <authentication-manager>
        <!-- 连接数据库 收集userDetailsService传来的用户对象,和表单账号密码进行比对,比对成功则跳转,保存用户信息到session,失败则返回登录页 -->
        <authentication-provider user-service-ref="userDetailsService">
            <!--密码加密Bcrypt-->
            <password-encoder ref="bCryptPasswordEncoder"/>
        </authentication-provider>
    </authentication-manager>

    <!-- 连接dubbo给userDetailsService里的sellerService注入 -->
    <dubbo:application name="pyg_shop_web"></dubbo:application>
    <dubbo:registry address="zookeeper://192.168.35.128:2181"></dubbo:registry>
    <dubbo:reference id="sellerService" interface="com.pyg.sellergoods.service.SellerService"></dubbo:reference>

    
    <beans:bean id="userDetailsService" class="com.pyg.service.UserDetailsServiceImpl">
        <beans:property name="sellerService" ref="sellerService"></beans:property>
    </beans:bean>

    
    <!--Bcrypt加密类-->
    <beans:bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>


</beans:beans>

4.编写UserDetailsService实现类


import com.pyg.pojo.TbSeller;
import com.pyg.sellergoods.service.SellerService;
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 java.util.ArrayList;

/**
 * @author QuietHR
 * @create 2018/10/12
 **/
public class UserDetailsServiceImpl implements UserDetailsService {

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

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //权限列表
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //添加权限
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_SELLER"));
        //根据username调用service查询对象
        TbSeller seller = sellerService.findOne(username);
        if(seller!=null){
            return new User(username,seller.getPassword(),grantedAuthorities);
        }else{
            return null;
        }

    }
}

2.controller获取当前用户信息


import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author QuietHR
 * @create 2018/10/12
 **/
@RestController
@RequestMapping("/login")
public class LoginController {

    @RequestMapping("name")
    public Map name(){
        //SecurityContextHolder 提供了静态方法获取上下文
        //getContext 获取上下文
        //getAuthentication 获取当前用户
        //getName 获取登录用户名
        
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("loginName",name);
        return map;
    }

}