Spring Security(二)登入與安全控制

Admin_lee發表於2018-09-22

1、在pom.xml中新增依賴

<!-- Spring Security -->
   <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新增

<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

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

    <!-- 頁面攔截規則 -->
    <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>
        <authentication-provider user-service-ref="userDetailsService">
        </authentication-provider>
    </authentication-manager>

    <!-- 引用dubbo 服務 -->
    <dubbo:application name="pinyougou-shop-web" />
    <dubbo:registry address="zookeeper://123.207.255.168:2181"/>
    <dubbo:reference id="sellerService"  interface="com.pinyougou.sellergoods.service.SellerService" >
    </dubbo:reference>
    <beans:bean id="userDetailsService" class="com.pinyougou.shop.service.UserDetailsServiceImpl">
        <beans:property name="sellerService" ref="sellerService"></beans:property>
    </beans:bean>
</beans:beans>

4、自定義認證類

/**
 * @author 麥客子
 * @title: UserDetailsServiceImpl
 * @desc 認證類
 * @date 11:03 2018/9/21
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    private SellerService sellerService;
    public void setSellerService(SellerService sellerService) {
        this.sellerService = sellerService;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("經過了UserDetailsServiceImpl");
        //構建角色列表
        List<GrantedAuthority> grantAuths=new ArrayList();
        grantAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));
        //得到商家物件
        TbSeller seller = sellerService.findOne(username);
        if(seller!=null){
            if(seller.getStatus().equals("1")){
                return new User(username,seller.getPassword(),grantAuths);
            }else{
                return null;
            }
        }else{
            return null;
        }
    }
}

5、修改登入頁面

在這裡插入圖片描述

6、BCrypt加密演算法

使用者表的密碼通常使用MD5等不可逆演算法加密後儲存,為防止彩虹表破解更會先使用一個特定的字串(如域名)加密,然後再使用一個隨機的salt(鹽值)加密。 特定字串是程式程式碼中固定的,salt是每個密碼單獨隨機,一般給使用者表加一個欄位單獨儲存,比較麻煩。 BCrypt演算法將salt隨機並混入最終加密後的密碼,驗證時也無需單獨提供之前的salt,從而無需單獨處理salt問題。
(1)程式碼中應用

/**
	 * 增加
	 * @param seller
	 * @return
	 */
	@RequestMapping("/add")
	public Result add(@RequestBody TbSeller seller){

		//密碼加密
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		String password = passwordEncoder.encode(seller.getPassword());
		seller.setPassword(password);

		try {
			sellerService.add(seller);
			return new Result(true, "增加成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "增加失敗");
		}
	}

(2)修改spring-security配置

<!-- 認證管理器 -->
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
            <password-encoder ref="bcryptEncoder"></password-encoder>
        </authentication-provider>
    </authentication-manager>

    <!-- 引用dubbo 服務 -->
    <dubbo:application name="pinyougou-shop-web" />
    <dubbo:registry address="zookeeper://123.207.255.168:2181"/>
    <dubbo:reference id="sellerService"  interface="com.pinyougou.sellergoods.service.SellerService" >
    </dubbo:reference>
    <beans:bean id="userDetailsService" class="com.pinyougou.shop.service.UserDetailsServiceImpl">
        <beans:property name="sellerService" ref="sellerService"></beans:property>
    </beans:bean>

    <beans:bean id="bcryptEncoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
    </beans:beans> 

相關文章