1.權限操做涉及的三張表css
(1)用戶表信息描述usersjava
sql語句:mysql
CREATE TABLE users ( id VARCHAR2 ( 32 ) DEFAULT SYS_GUID () PRIMARY KEY, email VARCHAR2 ( 50 ) UNIQUE NOT NULL, username VARCHAR2 ( 50 ), PASSWORD VARCHAR2 ( 50 ), phoneNum VARCHAR2 ( 20 ), STATUS INT )
(2)角色表描述roleweb
sql語句:spring
CREATE TABLE role ( id VARCHAR2 ( 32 ) DEFAULT SYS_GUID () PRIMARY KEY, roleName VARCHAR2 ( 50 ), roleDesc VARCHAR2 ( 50 ) )
(3)權限資源表描述permissionsql
sql語句:數據庫
CREATE TABLE permission ( id VARCHAR2 ( 32 ) DEFAULT SYS_GUID () PRIMARY KEY, permissionName VARCHAR2 ( 50 ), url VARCHAR2 ( 50 ) )
(4)權限資源與角色關聯關係express
權限資源與角色是多對多關係,咱們使用role_permission表來描述。apache
sql語句:跨域
CREATE TABLE role_permission ( permissionId VARCHAR2 ( 32 ), roleId VARCHAR2 ( 32 ), PRIMARY KEY ( permissionId, roleId ), FOREIGN KEY ( permissionId ) REFERENCES permission ( id ), FOREIGN KEY ( roleId ) REFERENCES role ( id ) )
(5)用戶與角色關聯關係
用戶與角色之間是多對多關係,咱們經過user_role表來描述其關聯
sql語句:
CREATE TABLE users_role ( userId VARCHAR2 ( 32 ), roleId VARCHAR2 ( 32 ), PRIMARY KEY ( userId, roleId ), FOREIGN KEY ( userId ) REFERENCES users ( id ), FOREIGN KEY ( roleId ) REFERENCES role ( id ) )
(6)三張表關聯
2.Spring Security概述
Spring Security是 Spring 項目組中用來提供安全認證服務的框架。 Spring Security 爲基於J2EE企業應用軟件提供了全面安全服務。
安全包括兩個主要操做:
「認證」,是爲用戶創建一個他所聲明的主體。主題通常式指用戶,設備或能夠在你係 統中執行動做的其餘系統 。典型範例:用戶登陸
「受權」指的是一個用戶可否在你的應用中執行某個操做,在到達受權判斷以前,身份的主題已經由 身份驗證過程創建了。
3.Spring Security簡單應用---用戶登陸
(1)在父pom文件添加Spring Security的依賴
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.security.version}</version> </dependency>
注意:${spring.security.version}爲版本控制
<properties> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <oracle.version>10.2.0.4.0</oracle.version> <mybatis.version>3.4.5</mybatis.version> <mysql.version>5.1.6</mysql.version> <spring.security.version>5.0.1.RELEASE</spring.security.version> </properties>
(2)在web.xml文件中配置springsecurity
<1>添加一個過濾器
<!--04 配置springSecurity(開始)--> <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> <!--04 配置springSecurity(結束)-->
<2>添加類加載路徑
<!-- 配置加載類路徑的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml,classpath:spring-security.xml</param-value> </context-param>
(3)在resources目錄下建立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"> <!-- 配置不攔截的資源 --> <security:http pattern="/login.jsp" security="none"/> <security:http pattern="/failer.jsp" security="none"/> <security:http pattern="/css/**" security="none"/> <security:http pattern="/img/**" security="none"/> <security:http pattern="/plugins/**" security="none"/> <!-- 配置具體的規則 auto-config="true" 不用本身編寫登陸的頁面,框架提供默認登陸頁面 use-expressions="false" 是否使用SPEL表達式(沒學習過) --> <security:http auto-config="true" use-expressions="false"> <!-- 配置具體的攔截的規則 pattern="請求路徑的規則" access="訪問系統的人,必須有ROLE_USER的角色" --> <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/> <!-- 定義跳轉的具體的頁面,login-page指定登陸頁面,login-processing-url登陸路徑,login.jsp文件中會調用 --> <!--authentication-success-forward-url指定成功頁面,authentication-failure-url失敗頁面--> <security:form-login login-page="/login.jsp" login-processing-url="/login" default-target-url="/index.jsp" authentication-failure-url="/failer.jsp" authentication-success-forward-url="/pages/main.jsp" /> <!-- 關閉跨域請求 --> <security:csrf disabled="true"/> <!-- 退出 --> <security:logout invalidate-session="true" logout-url="/logout" logout-success-url="/login.jsp" /> </security:http> <!-- 切換成數據庫中的用戶名和密碼 --> <security:authentication-manager> <security:authentication-provider user-service-ref="userService"> <!-- 配置加密的方式 --> <security:password-encoder ref="passwordEncoder"/> </security:authentication-provider> </security:authentication-manager> <!-- 配置加密類 --> <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> <!-- 提供了入門的方式,在內存中存入用戶名和密碼 <security:authentication-manager> <security:authentication-provider> <security:user-service> <security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/> </security:user-service> </security:authentication-provider> </security:authentication-manager> --> </beans>
(5)在service模塊中建立IUserService和UserServiceImpl
接口
package lucky.service; import org.springframework.security.core.userdetails.UserDetailsService; public interface IUserService extends UserDetailsService { }
實現類
package lucky.service.impl; import lucky.dao.IUserDao; import lucky.domain.Role; import lucky.domain.UserInfo; import lucky.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; 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.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * 使用springsecurity進行用戶登陸 */ @Service(value = "userService") public class UserServiceImpl implements IUserService { @Autowired private IUserDao iUserDao; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserInfo userInfo=null; try { userInfo=iUserDao.queryByUsername(username); } catch (Exception e) { e.printStackTrace(); } //將本身的用戶對象封裝成UserDetails,參數1爲用戶名,參數2爲密碼,參數3是用戶權限 User user=new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles())); return user; } /** * @return 返回一個list集合,集合中裝的是用戶權限描述 * @param roles */ public List<SimpleGrantedAuthority> getAuthority(List<Role> roles) { List<SimpleGrantedAuthority> list=new ArrayList<>(); for (Role role : roles) { list.add(new SimpleGrantedAuthority(role.getRoleName())); } return list; } }
(6)IUserDao.java
package lucky.dao; import lucky.domain.UserInfo; import org.apache.ibatis.annotations.Many; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; public interface IUserDao { /** * @param username 用戶名 * @Results 映射查詢結果集到實體類屬性 * column爲數據庫字段名,porperty爲實體類屬性名,jdbcType爲數據庫字段數據類型,id爲是否爲主鍵。 * 涉及多對多查詢,有中間表 */ @Select("select * from LUCKY.USERS where username=#{username}") @Results({ @Result(id=true,property = "id",column = "id"), @Result(property = "username",column = "username"), @Result(property = "email",column = "email"), @Result(property = "password",column = "password"), @Result(property = "phoneNum",column = "phoneNum"), @Result(property = "status",column = "status"), @Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(select="lucky.dao.IRoleDao.queryByUserId")), }) public UserInfo queryByUsername(String username) throws Exception; }
(7)用戶退出功能
<1>只須要在springsecurity.xml配置文件中添加
<!-- 退出 --> <security:logout invalidate-session="true" logout-url="/logout" logout-success-url="/login.jsp" />
<2>再header.jsp頁面中調用便可
<li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">修改密碼</a> </div> <div class="pull-right"> <a href="${pageContext.request.contextPath}/logout" class="btn btn-default btn-flat">註銷</a> </div> </li>
(8)效果圖