(十三)springboot实战——springboot前后端分离方式项目集成spring securtity安全框架

news/2024/12/22 23:49:40/

前言

Spring Security 是一款强大且高度可定制的认证和访问控制框架,它是为了保护基于Spring的应用程序提供安全性支持。Spring Security提供了全面的安全服务,主要针对企业级应用程序的需求。其核心组件主要包含:Authentication(认证)、Authorization(授权)、Principal(主体)、Granted Authority(授予的权限)、Security Context(安全上下文),可提供方法级别的权限认证。其底层主要通过Filter拦截器实现,关于其实现原理,我们会在后面的章节内容中介绍。

本节内容主要是关于前后端分离的项目如何集成spring securtity安全框架,完成用户的认证与授权。也会详细介绍各个配置项及配置组件的使用。

正文

①创建一个springboot web项目,引入spring security的依赖,同时引入mysql和mybatis-plus依赖,用于实现一个数据库版本的spring security安全框架


<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.22</version>
</dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.4</version>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope>
</dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>

 ②在application.yml中添加数据库配置,用于连接数据库

spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://192.168.110.88:3306/ht-atp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useAffectedRows=true&nullCatalogMeansCurrent=trueusername: rootpassword: root
server:port: 8080

③ 创建一张用户数据库表auth_user,用于存储用户信息

CREATE TABLE `auth_user` (`id` int NOT NULL AUTO_INCREMENT,`username` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL,`password` varchar(500) COLLATE utf8mb4_general_ci DEFAULT NULL,`enabled` tinyint(1) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

④创建用户实体AuthUser 

@Data
public class AuthUser {@TableId(value = "id", type = IdType.AUTO)private Integer id;private String username;private String password;private Boolean enabled;}

 ⑤创建用户持久层Mapper

package com.yundi.atp.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yundi.atp.entity.AuthUser;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface AuthUserMapper extends BaseMapper<AuthUser> {}

⑥统一响应请求返回定义

package com.yundi.atp.commom;import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;@Data
@Builder
public class ApiResponse<T> {@Schema(name = "code", description = "状态码")private Integer code;@Schema(name = "msg", description = "消息结果")private String msg;@Schema(name = "data", description = "数据")private T data;/*** 成功统一响应格式** @param* @param <T>* @return*/public static <T> ApiResponse<T> success() {ApiResponse<T> apiResponse = new ApiResponse<>(200, "成功", null);return apiResponse;}/*** 成功统一响应格式** @param* @param <T>* @return*/public static <T> ApiResponse<T> success(String msg) {ApiResponse<T> apiResponse = new ApiResponse<>(200, msg, null);return apiResponse;}/*** 成功统一响应格式** @param data* @param <T>* @return*/public static <T> ApiResponse<T> success(T data) {ApiResponse<T> apiResponse = new ApiResponse<>(200, "成功", data);return apiResponse;}/*** 成功统一响应格式** @param data* @param <T>* @return*/public static <T> ApiResponse<T> success(String msg, T data) {ApiResponse<T> apiResponse = new ApiResponse<>(200, msg, data);return apiResponse;}/*** 失败统一响应格式** @param code* @param message* @param <T>* @return*/public static <T> ApiResponse<T> fail(Integer code, String message) {return new ApiResponse<>(code, message, null);}/*** 失败统一响应格式** @param errorCode* @param <T>* @return*/public static <T> ApiResponse<T> fail(ErrorCode errorCode) {return new ApiResponse<>(errorCode.getCode(), errorCode.getMsg(), null);}
}

⑦ 统一错误码定义

package com.yundi.atp.commom;public enum ErrorCode {SYSTEM_ERROR(10000, "系统错误!"),UN_AUTH(10001, "用户未认证,请先登录!"),AUTH_FAILURE(10002, "认证失败,用户名或密码错误!"),UN_ACCESS(10003, "该用户没有此操作权限!"),METHOD_ARGS_VALID(10004, "方法参数验证失败!"),TOKEN_VALID(10005, "token鉴权失败!"),TOKEN_NOT_EXIST(10006, "token不存在!"),;private Integer code;private String msg;ErrorCode(Integer code, String message) {this.code = code;this.msg = message;}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}
}

⑧创建DbUserDetailsManager类实现UserDetailsManager和UserDetailsPasswordService接口方法,用于实现数据库版本的认证权限管理,该类主要是实现用户数据和权限数据的获取,用于认证和授权使用

