前言

即访问控制,控制设能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某资源没有权限是无法访问的


一、导入坐标

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zsh</groupId>
<artifactId>springsecurity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springsecurity</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

二、Users实体类及其数据库表的创建

@Data
public class Users { private int id;
private String username;
private String password;
}

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springsecurity?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin

三、controller,service,mapper层的实现

package com.zsh.security.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* @author:抱着鱼睡觉的喵喵
* @date:2021/3/12
* @description:
*/
@RestController
@RequestMapping("/test")
public class SecurityController { @RequestMapping("/hello")
public String hello() { return "hello! Spring Security!";
} @RequestMapping("/index")
public String index() {
return "hello index!";
}
}
package com.zsh.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsh.security.mapper.UserMapper;
import com.zsh.security.pojo.Users;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service; import java.util.List; /**
* @author:抱着鱼睡觉的喵喵
* @date:2021/3/12
* @description:
*/
@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper; @Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username", s);
Users users = userMapper.selectOne(wrapper);
if (users == null) {//
throw new UsernameNotFoundException("账号或密码错误!");
} else {//表示有user角色权限
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_user");
return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
} }
}
package com.zsh.security.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsh.security.pojo.Users;
import org.springframework.stereotype.Repository; /**
* @author:抱着鱼睡觉的喵喵
* @date:2021/3/12
* @description:
*/
@Repository
public interface UserMapper extends BaseMapper<Users> { }

四、核心–编写配置文件

package com.zsh.security.config;

import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; /**
* @author:抱着鱼睡觉的喵喵
* @date:2021/3/12
* @description:
*/
@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter { @Autowired
private UserDetailsService userDetailsService; @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
} @Override
protected void configure(HttpSecurity http) throws Exception {
//没有权限时跳转到403界面(无权限界面)
http.exceptionHandling().accessDeniedPage("/noauth.html");
http.formLogin()
.loginPage("/login.html") //设置登录界面
.loginProcessingUrl("/user/login") //登录界面url
.defaultSuccessUrl("/test/index").permitAll() //默认登录成功界面
.and().authorizeRequests() //哪些资源可以直接访问
.antMatchers("/","/test/hello","/user/loin").permitAll() //不做处理
//.antMatchers("/test/index").hasAuthority("admin")
// .antMatchers("/test/index").hasAnyAuthority("admin","manager")
//.antMatchers("/test/index").hasRole("admin")
.antMatchers("/test/index").hasAnyRole("admin","user")
.anyRequest().authenticated() //所有请求都可以访问
.and().csrf().disable(); //关闭CSRF
} @Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
} }

分析核心的四个方法(其中给予某个角色权限在service层实现)
1、hasAuthority:是否有某个权限
2、hasAnyAuthority:是否拥有其中一个权限
3、hasRole:是否拥有某个角色
4、hasAnyRole:是否拥有其中一个角色

关于hasAuthority、hasAnyAuthority与hasRole、hasAnyRole的区别:
本质上没有什么区别,只不过是设计的维度不同(角色是权限的集合)
根据底层可以得出,如果要使用hasRole和hasAnyRole必须在service层加上ROLE_的前缀


五、无权限界面和登录界面的实现

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/user/login" method="post">
username:<input type="text" name="username"> <br>
password:<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a style="background-color: red; margin-top: 100px; margin-left: 100px">no auth</a>
</body>
</html>

