在Spring Boot中利用spring security实现权限管理

原创 2018年04月15日 22:42:13

效果图:





1.创建spring boot工程并导入依赖

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</groupId>
    <artifactId>security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>security</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- spring security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- thymeleaf基础模板 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- thymeleaf security模板 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>

        <!-- springboot单元测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <!-- web模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.application.yml配置(也可以换成application.properties)

application.yml
# server
server:
  port: 8086
  servlet:
    context-path:

# spring
spring:
  ## 数据源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/employee?useSSL=true&serverTimezone=Asia/Shanghai
    username: root
    password: root
  ## 彩色日志
  output:
    ansi:
      enabled: always
  ## jpa
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  ## thymeleaf
  thymeleaf:
    cache: false

# logging
logging:
  level:
    org.springframework.security: info

3.实体类

package com.security.domain;

import javax.persistence.*;

/**
 * @classDesc: 角色实体类
 * @author: Vipin Zheng
 * @createDate: 2018-04-15 13:19:09
 * @version: v1.0
 */
@Entity
public class SysRole {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column
    private String name;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.security.domain;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @classDesc: 用户实体类:实现UserDetails接口,这样我们的用户实体即为Spring Security所使用的用户
 * @author: Vipin Zheng
 * @createDate: 2018-04-15 13:26:03
 * @version: v1.0
 */

@Entity
public class SysUser implements UserDetails{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column
    private String username;
    @Column
    private String password;

    /**
     * 配置用户和角色多对多关系
     */
    @ManyToMany(cascade = {CascadeType.REFRESH},fetch = FetchType.EAGER)
    private List<SysRole> roles;

    /**
     * 正常情况下,角色和权限是两回事
     * 重写getAuthorities(),将角色和权限关联起来
     * @return GrantedAuthority
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<SysRole> roles = this.roles;
        for(SysRole role:roles){
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public Long getId() {
        return id;
    }

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

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

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

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

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

/**
 * @classDesc: 自定义信息返回类
 * @author: Vipin Zheng
 * @createDate: 2018-04-15 21:44:46
 * @version: v1.0
 */
public class Msg {
    private String title;
    private String content;
    private String extraInfo;

    public Msg() {
    }

    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 getExtraInfo() {
        return extraInfo;
    }

    public void setExtraInfo(String extraInfo) {
        this.extraInfo = extraInfo;
    }

    public Msg(String title, String content, String extraInfo) {
        this.title = title;
        this.content = content;
        this.extraInfo = extraInfo;
    }
}

4.持久层

package com.security.dao;

import com.security.domain.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @classDesc: 用户表 数据库访问接口
 * @author: Vipin Zheng
 * @createDate: 2018-04-15 13:33:47
 * @version: v1.0
 */
public interface SysUserRepository extends JpaRepository<SysUser, Long> {
    SysUser findByUsername(String username);
}

5.业务逻辑类

package com.security.service;

import com.security.dao.SysUserRepository;
import com.security.domain.SysUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;

/**
 * @classDesc: 用户表 业务逻辑类:实现UserDetailsService接口,在Spring Security中我们配置相关参数需要UserDetailsService类型的数据
 * @author: Vipin Zheng
 * @createDate: 2018-04-15 13:36:08
 * @version: v1.0
 */
public class SysUserService implements UserDetailsService {
    @Resource
    private SysUserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        System.out.println("username:"+user.getUsername()+";password:"+user.getPassword());
        return user;
    }
}

6.spring security配置类(核心)

package com.security.config;

import com.security.service.SysUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @classDesc: spring security配置类
 * @author: Vipin Zheng
 * @createDate: 2018-04-15 16:45:07
 * @version: v1.0
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 注册CustomUserService的Bean
     *
     * @return SysUserService
     */
    @Bean
    UserDetailsService customUserService() {
        return new SysUserService();
    }

    /**
     * 装载BCrypt密码编码器
     *
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.
                // 设置 UserDetailsService
                        userDetailsService(customUserService()).
                // 使用 BCrypt 进行密码的 hash
                        passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
                // 过滤静态资源
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                // 其他地址的访问均需登录
                .anyRequest().authenticated()

                .and()

                // 登录
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/index")
                .permitAll()

                .and()

                // 注销
                .logout()
                .logoutSuccessUrl("/login")
                .permitAll();
    }
}

7.控制器

package com.security.controller;

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

/**
 * @classDesc: 控制器
 * @author: Vipin Zheng
 * @createDate: 2018-04-15 20:02:00
 * @version: v1.0
 */
@Controller
public class SysUserController {

    @RequestMapping("/login")
    public String login(){
        return "login.html";
    }