package com.yundi.atp.auth;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yundi.atp.entity.AuthUser;
import com.yundi.atp.mapper.AuthUserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;@Service
public class DbUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {@Resourceprivate AuthUserMapper authUserMapper;@Overridepublic UserDetails updatePassword(UserDetails user, String newPassword) {return null;}@Overridepublic void createUser(UserDetails userDetails) {AuthUser authUser = new AuthUser();authUser.setUsername(userDetails.getUsername());authUser.setPassword(userDetails.getPassword());authUser.setEnabled(true);authUserMapper.insert(authUser);}@Overridepublic void updateUser(UserDetails user) {}@Overridepublic void deleteUser(String username) {}@Overridepublic void changePassword(String oldPassword, String newPassword) {}@Overridepublic boolean userExists(String username) {return false;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//查询用户数据QueryWrapper<AuthUser> queryWrapper = new QueryWrapper<>();queryWrapper.eq("username", username);AuthUser authUser = authUserMapper.selectOne(queryWrapper);if (authUser == null) {throw new UsernameNotFoundException(username);} else {//从数据库获取用户权限列表Collection<GrantedAuthority> authorities = new ArrayList<>();authorities.add(() -> "USER_LIST");authorities.add(() -> "USER_ADD");return new User(//用户账号authUser.getUsername(),//用户密码authUser.getPassword(),//是否启用authUser.getEnabled(),//用户账号是否过期true,//用户凭证是否过期true,//用户是否未被锁定true,//权限列表authorities);}}
}

⑨创建MyAuthenticationEntryPoint类实现AuthenticationEntryPoint接口,用于未认证的处理

package com.yundi.atp.auth;import com.alibaba.fastjson.JSON;
import com.yundi.atp.commom.ApiResponse;
import com.yundi.atp.commom.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Slf4j
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {log.info("未认证:" + authException);//返回响应response.setContentType("application/json;charset=UTF-8");response.getWriter().println(JSON.toJSONString(ApiResponse.fail(ErrorCode.UN_AUTH)));}
}

 ⑩创建MyAuthenticationSuccessHandler类实现AuthenticationSuccessHandler接口,用于认证成功的处理

package com.yundi.atp.auth;import com.alibaba.fastjson.JSON;
import com.yundi.atp.commom.ApiResponse;
import com.yundi.atp.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {AuthenticationSuccessHandler.super.onAuthenticationSuccess(request, response, chain, authentication);}@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {//返回响应response.setContentType("application/json;charset=UTF-8");response.getWriter().println(JSON.toJSONString(ApiResponse.success("认证成功!")));}
}

⑪创建MyAuthenticationFailureHandler类实现AuthenticationFailureHandler接口,用于认证失败的处理

package com.yundi.atp.auth;import com.alibaba.fastjson.JSON;
import com.yundi.atp.commom.ApiResponse;
import com.yundi.atp.commom.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {response.setContentType("application/json;charset=UTF-8");response.getWriter().println(JSON.toJSONString(ApiResponse.fail(ErrorCode.AUTH_FAILURE)));}
}

⑫创建MyLogoutSuccessHandler类实现LogoutSuccessHandler接口,用于退出登录的处理

package com.yundi.atp.auth;import com.alibaba.fastjson.JSON;
import com.yundi.atp.commom.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Slf4j
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {@Overridepublic void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {response.setContentType("application/json;charset=UTF-8");response.getWriter().println(JSON.toJSONString(ApiResponse.success("注销成功!")));}
}

⑬创建MyAccessDeniedHandler类实现AccessDeniedHandler接口,用于授权不通过的处理

package com.yundi.atp.auth;import com.alibaba.fastjson.JSON;
import com.yundi.atp.commom.ApiResponse;
import com.yundi.atp.commom.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {response.setContentType("application/json;charset=UTF-8");response.getWriter().println(JSON.toJSONString(ApiResponse.fail(ErrorCode.UN_ACCESS)));}
}

⑭创建spring security的配置类,开启spring security认证以及方法级别的授权