springboot+springsecurity+mybatis plus之用户授权的更多相关文章

  1. springboot+springsecurity+mybatis plus之用户认证

    一.权限管理的概念 另一个安全框架shiro:shiro之权限管理的描述 导入常用坐标 <dependency> <groupId>org.springframework.bo ...

  2. springboot+springsecurity+mybatis plus注解实现对方法的权限处理

    文章目录 接上文 [springboot+springsecurity+mybatis plus之用户授权](https://blog.csdn.net/Kevinnsm/article/detail ...

  3. SpringBoot+SpringSecurity之多模块用户认证授权同步

    在之前的文章里介绍了SpringBoot和SpringSecurity如何继承.之后我们需要考虑另外一个问题:当前微服务化也已经是大型网站的趋势,当我们的项目采用微服务化架构时,往往会出现如下情况: ...

  4. springBoot+springSecurity 数据库动态管理用户、角色、权限

    使用spring Security3的四种方法概述 那么在Spring Security3的使用中,有4种方法: 一种是全部利用配置文件,将用户.权限.资源(url)硬编码在xml文件中,已经实现过, ...

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

    序: 本文使用springboot+mybatis+SpringSecurity 实现数据库动态的管理用户.角色.权限管理 本文细分角色和权限,并将用户.角色.权限和资源均采用数据库存储,并且自定义滤 ...

  6. 基于SpringBoot+SpringSecurity+mybatis+layui实现的一款权限系统

    这是一款适合初学者学习权限以及springBoot开发,mybatis综合操作的后台权限管理系统 其中设计到的数据查询有一对一,一对多,多对多,联合分步查询,充分利用mybatis的强大实现各种操作, ...

  7. SpringBoot整合MyBatis完成添加用户

    怎么创建项目就不说了,可以参考:https://www.cnblogs.com/braveym/p/11321559.html 打开本地的mysql数据库,创建表 CREATE TABLE `user ...

  8. SpringBoot + SpringSecurity + Mybatis-Plus + JWT实现分布式系统认证和授权

    1. 简介   Spring Security是一个功能强大且易于扩展的安全框架,主要用于为Java程序提供用户认证(Authentication)和用户授权(Authorization)功能.    ...

  9. 基于SpringSecurity和JWT的用户访问认证和授权

    发布时间:2018-12-03   技术:springsecurity+jwt+java+jpa+mysql+mysql workBench   概述 基于SpringSecurity和JWT的用户访 ...

随机推荐

  1. LGP4216题解

    这是一种题解没有的 \(O(m\log n)\) 做法. 首先第一步转化.设这是第 \(x\) 个任务,若 \(opt\) 为 \(1\),危险值大于 \(c\) 的只有可能在第 \(x-c-1\) ...

  2. HCNP Routing&Switching之组播技术-组播分发

    前文我们了解了组播技术中的igmp-snooping相关话题,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/15860484.html:今天我们来聊一聊组播技术 ...

  3. ArcMap操作随记(6)

    1.上流汇流区 [填洼]→[流向]→[分水岭] 2.输入坐标进行移动,也就是精确移动 [移动]工具(在自定义中,其中的[旋转]工具也有类似效果) 3.找最近的要素(矢量) [近邻分析]→[汇总] 4. ...

  4. XML解析与文件存取

    using System; using System.IO; using System.Text; using System.Xml; namespace XMLDemo { class Progra ...

  5. 《前端运维》一、Linux基础--06Shell流程控制

    这章我们来学习下流程控制,简单来说就是逻辑判断和循环的写法.并不复杂,我们来简单地看下. 1.if语句 shell的if语句有两种写法,一种是shell脚本式的,一种是命令式的. if conditi ...

  6. 《Mybatis 手撸专栏》第1章:开篇介绍,我要带你撸 Mybatis 啦!

    作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 1. 为甚,撸Mybatis 我就知道,你会忍不住对它下手! 21年带着粉丝伙伴撸了一遍 Sp ...

  7. [MySQL]MySQL8.0的一些注意事项以及解决方案

    MySQL8.0 注意事项以及解决方案 1. MySQL8.0 修改大小写敏感配置 天坑MySQL8.0! 在安装后, 便无法通过修改配置文件,重启服务,或者执行sql来更改数据库配置, 要想配置的话 ...

  8. Java基础——方法重写

    什么是方法重写? 子类中出现和父类中完全一样的方法声明 什么时候可以进行方法重写? 在子类需要父类的功能的同时,功能主体子类有自己的特有内容时,可以重写,一面沿袭了父类的功能一面又定义了子类特有的内容 ...

  9. Linux指令入门-系统管理(云小宝码上送祝福,免费抽iphone13任务)

    码上送祝福,带云小宝回家 做任务免费抽iphone13,还可得阿里云新春限量手办 日期:2021.12.27-2022.1.16 云小宝地址:https://developer.aliyun.com/ ...

  10. Redis+Caffeine两级缓存,让访问速度纵享丝滑

    原创:微信公众号 码农参上,欢迎分享,转载请保留出处. 在高性能的服务架构设计中,缓存是一个不可或缺的环节.在实际的项目中,我们通常会将一些热点数据存储到Redis或MemCache这类缓存中间件中, ...