    @RequestMapping("/index")
    public String index(Model model) {
        Msg msg = new Msg("测试标题", "测试内容", "额外信息,只对管理员显示");
        model.addAttribute("msg", msg);
        return "index.html";
    }
}

8.其他

login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8"/>
    <title>登录</title>
    <link rel="shortcut icon" th:href="@{favicon.ico}" type="image/x-icon">
    <link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
    <link rel="stylesheet" th:href="@{css/signin.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>
                <li><a th:href="@{http://www.baidu.com}">百度</a></li>
            </ul>
        </div>
    </div>
</nav>
<div class="container">
    <div class="starter-template">
        <p th:if="${param.logout}" class="bg-warning">已注销</p>
        <p th:if="${param.error}" class="bg-danger">有错误,请重试</p>
        <h2>使用账号密码登录</h2>
        <form class="form-signin" role="form" name="form" th:action="@{/login}" th:method="post">
            <div class="form-group">
                <label for="username">账号</label>
                <input type="text" class="form-control" name="username" placeholder="账号" id="username"/>
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" class="form-control" name="password" placeholder="密码" id="password"/>
            </div>
            <input type="submit" value="登录" class="btn btn-primary"/>
        </form>
    </div>
</div>

</body>
</html>

index.html
<!DOCTYPE html>
<!–suppress ThymeleafVariablesResolveInspection –>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8"/>
    <title sec:authentication="name"></title>
    <link rel="shortcut icon" th:href="@{favicon.ico}" type="image/x-icon">
    <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>
                <li><a th:href="@{http://www.baidu.com}">百度</a></li>
            </ul>
        </div>
    </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')">
            <p class="bg-info" th:text="${msg.extraInfo}"></p>
        </div>
        <div sec:authorize="hasRole('ROLE_USER')">
            <p class="bg-info">无更多显示信息</p>
        </div>
    </div>
    <form th:action="@{/logout}" th:method="post" class="text-center">
        <input type="submit" class="btn btn-primary" value="注销"/>
    </form>
</div>
</body>
</html>

PS:

    项目访问路径:localhost:8086/login

    项目下载路径:https://download.csdn.net/download/zhengweiping1004/10351197

参考资料:

https://blog.csdn.net/lenkvin/article/details/79482205

https://blog.csdn.net/dream_an/article/details/79381459

https://blog.csdn.net/u012702547/article/details/54319508

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhengweiping1004/article/details/79954341

springboot+springSecurity+mybatis实现权限管理

数据库设计 说明: 1.用户可以对应多个角色,角色可以对应多个权限; 2.PermissionAccess对应menu,button,action; 配置文件 pom.xml ...
  • pjj755
  • pjj755
  • 2017-06-21 14:49:34
  • 2075

在Spring Boot中使用Spring Security实现权限控制

Spring Boot框架我们前面已经介绍了很多了,相信看了前面的博客的小伙伴对Spring Boot应该有一个大致的了解了吧,如果有小伙伴对Spring Boot尚不熟悉,可以先移步这里从Sprin...
  • u012702547
  • u012702547
  • 2017-01-12 15:52:37
  • 92273

SpringBoot中使用Springsecurity实现权限控制

本文转自:http://blog.csdn.net/u012702547/article/details/54319508 ——————————————————————- Spring Boot框架我...
  • m0_37190495
  • m0_37190495
  • 2017-11-29 11:06:24
  • 338

SpringBoot中使用Spring Security实现权限控制

Spring Security,这是一个专门针对基于Spring的项目的安全框架,它主要是利用了AOP来实现的。以前在Spring框架中使用Spring Security需要我们进行大量的XML配置,...
  • qq_34912469
  • qq_34912469
  • 2017-07-21 17:02:52
  • 4343

springBoot+springSecurity 数据库动态管理用户、角色、权限(二)

序: 本文使用springboot+mybatis+SpringSecurity 实现数据库动态的管理用户、角色、权限管理本文细分角色和权限,并将用户、角色、权限和资源均采用数据库存储,并且自定义滤...
  • u012373815
  • u012373815
  • 2017-01-20 18:47:16
  • 41109

spring之使用Spring Security实现权限管理

转载:http://hanqunfeng.iteye.com/blog/1155226 目录 SpringSecurity3.X--一个简单实现 SpringSecurity3.X--前台与后...
  • u011068702
  • u011068702
  • 2015-12-06 02:59:50
  • 2118

Spring Boot 整合 Security 权限控制 - 第006章 - 自定义failureHandler

视频课程地址: Spring Boot 整合 Security 权限控制 在 java 源码目录下创建hander文件夹, 在该文件夹下创建CustomAuthenticationFailHand...
  • ShrCheng
  • ShrCheng
  • 2018-03-29 09:48:12
  • 49

Spring security实现权限管理

1、配置文件 1、POM.xml
  • zmx729618
  • zmx729618
  • 2016-04-08 14:53:57
  • 56599

Spring Boot 整合 Security 权限控制 - 第001章 - 基础环境配置

视频课程地址: Spring Boot 整合 Security 权限控制 创建一个 maven 项目(可使用 idea 或者其他编辑器) mvn archetype:generate -Dgr...
  • ShrCheng
  • ShrCheng
  • 2018-03-26 10:29:22
  • 90

使用Spring Security、Spring Data Jpa实现的RBAC权限控制

使用Spring Security、Spring Data Jpa做RBAC的权限控制。
  • u012556150
  • u012556150
  • 2016-05-18 09:54:33
  • 7643
收藏助手
不良信息举报
您举报文章:在Spring Boot中利用spring security实现权限管理
举报原因:
原因补充:

(最多只允许输入30个字)