zoukankan      html  css  js  c++  java
  • 08 SSM整合案例(企业权限管理系统):08.权限控制

    04.AdminLTE的基本介绍

    05.SSM整合案例的基本介绍

    06.产品操作

    07.订单操作

    08.权限控制

    09.用户操作

    10.权限关联与控制

    11.AOP日志

    08.权限控制 

    SSM权限操作


      

     1.数据库与表结构

    4.用户角色权限关系

     如果删除TABLE ,需要先删除多对多创建的中间表后,才能删除其它主键关联的表。

     1.1 用户表 

    用户表信息描述users

      本案例使用oracle数据库

    -- 1.1.2 sql语句
    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
    )

      实体类

    package cn.bjut.ssm.domain;
    
    import java.util.List;
    
    public class UserInfo {
        private String id;
        private String username;
        private String email;
        private String password;
        private String phoneNum;
        private Integer status;
        //======成员变量是其它实体类的List<E>=====
        private String statusStr;
        private List<Role> roles; 
    
        public String getStatusStr() {
            //状态0 未开启 1 开启
            if(status!=null){
                if(status==0)
                    statusStr="未开启";
                if(status==1)
                    statusStr="开启";
            }
            
            return statusStr;
        }
    
        public void setStatusStr(String statusStr) {
            this.statusStr = statusStr;
        }
        //==========其它get/set方法===============

     1.2 角色表 

    -- 1.2.2 sql语句
    CREATE TABLE role(
    id varchar2(32) default SYS_GUID() PRIMARY KEY,
    roleName VARCHAR2(50) ,
    roleDesc VARCHAR2(50)
    )

      

    package cn.bjut.ssm.domain;
    
    import org.springframework.security.core.userdetails.User;
    
    import java.util.List;
    
        public class Role {
        private String id;
        private String roleName;
        private String roleDesc;
        private List<Permission> permissions;
        private List<User> users;
        //=====Role与User以及Permission都是多对多的关系

    1.2.3 用户与角色关联关系

    用户与角色之间是多对多关系,我们通过user_role表来描述其关联,在实体类中User中存在List,在Role中有List 

    -- 用户与角色关联表
    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)
    )

     1.3 资源权限表

    -- 1.3.2 sql语句
    CREATE TABLE permission(
    id varchar2(32) default SYS_GUID() PRIMARY KEY,
    permissionName VARCHAR2(50) ,
    url VARCHAR2(50)
    )

        

    package cn.bjut.ssm.domain;
    
    import java.util.List;
    
    public class Permission {
        private String id;
        private String permissionName;
        private String url;
        private List<Role> roles;
        //=====存在一对多关系,则在一的实体类中的成员变量类型是多的List<E>
        //=====存在一对多关系,则在一的实体类中的成员变量名称是多的names

     1.3.3.权限资源与角色关联关系 

     权限资源与角色是多对多关系,我们使用role_permission表来描述。在实体类Permission中存在List,Role类中List

    -- 权限资源与角色是多对多关系
    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)
    )

      


    2.Spring Security概述

     Spring Security 是 Spring 项目组中用来提供安全服务的框架。 安全包括两个主要操作:

    认证

    授权” 

     maven依赖

    <dependencies>
      <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.0.10.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.0.10.RELEASE</version>
      </dependency>
    </dependencies>

     

    Spring Security快速入门

    1、导入maven依赖坐标

       pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>cn.bjut</groupId>
      <artifactId>springSecurityTest</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <name>springSecurityTest Maven Webapp</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <properties>
        <spring.version>5.0.15.RELEASE</spring.version>
        <spring.security.version>5.0.10.RELEASE</spring.security.version>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <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>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
          <scope>provided</scope>
        </dependency>
      </dependencies>
    
        <build>
          <finalName>springSecurityTest</finalName>
          <plugins>
            <!-- java编译插件 -->
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.8.0</version>
              <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
              </configuration>
            </plugin>
            <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.2</version>
              <configuration>
                <!-- 指定端口 -->
                <port>8090</port>
                <!-- 请求路径 -->
                <path>/</path>
              </configuration>
            </plugin>
          </plugins>
        </build>
    </project>

     2、在WEB-INF目录下的 web.xml中配置<filter>

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        version="2.5">
    
    
        <display-name>SpringSecurityTest</display-name>
    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath: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>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

     3、在 classpath: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 auto-config="true" use-expressions="false">
            <!-- intercept-url定义一个过滤规则 pattern表示对哪些url进行权限控制,access属性表示在请求对应
            的URL时需要什么权限,
            默认配置时它应该是一个以逗号分隔的角色列表,请求的用户只需拥有其中的一个角色就能成功访问对应
            的URL -->
            <security:intercept-url pattern="/**" access="ROLE_USER" />
            <!-- auto-config配置后,不需要在配置下面信息 <security:form-login /> 定义登录表单信息
            <security:http-basic/> <security:logout /> -->
        </security:http>
        <security:authentication-manager>
            <security:authentication-provider>
                <security:user-service>
                    <security:user name="user" password="{noop}user"
                                   authorities="ROLE_USER" />
                    <security:user name="admin" password="{noop}admin"
                                   authorities="ROLE_ADMIN" />
                </security:user-service>
            </security:authentication-provider>
        </security:authentication-manager>
    </beans>

     2.2.5 springSecurity快速入门:使用自定义页面

     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 security="none" pattern="/login.html" />
        <security:http security="none" pattern="/failer.html" />
        <security:http auto-config="true" use-expressions="false">
            <!-- 配置资料连接,表示任意路径都需要ROLE_USER权限 -->
            <security:intercept-url pattern="/**" access="ROLE_USER" />
            <!-- 自定义登陆页面,login-page 自定义登陆页面 authentication-failure-url 用户权限校验失败之
            后才会跳转到这个页面,如果数据库中没有这个用户则不会跳转到这个页面。
            default-target-url 登陆成功后跳转的页面。 注:登陆页面用户名固定 username,密码
            password,action:login -->
            <security:form-login login-page="/login.html"
                                 login-processing-url="/login"
                                 username-parameter="username" password-parameter="password"
                                 authentication-failure-url="/failer.html"
                                 authentication-success-forward-url="/success.html"
                                 default-target-url="/success.html"
            />
            <!-- 登出, invalidate-session 是否删除session logout-url:登出处理链接 logout-successurl:登出成功页面
            注:登出操作 只需要链接到 logout即可登出当前用户 -->
            <security:logout invalidate-session="true"
                             logout-url="/logout"
                             logout-success-url="/login.jsp" />
            <!-- 关闭CSRF,默认是开启的 -->
            <security:csrf disabled="true" />
        </security:http>
        <security:authentication-manager>
            <security:authentication-provider>
                <security:user-service>
                    <security:user name="user" password="{noop}user"
                                   authorities="ROLE_USER" />
                    <security:user name="admin" password="{noop}admin"
                                   authorities="ROLE_ADMIN" />
                </security:user-service>
            </security:authentication-provider>
        </security:authentication-manager>
    </beans>

      

     2.3 Spring Security使用数据库认证

    在Spring Security中如果想要使用数据进行认证操作,有很多种操作方式,这里我们介绍使用UserDetails接口、UserDetailsService来完成操作。

    UserDetails作用是于封装当前进行认证的用户信息,但由于其是一个接口,
    所以我们可以对其进行实现,也可以使用Spring Security提供的一个UserDetails实现类User来完成操作。

    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; //帐户是否可用

    UserDetailsService

    public interface UserDetailsService {
    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
    }

      

    3. 用户管理 

    6.使用数据库完成springSecurity用户登录流程分析

    3.1 用户登录
     webapp/WEB-INF目录下的

     web.xml

     

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
    
        <!-- 声明加载spring框架配置文件的路径 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:applicationContext.xml,classpath*:spring-security.xml</param-value>
        </context-param>
    
        <!-- 配置spring-web监听器 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!-- 配置监听器,监听request域对象的创建和销毁的 -->
        <listener>
            <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
        </listener>
    
        <!-- 前端控制器(加载classpath:springmvc.xml 服务器启动创建servlet) -->
        <servlet>
            <servlet-name>dispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
            <!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
    
        <!-- 解决中文乱码过滤器 -->
        <filter>
            <filter-name>characterEncodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <!--委派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>
    
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

     配置在web项目的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="/images/**" security="none"/>
        <security:http pattern="/plugins/**" security="none"/>
        
        <!-- 
            配置具体的规则 
            auto-config="false"    选用自己编写登录的页面,不用框架提供的默认登录页面
            use-expressions="false"    是否使用SPEL表达式(还没学习过)
        -->
        <security:http auto-config="false" use-expressions="true" >
            <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
            <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>
            <!--<security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>-->
    
            <!--如果没有login-processing-url这一属性,那么登录表单的action,必须为j_spring_secutity_check-->
            <!-- 定义跳转的具体的页面 -->
            <security:form-login  
                login-page="/login.jsp"
                login-processing-url="/login"
                username-parameter="username" password-parameter="password"
                default-target-url="/index.jsp"
                authentication-failure-url="/failer.jsp"
                authentication-success-forward-url="/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"/>-->
        
        <!-- 提供了入门的方式,在内存中存入用户名和密码 
        <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>
      

     自己编写用到的

     userServiceImpl实现类

     

      

    package cn.bjut.ssm.service.impl;
    
    import cn.bjut.ssm.dao.IUserDao;
    import cn.bjut.ssm.domain.UserInfo;
    import cn.bjut.ssm.service.IUserService;
    import org.springframework.beans.factory.annotation.Autowired;
    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 org.springframework.transaction.annotation.Transactional;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Service(value = "userService")
    @Transactional  //注解的方式使用spring事务管理
    public class UserServiceImpl implements IUserService {
        @Autowired
        IUserDao userDao;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            //UserInfo是domain包下的实体类
            UserInfo userInfo = null;
    
            try{
                userInfo = userDao.findByUsername(username);
            } catch(Exception e){
                e.printStackTrace();
            }
    
            //把自己查询到的实体类中的认证信息封装成UserDetails
            //"{noop}"使用密码明文的必要前缀
    
            User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority());
            return user;
    
        }
    
        //这个成员方法作用就是返回一个List集合,集合中装入的是角色描述。
        //实际项目中应该是从数据库中获取role描述后封装到这个方法体里面。
        public List<SimpleGrantedAuthority> getAuthority(){
    
            List<SimpleGrantedAuthority> list = new ArrayList<>();
            // new 匿名对象
            list.add(new SimpleGrantedAuthority("ROLE_USER"));
            return list;
        }
    
    }

     在DAO层写一个Java的 Interface ,用来查询用户信息,获取username和password查询结果集封装在实体类中。

    package cn.bjut.ssm.dao;
    
    import cn.bjut.ssm.domain.UserInfo;
    import org.apache.ibatis.annotations.Select;
    
    public interface IUserDao {
    
        @Select("select * from USERS where username = #{username}")
        public UserInfo findByUsername(String username) throws Exception;
    }

     

     使用PL/SQL Developer插入一条完整用户数据到USERS表如下:

    -- 查询user表
    select * from users t;
    
    -- 插入一条users表数据
    insert into users values('1101112019','itheima@itcast.cn','ssm08','itheima','15612345678',1);

      

    运行版本报错信息为:WARN  o.bcrypt.BCryptPasswordEncoder  - Encoded password does not look like BCrypt;

    因为spring-security在最新版本升级后,默认把之前的明文密码方式给去掉了官方文档说明

    参考资料: 

    使用Spring Security下的BCryptPasswordEncoder进行密码加密

    SpringBoot Security:Encoded password does not look like BCrypt 解决

    spring-cloud-oauth2升级版本遇到的认证报bad credentials,Encoded password does not look likebcrypt的问题

    https://blog.csdn.net/SWPU_Lipan/article/details/80586054 

      index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8"%>
    <html>
    <head>
    
        <title>默认主页</title>
    </head>
    <body>
    <p>你正在浏览webapp目录下的index.jsp</p><br>
    超链接标签请求的href后面访问不到WEB-INF目录里的jsp文件<br>
    <a href="${pageContext.request.contextPath}/pages/main.jsp">点击跳转到:/webapp/pages/main.jsp</a><br>
    <%--<jsp:forward page="/pages/main.jsp"></jsp:forward>--%>
    
    <jsp:forward page="./WEB-INF/pages2/main2.jsp"></jsp:forward>
    </body>
    </html>

    截止目前我发现如果浏览器想访问WEB-INF目录里的.jsp页面,首先可以通过springMVC的视图解析器配置通过返回ModelAndView访问到,再有就是通过<jsp:forward page=" /WEB-INF"> 跳转访问。


    -- 插入一条记录到角色表记录
    insert into ROLE values ('12345','ADMIN','vip');
    -- 插入一条用户-角色中间表记录
    insert into USERS_ROLE values('1101112019','12345');
    package cn.bjut.ssm.dao;
    
    import cn.bjut.ssm.domain.Role;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    public interface IRoleDao {
        //根据用户ID查询出所有对应的角色
        @Select("select * from ROLE where id in( select ROLEID from USERS_ROLE where USERID  = #{userId})")
        public List<Role> findRoleByUserId(String userId) throws Exception;
    }
    public interface IUserDao {
    
        @Select("select * from USERS where username = #{username}")
        @Results({
                @Result(property = "id",column = "id",id = true),
                @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"),
                //通过中间表查询多对多关系,返回一个其它实体类的List集合
                @Result(property = "roles",column = "id",javaType =java.util.List.class,many = @Many(select = "cn.bjut.ssm.dao.IRoleDao.findRoleByUserId"))
        })
        public UserInfo findByUsername(String username) throws Exception;
    
    
    }

     这是不考虑Role的可用/不可用状态时的认证实现类

    @Service(value = "userService")
    @Transactional  //注解的方式使用spring事务管理
    public class UserServiceImpl implements IUserService {
        @Autowired
        IUserDao userDao;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            //UserInfo是domain包下的实体类
            UserInfo userInfo = null;
    
            try{
                userInfo = userDao.findByUsername(username);
            } catch(Exception e){
                e.printStackTrace();
            }
    
            //把自己查询到的实体类中的认证信息封装成UserDetails
            //"{noop}"使用密码明文的必要前缀
    
            User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles()));
    
    
    
    
            return user;
    
        }
    
        //这个成员方法作用就是返回一个List集合,集合中装入的是角色描述。
        //实际项目中应该是从数据库中获取role描述后封装到这个方法体里面。
        public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
    
            List<SimpleGrantedAuthority> list = new ArrayList<>();
    
    
            //增强for循环
            for (Role role :roles){
                         // new 匿名对象
                list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
            }
    
            return list;
        }

      考虑用户表中状态值:

    //状态0 未开启 1 开启
    使用了三元运算符进行判断
    @Service(value = "userService")
    @Transactional  //注解的方式使用spring事务管理
    public class UserServiceImpl implements IUserService {
        @Autowired
        IUserDao userDao;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            //UserInfo是domain包下的实体类
            UserInfo userInfo = null;
    
            try{
                userInfo = userDao.findByUsername(username);
            } catch(Exception e){
                e.printStackTrace();
            }
    
            //把自己查询到的实体类中的认证信息封装成UserDetails
            //"{noop}"使用密码明文的必要前缀
    
            // User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles()));
            User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),userInfo.getStatus() ==0 ?false:true,true,true,true,getAuthority(userInfo.getRoles()));
            
            return user;
    
        }
    
        //这个成员方法作用就是返回一个List集合,集合中装入的是角色描述。
        //实际项目中应该是从数据库中获取role描述后封装到这个方法体里面。
        public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
    
            List<SimpleGrantedAuthority> list = new ArrayList<>();
    
    
            //增强for循环
            for (Role role :roles){
                         // new 匿名对象
                list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
            }
    
            return list;
        }

    ====================

    end

    部分内容来自于学习编程期间收集于网络的免费分享资源和工作后购买的付费内容。
  • 相关阅读:
    远程连接mysql数据库注意点记录
    一个支持chrome、firefox的全屏插件
    Windows Phone应用程序Tombstone执行模型总结
    Windows Phone页面导航和独立存储开发总结
    【讨论帖】控制分布式缓存“及时”过期的一种实现
    Java HashMap的死循环的启示
    You must use the Role Management Tool to install or configure Microsoft .NET Framework 3.5 SP1
    Analysis Service Tabular Model #003 Multidimensional Model VS Tabular Model 我们该如何选择?
    Analysis Service Tabular Model #002 Analysis services 的结构:一种产品 两个模型
    基于DotNet构件技术的企业级敏捷软件开发平台 AgileEAS.NET 4.0 最新发布版本 下载使用说明
  • 原文地址:https://www.cnblogs.com/MarlonKang/p/11570327.html
Copyright © 2011-2022 走看看