1. 程式人生 > >springboot+mybatis+SpringSecurity 實現用戶角色數據庫管理

springboot+mybatis+SpringSecurity 實現用戶角色數據庫管理

.html ngs list css per title 。。 nfa from

本文使用springboot+mybatis+SpringSecurity 實現用戶權限數據庫管理

實現用戶和角色用數據庫存儲,而資源(url)和權限的對應采用硬編碼配置。 也就是角色可以訪問的權限通過硬編碼控制。角色和用戶的關系通過數據庫配置控制

本文用戶和角色的關系是多對多的關系。

SpringSecurity 驗證帳號密碼

首先在usernamePasswordAuthenticationFilter中來攔截登錄請求,並調用AuthenticationManager。

AuthenticationManager調用Provider,provider調用userDetaisService來根據username獲取真實的數據庫信息。
最終驗證帳號密碼的類是org.springframework.security.authentication.dao.DaoAuthenticationProvider這個流程雖然沒多麽復雜,但是花費我不少時間給理解到了。。。


本文結構:
1:數據庫表設計
2:springboot+mybatis 配置
3:業務實現
4:springSecurity整合
5:頁面實現
6:測試驗證

完整目錄結構如下:

技術分享


1:數據庫表設計

數據庫表有 用戶表,角色表,用戶角色關系表三張表:

技術分享

插入數據

insert into SYS_USER (id,username, password) values (1,‘admin‘, ‘admin‘);
insert into SYS_USER (id,username, password) values (2,‘abel‘, ‘abel‘);

insert into SYS_ROLE(id,name) values(1,‘ROLE_ADMIN‘);
insert into SYS_ROLE(id,name) values(2,‘ROLE_USER‘);

insert into SYS_ROLE_USER(SYS_USER_ID,ROLES_ID) values(1,1);
insert into SYS_ROLE_USER(SYS_USER_ID,ROLES_ID) values(2,2);

2:springboot+mybatis 配置

2.1 springboot 配置

新建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>com.us</groupId>
    <artifactId>springboot-security</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.RELEASE</version>
    </parent>

    <properties>
        <start-class>com.us.Application</start-class>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <mybatis.version>3.2.7</mybatis.version>
        <mybatis-spring.version>1.2.2</mybatis-spring.version>
    </properties>
    <dependencies>
        <!--springboot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
        <!--db-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>
    </dependencies>

</project>

MyBatisConfig.java (掃描mapper.xml文件)

package com.us.example.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@ComponentScan
public class MyBatisConfig {

