1. 程式人生 > >Spring Security的使用(入門)

Spring Security的使用(入門)

 概述:Spring Security的前身是Acegi Security,是Spring專案組中用來提供安全認證服務的框架
      認證: 驗證使用者名稱密碼是否正確的過程,authentication
      授權: 對使用者所能訪問的資源進行控制,authority

 

第一步:匯入依賴
<dependencies>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.0.1.RELEASE</version>
    </dependency>
</dependencies>

 

第二步:配置web.xml
<!--配置listener-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--環境載入監聽器,預設只能載入WEB-INF目錄下的資源,手動指定環境引數的位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <!--classpath*可以載入多個資原始檔-->
    <param-value>classpath*:applicationContext.xml,classpath*:spring-security.xml</param-value>
</context-param>
<!--配置filter-->
<filter>
    <!--此處springSecurityFilterChain固定寫法,不能改變-->
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-value>org.springframework.web.filter.DelegatingFilterProxy</filter-value>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

第三步:配置spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       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">
    
    <!--配置不攔截的資源,注意不要把pages目錄頁配置進來-->
     <security:http pattern="/login.jsp" security="none"/>
     <security:http pattern="/failure.jsp" security="none"/>
     <security:http pattern="/css/**" security="none"/>
     <security:http pattern="/js/**" security="none"/>
     <security:http pattern="/img/**" security="none"/>
     <security:http pattern="/plugins/**" security="none"/>

    <!--配置具體的規則-->
    <security:http auto-config="true" use-expressions="false">
        <!--配置具體的攔截放行規則-->
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
        <!--配置具體的表單頁面-->
        <security:form-page
            login-page="/login.jsp"        <!--指定登入頁面-->              
             login-processing-url="/login.do"  <!--指定處理登入請求的url-->
             default-target-url="/login.jsp"   <!--指定登入成功的頁面-->
             authentication-failure-url="/failure.jsp" <!--指定登入失敗的頁面-->
        <!--關閉跨域請求,注意少了這一行會一直403-->
        <security-csrf disabled="true"/>
        <!--配置登出使用者,logout-url指定處理退出請求的url-->
        <security:logout invalidate-session="true" logout-url="/logout.do" 
logout-success-url="/login.jsp">     
    </security:http>
        
    <!--在service層從資料庫查詢賬戶資訊-->
     <security:authentication-manager>
         <security:authentication-provider user-service-ref="userServiceImpl">
         </security:authentication-provider>
     </security:authentication-manager>
        
     <!--配置密碼加密類物件-->
     <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
     </bean>
</beans>

 

第四步:配置Service層
    自定義一個介面繼承UserDetailsService介面
    public interface IUserService extends UserDetailsService{ 什麼程式碼都不寫 }
    實現自定義的IUserService介面
    public class UserServiceImpl implements IUserService{ ... }
    這裡的User是由spring-security框架提供的,以下是User原始碼的Field
    public class User implements UserDetails, CredentialsContainer {
        private String password;
        private final String username;
        private final Set<GrantedAuthority> authorities;
        private final boolean accountNonExpired; //帳戶是否過期
        private final boolean accountNonLocked; //帳戶是否鎖定
        private final boolean credentialsNonExpired; //認證是否過期
        private final boolean enabled; //帳戶是否可用
}    

@Service("userServiceImpl")
public class UserServiceImpl implements IUserService{ 
     @Autowired
    private IUserDao userDao;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUsername(username);
        User user = new User(userInfo.getUsername(),"    {noop}"+userInfo.getPassword(),userInfo.getStatus()==0?false:true,
                true,true,true,getAuthorities(userInfo.getRoles()));
        return user;
    }
    public List<SimpleGrantedAuthority> getAuthorities(List<Role> roles){
        List<SimpleGrantedAuthority> list=new ArrayList<>();
        for (Role role : roles) {
            String roleName = role.getRoleName();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+roleName);
            System.out.println("ROLE_"+roleName);
            list.add(authority);
        }
        return list;
    }
}