SpringBoot 整合Spring Security框架
引入maven依赖
<!-- 放入spring security依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Security配置类
SecurityConfig.java
package com.example.demo.security; import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; /**
* 配置类
* @EnableWebSecurity 开启Security功能
*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //允许通过注解的方法拦截
public class SecurityConfig extends WebSecurityConfigurerAdapter { /**
* 用于密码加密
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
} /**
* 进行授权
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception{
/**
*定制请求的授权规则
* permitAll() 表示都允许访问
* hasRole("admin") 表示用户必须有admin的角色才能访问
*/ http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/add").hasRole("admin"); /**
* 开启自动配置的登录功能,如果没有权限就会来到登录页面
* 1、 /login 请求进入登录页,可自定义
* 表单的用户名name 默认为username
* 密码name 默认为 password
*
* usernameParameter 参数可以设置表单中用户名的name
* passwordParameter 参数可以设置表单中密码的name
*
* 2、重定向到/login?error 表示登录失败
* 定义登录页 /toLogin 请求
* loginProcessingUrl("") 设置登录提交的请求链接
*/
http.formLogin().
loginPage("/toLogin")
.usernameParameter("username")
.passwordParameter("pwd")
.loginProcessingUrl("/login"); /**
* 关闭csrf功能,禁用跨站请求,进行安全访问
*/
http.csrf().disable(); /**
* 开启记住我功能,登录信息保存cookie,
* 默认保存两周
* rememberMeParameter 参数设置表单中 记住我 的name名
*/
http.rememberMe().rememberMeParameter("rememberMe"); /**
* 开启自动配置的注销功能
* 1、访问 logout 表示用户注销,清空session
* 可以通过
* Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
* authentication.getPrincipal(); 获取登录用户信息
*
*
*
* 2、注销成功默认会请求 /login?logout (登录页面)
* 可以通过logoutSuccessUrl() 方法自定义退出成功后的地址
*/
http.logout().logoutSuccessUrl("/"); } /**
* 认证 springboot 2.1.x可以直接使用
* 密码编码 :passwordEncoder
* 在spring security 5.0+ 新增了加密方法
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(new UserServiceConfig());
}
}
Spring Security 查询用户信息类
UserServiceConfig.java
package com.example.demo.security; import com.example.demo.entity.CmsUser;
import com.example.demo.entity.Role;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.password.PasswordEncoder; import java.util.ArrayList;
import java.util.List; @Configuration
public class UserServiceConfig implements UserDetailsService { @Autowired
private PasswordEncoder passwordEncoder; @Autowired
private UserService userService; /**
* 根据用户名查找用户
* @param username 用户在浏览器输入的用户名
* @return UserDetails 是spring security自己的用户对象
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
CmsUser cmsUser =userService.findByUsername(username); if (cmsUser==null){
//表示查询不到用户,认证失败
return null;
} /**
* 这里为了演示进行了密码加密,实际开发中应该是用户在进行注册时就对密码进行加密,
* 这里直接取数据库的密码进行比对即可,不需要再进行加密
*/
String password=passwordEncoder.encode(cmsUser.getPassword()); /**
* 添加该用户的角色信息
* roleName 是角色名称
*/
List<SimpleGrantedAuthority> authorities=new ArrayList<>();
List<Role> roles=cmsUser.getRoles();
for (Role role:roles){
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
} return new User(cmsUser.getUsername(),password,authorities);
} }
自定义错误页面
ErrorPageConfig.java
package com.example.demo.security; import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus; /**
* 定制错误页面
*/
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar { @Override
public void registerErrorPages(ErrorPageRegistry registry) { /**
* 定制禁止访问错误页面
* /403 是错误页面的跳转请求
*/
ErrorPage errorPage=new ErrorPage(HttpStatus.FORBIDDEN,"/403"); registry.addErrorPages(errorPage); }
}
SpringBoot 整合Spring Security框架的更多相关文章
- SpringBoot整合Spring Security
好好学习,天天向上 本文已收录至我的Github仓库DayDayUP:github.com/RobodLee/DayDayUP,欢迎Star,更多文章请前往:目录导航 前言 Spring Securi ...
- springBoot整合spring security实现权限管理(单体应用版)--筑基初期
写在前面 在前面的学习当中,我们对spring security有了一个小小的认识,接下来我们整合目前的主流框架springBoot,实现权限的管理. 在这之前,假定你已经了解了基于资源的权限管理模型 ...
- springBoot整合spring security+JWT实现单点登录与权限管理--筑基中期
写在前面 在前一篇文章当中,我们介绍了springBoot整合spring security单体应用版,在这篇文章当中,我将介绍springBoot整合spring secury+JWT实现单点登录与 ...
- SpringBoot整合Spring Security使用Demo
https://start.spring.io/ 生成SpringBoot项目 pom文件应该是我这样的: <?xml version="1.0" encoding=&quo ...
- SpringBoot 整合 spring security oauth2 jwt完整示例 附源码
废话不说直接进入主题(假设您已对spring security.oauth2.jwt技术的了解,不懂的自行搜索了解) 依赖版本 springboot 2.1.5.RELEASE spring-secu ...
- SpringBoot整合Light Security框架
官方git地址:https://gitee.com/itmuch/light-security/tree/master 引入maven <dependency> <groupId&g ...
- springboot配置spring security 静态资源不能访问
在springboot整合spring security 过程中曾遇到下面问题:(spring boot 2.0以上版本 spring security 5.x (spring secur ...
- springboot+maven整合spring security
springboot+maven整合spring security已经做了两次了,然而还是不太熟悉,这里针对后台简单记录一下需要做哪些事情,具体的步骤怎么操作网上都有,不再赘述.1.pom.xml中添 ...
- SpringBoot安全篇Ⅵ --- 整合Spring Security
知识储备: 关于SpringSecurity的详细学习可以查看SpringSecurity的官方文档. Spring Security概览 应用程序的两个主要区域是"认证"和&qu ...
随机推荐
- HDU 7066 - NJU emulator(构造题)
题面传送门 提供一种不同于官方题解.需要的操作次数比官方题解多(官方题解大概是 \(2\times 16\),我这大概是 \(3\times 16\)),但能通过此题的做法. 首先我们考虑一个暴力,我 ...
- 回文字符串 Manacher
1. Manacher 忘光了,忘光了. 首先将字符串所有字符之间(包括头尾)插入相同分隔符,再在最前方插入另一个分隔符防止越界. 设以 \(s_i\) 为对称中心的回文串中,最长的回文半径为 \(p ...
- R合并数据框有重复匹配时只保留第一行
前言 合并数据框有重复匹配时通常会返回所有的匹配,如何只保留匹配的第一行呢?其实这个需求也很常见.如芯片探针ID和基因ID往往多对一,要合并ID对应矩阵和芯片表达矩阵时. 数据例子 data = da ...
- 【7】基于NGS检测体系变异解读和数据库介绍
目录 解读相关专业术语 体系变异解读规则 体系变异和用药解读流程 主要数据库介绍 解读相关专业术语 2个概念:胚系.体系突变 4种变异类型:SNV.Indel.融合/SV(大的易位/倒位/缺失).CN ...
- C++/Python冒泡排序与选择排序算法详解
冒泡排序 冒泡排序算法又称交换排序算法,是从观察水中气泡变化构思而成,原理是从第一个元素开始比较相邻元素的大小,若大小顺序有误,则对调后再进行下一个元素的比较,就仿佛气泡逐渐从水底逐渐冒升到水面一样. ...
- 我的分布式微服务框架:YC-Framework
YC-Framework官方文档:http://framework.youcongtech.com/ YC-Framework源代码:https://github.com/developers-you ...
- Spring DAO
Spring DAO 连接池 使用JDBC访问数据库是,频繁的打开连接和关闭连接,造成性能影响,所以有了连接池.数据库连接池负责分配.管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接, ...
- hadoop运行jar包报错
执行命令:[root@hadoop102 mapreduce]# hadoop jar mapreduce2_maven.jar Filter 错误信息:Exception in thread &qu ...
- 【leetcode】122.Best Time to Buy and Sell Stock II(股票问题)
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. ...
- liunux 6.5设置网卡默认开启
编辑如下文件; vi /etc/sysconfig/network-scripts/ifcfg-eth0 把 ONBOOT=no 改为 ONBOOT=yes 好了网卡会在启动机器的时候一起启动了.