    @Autowired
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        // sessionFactory.setPlugins(new Interceptor[]{new PageInterceptor()});
        sessionFactory.setMapperLocations(applicationContext.getResources("classpath*:mapper/*.xml"));
        return sessionFactory;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

MyBatisScannerConfig.java (dao 掃描器)

package com.us.example.config;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisScannerConfig {
    @Bean
    public MapperScannerConfigurer MapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.us.example.dao");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return mapperScannerConfigurer;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

TransactionConfig.java (開啟事物管理)

package com.us.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

@Configuration
@ComponentScan
public class TransactionConfig implements TransactionManagementConfigurer{
    @Autowired
    private DataSource dataSource;

    @Bean(name = "transactionManager")
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

3:業務實現

3.1 java bean

有三個bean ,sysuser(用戶),sysrole(角色)msg(信息,用於和頁面傳遞信息使用)

sysuser.java

package com.us.example.domain;

import java.util.List;

/**
 * Created by yangyibo on 17/1/17.
 */

public class SysUser {
    private Integer id;
    private String username;
    private String password;

    private List<SysRole> roles;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<SysRole> getRoles() {
        return roles;
    }

    public void setRoles(List<SysRole> roles) {
        this.roles = roles;
    }
}

SysRole.java

package com.us.example.domain;

/**
 * Created by yangyibo on 17/1/17.
 */

public class SysRole {

    private Integer id;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Msg.java

package com.us.example.domain;

/**
 * Created by yangyibo on 17/1/17.
 */

    public class Msg {
        private String title;
        private String content;
        private String etraInfo;

        public Msg(String title, String content, String etraInfo) {
            super();
            this.title = title;
            this.content = content;
            this.etraInfo = etraInfo;
        }
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        public String getContent() {
            return content;
        }
        public void setContent(String content) {
            this.content = content;
        }
        public String getEtraInfo() {
            return etraInfo;
        }
        public void setEtraInfo(String etraInfo) {
            this.etraInfo = etraInfo;
        }

    }

3.2 dao 層實現

UserDao.java

package com.us.example.dao;

import com.us.example.config.MyBatisRepository;
import com.us.example.domain.SysUser;

public interface UserDao {
    public SysUser findByUserName(String username);
}

mapper.xml

在src/resource目錄下新建 mapper 文件夾,在mapper文件夾下新建UserDaomapper.xml文件內容如下;

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.us.example.dao.UserDao">
    <resultMap id="userMap" type="com.us.example.domain.SysUser">
        <id property="id" column="ID"/>
        <result property="username" column="username"/>
        <result property="password" column="PASSWORD"/>
        <collection property="roles" ofType="com.us.example.domain.SysRole">
            <result column="name" property="name"/>
        </collection>

    </resultMap>
    <select id="findByUserName" parameterType="String" resultMap="userMap">
        select u.*
        ,r.name
        from Sys_User u
        LEFT JOIN sys_role_user sru on u.id= sru.Sys_User_id
        LEFT JOIN Sys_Role r on sru.Sys_Role_id=r.id
        where username= #{username}
    </select>
</mapper>

由於本例較為簡單,所以就去掉了service 層。

4:springSecurity整合

添加springSecurity 配置,在com.us.example.config 包下,新建
WebSecurityConfig.java 配置文件,用於管控登錄訪問權限

可以在WebSecurityConfig 中 使用                .antMatchers("/admin/**").hasRole("ROLE_ADMIN")

將url 權限分配給角色

WebSecurityConfig.java

package com.us.example.config;

import com.us.example.security.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
 * Created by yangyibo on 17/1/18.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService customUserService(){ //註冊UserDetailsService 的bean
        return new CustomUserService();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService()); //user Details Service驗證

    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated() //任何請求,登錄後可以訪問
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .permitAll() //登錄頁面用戶任意訪問
                .and()
                .logout().permitAll(); //註銷行為任意訪問


    }
}

CustomUserService.java

新建 CustomUserService 用於將用戶權限交給 springsecurity 進行管控;

package com.us.example.security;

import com.us.example.dao.UserDao;
import com.us.example.domain.SysRole;
import com.us.example.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangyibo on 17/1/18.
 */
@Service
public class CustomUserService implements UserDetailsService { //自定義UserDetailsService 接口

    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) { //重寫loadUserByUsername 方法獲得 userdetails 類型用戶

        SysUser user = userDao.findByUserName(username);
        if(user == null){
            throw new UsernameNotFoundException("用戶名不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //用於添加用戶的權限。只要把用戶權限添加到authorities 就萬事大吉。
        for(SysRole role:user.getRoles())
        {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            System.out.println(role.getName());
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(), authorities);
    }
}

5:頁面實現

在src/resource 目錄下新建static/css 目錄,並放入js 文件 bootstrap.min.css (此文件在本文源碼裏有, 源碼地址在文章底端)

在src/resource目錄下新建 templates 文件夾,裏面編寫靜態頁面

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
<title>登錄頁面</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
<style type="text/css">
    body {
  padding-top: 50px;
}
.starter-template {
  padding: 40px 15px;
  text-align: center;
}
</style>
</head>
<body>

     <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">Spring Security演示</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
           <li><a th:href="@{/}"> 首頁 </a></li>

          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>
     <div class="container">

      <div class="starter-template">
       <p th:if="${param.logout}" class="bg-warning">已成功註銷</p><!-- 1 -->
            <p th:if="${param.error}" class="bg-danger">有錯誤,請重試</p> <!-- 2 -->
            <h2>使用賬號密碼登錄</h2>
            <form name="form" th:action="@{/login}" action="/login" method="POST"> <!-- 3 -->
                <div class="form-group">
                    <label for="username">賬號</label>
                    <input type="text" class="form-control" name="username" value="" placeholder="賬號" />
                </div>
                <div class="form-group">
                    <label for="password">密碼</label>
                    <input type="password" class="form-control" name="password" placeholder="密碼" />
                </div>
                <input type="submit" id="login" value="Login" class="btn btn-primary" />
            </form>
      </div>
    </div>  
</body>
</html>

home.html

註意:本文是通過home.html  的sec:authorize="hasRole(‘ROLE_ADMIN‘) 實現角色權限管理
  • 1
  • 2
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta content="text/html;charset=UTF-8"/>
<title sec:authentication="name"></title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
<style type="text/css">
body {
  padding-top: 50px;
}
.starter-template {
  padding: 40px 15px;
  text-align: center;
}
</style>
</head>
<body>
     <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">Spring Security演示</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
           <li><a th:href="@{/}"> 首頁 </a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>


     <div class="container">

      <div class="starter-template">
        <h1 th:text="${msg.title}"></h1>

        <p class="bg-primary" th:text="${msg.content}"></p>

        <div sec:authorize="hasRole(‘ROLE_ADMIN‘)"> <!-- 用戶類型為ROLE_ADMIN 顯示 -->
            <p class="bg-info" th:text="${msg.etraInfo}"></p>
        </div>  

        <div sec:authorize="hasRole(‘ROLE_USER‘)"> <!-- 用戶類型為 ROLE_USER 顯示 -->
            <p class="bg-info">無更多信息顯示</p>
        </div>  

        <form th:action="@{/logout}" method="post">
            <input type="submit" class="btn btn-primary" value="註銷"/>
        </form>
      </div>

    </div>

</body>
</html>

6. controller

在com.us.example.controller 包下 編寫控制器 HomeController.java

HomeController.java

package com.us.example.controller;

import com.us.example.domain.Msg;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by yangyibo on 17/1/18.
 */
@Controller
public class HomeController {

    @RequestMapping("/")
    public String index(Model model){
        Msg msg =  new Msg("測試標題","測試內容","額外信息,只對管理員顯示");
        model.addAttribute("msg", msg);
        return "home";
    }
}

WebMvcConfig.java

springMVC 配置,註冊訪問 /login 轉向 login.html 頁面

package com.us.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * Created by yangyibo on 17/1/18.
 */
@Configuration

public class WebMvcConfig extends WebMvcConfigurerAdapter{

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }
}

7:測試驗證

啟動項目 在瀏覽器輸入 http://localhost:8080/ 進行測試:

首先使用 admin 帳號登錄

技術分享

結果:

技術分享

然後註銷,使用 abel 普通用戶登錄結果如下:

技術分享

本文參考:《JavaEE開發的顛覆者:Spring Boot實戰 》
本文源碼地址:https://github.com/527515025/springBoot
關於springboot 系列不定期更新。

springboot+mybatis+SpringSecurity 實現用戶角色數據庫管理