package com.yundi.atp.config;import com.yundi.atp.auth.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.web.SecurityFilterChain;@EnableMethodSecurity
@Configuration
public class SpringSecurityConfig {@Autowiredprivate DbUserDetailsManager dbUserDetailsManager;@Beanpublic AuthenticationManager authenticationManager() {DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();authenticationProvider.setUserDetailsService(dbUserDetailsManager);authenticationProvider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());return new ProviderManager(authenticationProvider);}@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {//authorizeRequests():开启授权保护//anyRequest():对所有请求开启授权保护//authenticated():已认证请求会自动被授权http.authorizeRequests(authorize -> {//放行路径authorize.antMatchers("/webjars/**", "/v3/**", "/doc.html", "/favicon.ico", "/swagger-ui/**").permitAll();//其它请求需要认证authorize.anyRequest().authenticated();});//自定义登录http.formLogin(formLogin -> {formLogin.loginPage("/login").permitAll() //登录页面无需授权即可访问.usernameParameter("username") //自定义表单用户名参数,默认是username.passwordParameter("password");//自定义表单密码参数,默认是password//登录认证成功formLogin.successHandler(new MyAuthenticationSuccessHandler());//登录认证失败formLogin.failureHandler(new MyAuthenticationFailureHandler());});// 基本授权方式http.httpBasic(Customizer.withDefaults());//自定义注销http.logout(logout -> {logout.logoutUrl("/logout");//删除授权信息logout.clearAuthentication(true);//删除cookielogout.deleteCookies("JSESSIONID");//设置session失效logout.invalidateHttpSession(true);//退出的处理logout.addLogoutHandler(new MyLogoutHandler());//退出成功的响应logout.logoutSuccessHandler(new MyLogoutSuccessHandler());});//错误处理http.exceptionHandling(exception -> {//请求未认证的接口exception.authenticationEntryPoint(new MyAuthenticationEntryPoint());//未授权的接口异常处理:可能会不生效,被全局异常处理器拦截exception.accessDeniedHandler(new MyAccessDeniedHandler());});// 跨域http.cors(Customizer.withDefaults());//关闭csrf攻击防御http.csrf(csrf -> {csrf.disable();});return http.build();}}

⑮spring security的配置说明

1.开启方法级别的权限验证

2.注入自定义的数据库版本的授权管理器

3.放行不需要认证的路径

4.配置登录的认证及认证处理

5.配置基本的授权方式

6.配置用户注销的处理

7.异常的处理

8.跨域的处理

9.关闭csrf攻击防御

⑯使用PasswordEncoderFactories工厂生成一个spring security的密码,创建一个用户用户测试

⑰访问未认证的请求

⑱使用正确的用户名和密码访问登录接口/login,注意这里必须是post请求

⑲使用错误的用户名和密码访问登录接口/login,注意这里必须是post请求

⑳测试接口授权,目前的权限包含USER_LIST、USER_ADD,在DbUserDetailsManager中查询的

㉑访问/logout注销接口,查看结果

结语

关于springboot前后端分离方式项目集成spring securtity安全框架的内容到这里就结束了,我们下期见。。。。。。


http://www.ppmy.cn/news/1350445.html

相关文章

Days 23 ElfBoard 板git版本管理工具

一、 介绍 git 就是一个版本管理库&#xff0c;也是一个版本管理工具&#xff0c;它的作用就是帮助我们记录版本信息&#xff0c;以及修改内容。git 的结构是分布式的资源库&#xff0c;特点是没有严格的服务器概念&#xff0c;每个单体都可作为资源库。这个特点就让我们人人有…

【案例】--分布式”雪花算法案例

目录 一、前言二、技术方案实现2.1、技术方案实现12.2、技术方案实现2三、存在的问题3.1、kygoException异常问题3.2、redis随机命令被禁止问题四、完整的“分布式雪花算法”代码一、前言 前段时间线上系统出现一个严重的bug:一个表中插入两条一样的id记录信息(该字段未设置唯…

ansible shell模块 可以用来使用shell 命令 支持管道符 shell 模块和 command 模块的区别

这里写目录标题 说明shell模块用法shell 模块和 command 模块的区别 说明 shell模块可以在远程主机上调用shell解释器运行命令&#xff0c;支持shell的各种功能&#xff0c;例如管道等 shell模块用法 ansible slave -m shell -a cat /etc/passwd | grep root # 可以使用管道…

鸿蒙系统进一步学习(一):学习资料总结,少走弯路

随着鸿蒙Next的计划越来越近&#xff0c;笔者之前的鸿蒙系统扫盲系列中&#xff0c;有很多朋友给我留言&#xff0c;不同的角度的问了一些问题&#xff0c;我明显感觉到一点&#xff0c;那就是许多人参与鸿蒙开发&#xff0c;但是又不知道从哪里下手&#xff0c;因为资料太多&a…

Stable Diffusion 模型下载:majicMIX fantasy 麦橘幻想

本文收录于《AI绘画从入门到精通》专栏,专栏总目录:点这里。 文章目录 模型介绍生成案例案例一案例二案例三案例四案例五案例六案例七案例八案例九案例十

面试经典150题——长度最小的子数组

​"In the midst of winter, I found there was, within me, an invincible summer." - Albert Camus 1. 题目描述 2. 题目分析与解析 首先理解题意&#xff0c;题目要求我们找到一个长度最小的 连续子数组 满足他们的和大于target&#xff0c;需要返回的是子数组的…

202209CSPT4吉祥物投票

题意&#xff1a;有 n n n个人对 m m m件作品投票,有 q q q个操作&#xff1a; 1 : 1: 1:编号为 [ L , R ] [L,R] [L,R]人投票给 x x x号作品 2 : 2: 2:投给 x x x号的人将票转投给 w w w号作品 3 : x , w 3:x,w 3:x,w号作品票数交换 4 : 4: 4:输出 x x x号作品票数 5 : 5…

Linux(Ubuntu)环境下安装卸载Python3(避免踩坑)

一、安装 第一步&#xff1a; 进入/usr/local/目录&#xff0c;下载Python3&#xff0c;这里我下载的是python 3.8.10&#xff0c;如果要下载其他版本改下链接中的版本号&#xff0c;需与官网版本号对应。 wget https://www.python.org/ftp/python/3.8.10/Python-3.8.10.tgz第…