1. 程式人生 > >SpringSecurity【使用者+許可權的資料庫持久化】

SpringSecurity【使用者+許可權的資料庫持久化】

實戰前理論講解

資料庫檔案

要想達到這個目的:主要是實現一個介面,UserDetilsService。
然後,把這個類配置到SpringSecurity的配置檔案中。

這個介面只有一個方法:

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{

}

這個方法的作用就是返回使用者的相關資訊包括使用者名稱和密碼還有該使用者擁有的許可權資訊。

返回的這些資訊將會被用作SpringSecurity驗證使用者登入資訊的標準,及這個方法返回的使用者名稱密碼,將會和 在使用者登入介面接收到的資訊進行比對。這些許可權資訊也會被保留到SpringSecurity自身的其它類中儲存起來,在以後訪問頁面時將會驗證當前使用者的許可權。

所以經過上面的分析,我們就能夠知道,我們可以在這個類中寫資料庫訪問的邏輯。

通常我們資料庫的表結構,有以下五個就夠了。

user(username 主鍵 , password)
role(rid 主鍵 , rname , rdescription)
user_role(urid 主鍵 , username 外來鍵 , rid 外來鍵)
res(res_id 主鍵 , res_url , res_description)
res_role(res_r_id 主鍵 , res_id 外來鍵 , r_id 外來鍵)

實現UserDetilsService

/**
 * Created by Administrator on 2017/8/9.
 */
@Component("customUserService") public class CustomUserService implements UserDetailsService{ @Autowired private UserMapper userMapper; @Autowired private UserRoleMapper userRoleMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserCustom requestMessage = new
UserCustom(username,""); cn.domarvel.po.User resultUser = userMapper.findUserByUsername(requestMessage); if (resultUser == null) { return null; } String password = resultUser.getPassword(); boolean enabled = true; boolean accountNonLoked = true; boolean accountNonExpired = true; boolean credentialsNonExipred = true; Collection<GrantedAuthority> authorities = new ArrayList<>(); List<Role> roles = userRoleMapper.findRolesByUsername(requestMessage); if (roles == null) { return null; } for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getRname())); } //前面的所有鋪墊都是為了返回這個User引數。所以你只需要看這一步就行了。相關引數 自行百度!!謝謝!! User user = new User(username,password,enabled,accountNonExpired,credentialsNonExipred,accountNonLoked,authorities); return user; } }

配置 SpringSecurity檔案

    <!-- 配置使用者角色資訊 -->
    <security:authentication-manager alias="authenticationManagerw">
        <security:authentication-provider user-service-ref="customUserService">
        </security:authentication-provider>
    </security:authentication-manager>

總的配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 配置不過濾的資源(靜態資源及登入相關) -->
    <security:http pattern="/**/*.css" security="none"></security:http>
    <security:http pattern="/**/*.jpg" security="none"></security:http>
    <security:http pattern="/**/*.jpeg" security="none"></security:http>
    <security:http pattern="/**/*.gif" security="none"></security:http>
    <security:http pattern="/**/*.png" security="none"></security:http>
    <security:http pattern="/**/*.js" security="none"></security:http>

    <security:http pattern="/login.jsp" security="none"></security:http>
    <security:http pattern="/index.jsp" security="none"></security:http>
    <security:http pattern="/getCode" security="none" /><!-- 不過濾驗證碼 -->
    <security:http pattern="/test/**" security="none"></security:http><!-- 不過濾測試內容 -->

    <!-- 配置資源許可權資訊 -->
    <security:http auto-config="true" use-expressions="false">

        <security:custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>

        <!-- 配置登出 -->
        <!-- 有時候,你會發現,就算重啟了 Tomcat ,session 也不會過期,那麼你需要配置退出時,session 過期。 -->
        <security:logout logout-url="/logoutSecurity" invalidate-session="true" delete-cookies="JSESSIONID"/>
        <!-- 在配置登出時,如果不把 csrf 設定為 true 的話,那麼登出時的連結將會發生 404 錯誤。 -->
        <security:csrf disabled="true"/>
    </security:http>

    <!-- 配置使用者角色資訊 -->
    <security:authentication-manager alias="authenticationManagerw">
        <security:authentication-provider user-service-ref="customUserService">
        </security:authentication-provider>
    </security:authentication-manager>

    <bean id="MyaccessManager" class="org.springframework.security.access.vote.AffirmativeBased">
        <constructor-arg name="decisionVoters">
            <list>
                <ref bean="roleVoter"/>
                <ref bean="authVoter"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
        <property name="rolePrefix" value="ROLE_"/>
    </bean>

    <bean id="authVoter" class="org.springframework.security.access.vote.AuthenticatedVoter"/>

    <bean id="securityMetadataSource" class="cn.domarvel.springsecurity.model.URLFilterInvocationSecurityMetadataSource" />

    <!-- 資料庫管理url -->
    <bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
        <property name="accessDecisionManager" ref="MyaccessManager"></property>
        <property name="authenticationManager" ref="authenticationManagerw"></property>
        <property name="securityMetadataSource" ref="securityMetadataSource"></property>
    </bean>
</beans>