spring mvc和mybatis和spring security 整合详解

 重点是spring security 整合详解

数据库准备

#用户表
CREATE TABLE USER ( id VARCHAR(32) PRIMARY KEY, userName VARCHAR(20), PASSWORD VARCHAR(32) COMMENT '密码加密', salary DOUBLE COMMENT '薪资' , birthday DATE COMMENT '生日' , gender VARCHAR(10) COMMENT '性别', station VARCHAR(40) COMMENT '住址', telephone VARCHAR(11) COMMENT '电话', remark VARCHAR(255) COMMENT '备注' ); #角色表 CREATE TABLE role( rid VARCHAR(32)PRIMARY KEY, rname VARCHAR(25), rdesc VARCHAR(100) )
#用户和角色表的关系表 CREATE TABLE user_role( user_id VARCHAR(32), role_id VARCHAR(32) )

 

 

1.spring security  需要准备的依赖

  <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.4.2</version>
        </dependency>
        <!--权限控制_页面控制-->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>5.4.2</version>
        </dependency>

 

2.配置我们的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:global-method-security pre-post-annotations="enabled"/>
    <security:global-method-security jsr250-annotations="enabled"/>
    <security:global-method-security secured-annotations="enabled"/>-->
    <security:debug/>
    <!-- 配置不拦截的资源 -->
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/statics/**" security="none"/>
    <security:http pattern="/user/zhuce" security="none"/>
    <security:http pattern="/isnetwork.jsp" security="none"/>
   <!-- <security:http pattern="/login.jsp" security="none"/>

    <security:http pattern="/user/zhuce" security="none"/>-->
    <!--
        配置具体的规则
        auto-config="true"    不用自己编写登录的页面,框架提供默认登录页面
        use-expressions="false"    是否使用SPEL表达式
    -->

    <security:http auto-config="true" use-expressions="true">
        <security:headers>
            <security:frame-options policy="SAMEORIGIN"/>
        </security:headers>
        <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
        <!--<security:intercept-url pattern="/userList" access="ROLE_ADMIN"/>-->
        <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
        <!-- 定义跳转的具体的页面 -->
        <security:form-login
                login-page="/login.jsp"
                username-parameter="userName"
                password-parameter="password"
                login-processing-url="/login.do"
                default-target-url="/index.jsp"
                authentication-failure-forward-url="/login.jsp"
                authentication-success-forward-url="/WEB-INF/jsp/index.jsp"
        />

        <!-- 关闭跨域请求 -->
        <security:csrf disabled="true"/>

        <!-- 退出 -->
        <security:logout invalidate-session="true" logout-url="/logout.do" 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"/>
    <bean id="userService" class="com.zjs.service.user.UserServiceImpl"/>

</beans>

 

3.在我们的applicationContext-mybatis.xml加上 开启注解配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd
">

    <context:component-scan base-package="com.zjs.service"/>

    <context:property-placeholder location="classpath:database.properties"/>
    <!--数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
        <!--4:-->
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"></property>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>

        <!--数据源调优:7-->
        <property name="initialSize" value="${initialSize}"/>
        <property name="maxIdle" value="${maxIdle}"/>
        <property name="minIdle" value="${minIdle}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="maxWait" value="${maxWait}"/>
        <property name="removeAbandoned" value="${removeAbandoned}"/>
        <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>

        <!--sql 心跳-->
        <property name="testWhileIdle" value="${testWhileIdle}"/>
        <property name="testOnBorrow" value="${testOnBorrow}"/>
        <property name="testOnReturn" value="${testOnReturn}"/>
        <property name="validationQuery" value="${validationQuery}"/>
        <property name="numTestsPerEvictionRun" value="${numTestsPerEvictionRun}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--配置mybatisplus 插件-->
        <property name="typeAliasesPackage" value="com.zjs.pojo"/>
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                            reasonable=true
                            supportMethodsArguments=true
                            params=count=countSql
                            autoRuntimeDialect=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!--mapperScannerConfiger-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zjs.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!--事务注解配置-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven/>

    <!--开启spring-security注解在service层生效-->
    <security:global-method-security
            secured-annotations="enabled"
            pre-post-annotations="enabled"
            jsr250-annotations="enabled"/>
    <!--读取spring-security.xml 资源-->
    <import resource="classpath:spring-security.xml"/>

</beans>

 

 

4.在我们的service 层接口中继承UserDetailsService

spring mvc和mybatis和spring security 整合详解

 

 

5.实现类UserServiceImpl 实现方法 

   @Override
    public User findByName(String userName) {
        System.out.println("用户名为:"+userName);
        return userMapper.findByName(userName);
    }
 @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User byName = userMapper.findByName(userName);
        if (byName==null){
            throw new UsernameNotFoundException("User等于空");
        }
        String username=byName.getUserName();
        String password = byName.getPassword();
        List<Role> byUserId = roleMapper.findByUserId(byName.getId());
        org.springframework.security.core.userdetails.User user= new org.springframework.security.core.userdetails.User(username,password,getAuthority(byUserId));
        System.out.println("userdetails = " +user);
        return user;
    }


    //作用就是返回一个List集合,集合中装入的是角色描述
    private Collection<? extends GrantedAuthority> getAuthority(List<Role> roles){
        List<SimpleGrantedAuthority> list=new ArrayList<SimpleGrantedAuthority>();
        for (Role role : roles) {
            System.out.println("role = " + role);
            list.add(new SimpleGrantedAuthority(role.getRolename()));//ROLE_+J ROLE_JICHU
        }
        return list;
    }

我们登陆也就不需要 controller ,因为在我们配置文件中 就配置了 登陆成功和失败所去的页面.

如果还要什么疑问的小伙伴 可以私信或留言在下方

 

 

上一篇:【自然框架】之通用权限的Demo(一):角色的添加和修改


下一篇:删除域中最后一台Exchange 2010