四SpringSecurity Web权限方案

Posted 上善若水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了四SpringSecurity Web权限方案相关的知识,希望对你有一定的参考价值。

一、设置登录系统的账号、密码

1.1、方式一:在application.yml配置

server:
  port: 8081

spring:
  security:
    user:
      name: bitaotao
      password: 123456

1.2、方式二:自定义类实现接口


SecurityConfig.java

package com.xbmu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig 
    /**
     * 注入PasswordEncoder类到spring ioc容器中
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder()
        return new BCryptPasswordEncoder();
    

LoginService.java

package com.xbmu.service;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
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;

@Service
public class LoginService implements UserDetailsService 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 
        // 判断用户名是否存在
        if(!"admin".equals(username))
            throw new UsernameNotFoundException("用户名不存在!");
        
        // 从数据库获取的密码 admin 的密文
        String password = "$2a$10$RWILKEfws6dj5oO5XmTJS.oAoCwWyXspJfjq3d88wFpKV6cgpDzpK";
        // 第三个参数表示权限。这里权限随便写的
        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,role"));
    

1.3、方式三:实现数据库认证来完成用户登录(推荐)

1.3.1、准备SQL


-- ----------------------------
-- Table structure for menu
-- ----------------------------
DROP TABLE IF EXISTS `menu`;
CREATE TABLE `menu`  (
  `id` bigint(0) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `url` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `parentid` bigint(0) NULL DEFAULT NULL,
  `permission` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of menu
-- ----------------------------
INSERT INTO `menu` VALUES (1, '系统管理', '', 0, 'menu:system');
INSERT INTO `menu` VALUES (2, '用户管理', '', 0, 'menu:user');

-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role`  (
  `id` bigint(0) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, '管理员');
INSERT INTO `role` VALUES (2, '普通用户');

-- ----------------------------
-- Table structure for role_menu
-- ----------------------------
DROP TABLE IF EXISTS `role_menu`;
CREATE TABLE `role_menu`  (
  `mid` bigint(0) NULL DEFAULT NULL,
  `rid` bigint(0) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of role_menu
-- ----------------------------
INSERT INTO `role_menu` VALUES (1, 1);
INSERT INTO `role_menu` VALUES (2, 1);
INSERT INTO `role_menu` VALUES (2, 2);

-- ----------------------------
-- Table structure for role_user
-- ----------------------------
DROP TABLE IF EXISTS `role_user`;
CREATE TABLE `role_user`  (
  `uid` bigint(0) NULL DEFAULT NULL,
  `rid` bigint(0) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of role_user
-- ----------------------------
INSERT INTO `role_user` VALUES (1, 1);
INSERT INTO `role_user` VALUES (2, 2);

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`  (
  `id` bigint(0) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
  `password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `username`(`username`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES (1, 'zhangsan', '$2a$10$2R/M6iU3mCZt3ByG7kwYTeeW0w7/UqdeXrb27zkBIizBvAven0/na');
INSERT INTO `users` VALUES (2, 'lisi', '$2a$10$2R/M6iU3mCZt3ByG7kwYTeeW0w7/UqdeXrb27zkBIizBvAven0/na');

1.3.2、添加依赖

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency>
	<!--  mybatis-plus -->
	<dependency>
		<groupId>com.baomidou</groupId>
		<artifactId>mybatis-plus-boot-starter</artifactId>
		<version>3.0.5</version>
	</dependency>
	<!--  mysql -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
	</dependency>
	<!--  lombok -->
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
	</dependency>
</dependencies>

1.3.3、编写实体类

package com.xbmu.entity;

import lombok.Data;

@Data
public class Users 
    private Integer id;
    private String username;
    private String password;

1.3.4、整合MybatisPlus编写mapper

package com.xbmu.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xbmu.entity.Users;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper<Users> 


spring boot核心配置文件添加数据库配置

server:
  port: 8081
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test_db?serverTimezone=GMT%2B8
    username: root
    password: root

1.3.5、编写登录实现类

package com.xbmu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbmu.entity.Users;
import com.xbmu.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
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.List;

@Service
@Slf4j
public class LoginService implements UserDetailsService 
    @Autowired
    private UserMapper userMapper;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Users users = userMapper.selectOne(wrapper);
        if(null == users)
            throw new UsernameNotFoundException("用户名不存在!");
        
        log.info("用户信息:"+users);
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User(users.getUsername(),users.getPassword(),auths);
    

1.3.7、编写启动类

package com.xbmu;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.xbmu.mapper")
public class MainApplication 
    public static void main(String[] args) 
        SpringApplication.run(MainApplication.class,args);
    

1.3.8、测试

以上是关于四SpringSecurity Web权限方案的主要内容,如果未能解决你的问题,请参考以下文章

[SpringSecurity]web权限方案_用户注销

六SpringSecurity Web权限方案—— 基于数据库实现权限认证

六SpringSecurity Web权限方案—— 基于数据库实现权限认证

[SpringSecurity]web权限方案_用户授权_自定义403页面

五SpringSecurity Web权限方案——自定义登录页面与权限访问控制

五SpringSecurity Web权限方案——自定义登录页面与权限访问控制