在Spring Boot中使用Spring Security实现权限控制
丢代码地址
https://gitee.com/a247292980/spring-security
再丢pom.xml
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
最后放个代码结构图
开讲
WebSecurityConfig
spring sercurity的设置。
要有一个实现了UserDetailsService的bean,我的是CustomUserService。
之后,重写两个configure的方法。
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(customUserService());
} /**
* 1.首先当我们要自定义Spring Security的时候我们需要继承自WebSecurityConfigurerAdapter来完成,相关配置重写对应 方法即可。
* 2.我们在这里注册CustomUserService的Bean,然后通过重写configure方法添加我们自定义的认证方式。
* 3.在configure(HttpSecurity http)方法中,我们设置了登录页面,而且登录页面任何人都可以访问,然后设置了登录失败地址,也设置了注销请求,注销请求也是任何人都可以访问的。
* 4.permitAll表示该请求任何人都可以访问,.anyRequest().authenticated(),表示其他的请求都必须要有权限认证。
* 5.这里我们可以通过匹配器来匹配路径,比如antMatchers方法,假设我要管理员才可以访问admin文件夹下的内容,我可以这样来写:.
* antMatchers("/admin/**").hasRole("ROLE_ADMIN"),也
* 可以设置admin文件夹下的文件可以有多个角色来访问,写法如下:
* .antMatchers("/admin/**").hasAnyRole("ROLE_ADMIN","ROLE_USER")
* 6.可以通过hasIpAddress来指定某一个ip可以访问该资源,假设只允许访问ip为210.210.210.210的请求获取admin下的资源,写法如下.a
* ntMatchers("/admin/**").hasIpAddress("210.210.210.210")
*/
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
// 留意代码顺序
// 首页(不需要登陆就能访问的页面
.antMatchers("/index").permitAll()
.anyRequest().authenticated()
// 需要登陆才能访问的页面
.and().formLogin().loginPage("/login").defaultSuccessUrl("/index").failureUrl("/login?error").permitAll()
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll()
.and().rememberMe().tokenValiditySeconds(60 * 60 * 24 * 7).key("kkkkkkkk");
}
HomeController,BaseEntity,Msg,SysRole
不用多说了,简单的mvc
SysUser
要实现UserDetails接口,重写getAuthorities方法。
里面有个@ManyToMany,虽然代码不配置也行,但这是将两个表关联起来的逻辑。
@Entity
public class SysUser extends BaseEntity implements UserDetails {
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
/**
* CascadeType.REFRESH:级联刷新,当多个用户同时作操作一个实体,为了用户取到的数据是实时的,
* 在用实体中的数据之前就可以调用一下refresh()方法!
* FetchType.EAGER:急加载,立即从数据库中加载
*/
@ManyToMany(cascade = {CascadeType.REFRESH}, fetch = FetchType.EAGER)
private List<SysRole> roles; public void setId(Long id) {
this.id = id;
} public Long getId() {
return this.id;
} public void setUsername(String username) {
this.username = username;
} @Override
public String getUsername() {
return this.username;
} public void setPassword(String password) {
this.password = password;
} @Override
public String getPassword() {
return this.password;
} public void setRoles(List<SysRole> roles) {
this.roles = roles;
} public List<SysRole> getRoles() {
return this.roles;
} @Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
List<SysRole> sysRoleList = this.getRoles();
for (SysRole sysRole : sysRoleList) {
grantedAuthorityList.add(new SimpleGrantedAuthority(sysRole.getName()));
}
return grantedAuthorityList;
} @Override
public boolean isAccountNonExpired() {
return true;
} @Override
public boolean isAccountNonLocked() {
return true;
} @Override
public boolean isCredentialsNonExpired() {
return true;
} @Override
public boolean isEnabled() {
return true;
}
}
SysUserRepository
spring-jpa的简单应用
CustomUserService
实现loadUserByUsername的方法,就是传说中的认证方法了,为啥不叫authorize啊?这名字太low了吧。
SpringSecurityApplication
不懂这个的,没关系新建spring boot自带的。
在Spring Boot中使用Spring Security实现权限控制的更多相关文章
- Spring Boot中使用 Spring Security 构建权限系统
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...
- Spring Boot中使用Spring Security进行安全控制
我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面.要实现访问控制的方法多种多样,可以通过Aop.拦截器实现,也可以通过框架实现(如:Apache ...
- 【swagger】1.swagger提供开发者文档--简单集成到spring boot中【spring mvc】【spring boot】
swagger提供开发者文档 ======================================================== 作用:想使用swagger的同学,一定是想用它来做前后台 ...
- Spring Boot中集成Spring Security 专题
check to see if spring security is applied that the appropriate resources are permitted: @Configurat ...
- Spring Boot 中使用 Spring Security, OAuth2 跨域问题 (自己挖的坑)
使用 Spring Boot 开发 API 使用 Spring Security + OAuth2 + JWT 鉴权,已经在 Controller 配置允许跨域: @RestController @C ...
- spring-boot-starter-security Spring Boot中集成Spring Security
spring security是springboot支持的权限控制系统. security.basic.authorize-mode 要使用权限控制模式. security.basic.enabled ...
- Spring Boot 中应用Spring data mongdb
摘要 本文主要简单介绍下如何在Spring Boot 项目中使用Spring data mongdb.没有深入探究,仅供入门参考. 文末有代码链接 准备 安装mongodb 需要连接mongodb,所 ...
- spring boot中扩展spring mvc 源码分析
首先,确认你是对spring boot的自动配置相关机制是有了解的,如果不了解请看我spring boot相关的源码分析. 通常的使用方法是继承自org.springframework.boot.au ...
- Spring boot后台搭建二集成Shiro权限控制
上一篇文章,实现了用户验证 查看,接下来实现下权限控制 权限控制,是管理资源访问的过程,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等 Apache Shir ...
随机推荐
- Python内置函数(49)——isinstance
英文文档: isinstance(object, classinfo) Return true if the object argument is an instance of the classin ...
- GIT入门笔记(15)- 链接到私有GitLab仓库
GitLab是利用 Ruby on Rails 一个开源的版本管理系统,实现一个自托管的Git项目仓库,可通过Web界面进行访问公开的或者私人项目.它拥有与Github类似的功能,能够浏览源代码,管理 ...
- C# 客户端程序调用外部程序的三种实现
简介 我们用C#来开发客户端程序的时候,总会不可避免的需要调用外部程序或者访问网站,本篇博客介绍了三种调用外部应用的方法,供参考 实现 第一种是利用shell32.dll,实现ShellExecute ...
- mybatis的generator中xml配置问题
<!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="com.sung.risk.model.biz" t ...
- H5 仿ios select滚动选择器。框架。
官网上描述的很详细,并且开源,轻量. 有兴趣的可以去尝试官网上的demo写的也很好,并且每个参数也解释的很详细. http://zhoushengfe.com/iosselect/website/in ...
- hdu1087 Super Jumping! Jumping! Jumping!---基础DP---递增子序列最大和
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1087 题目大意: 求递增子序列最大和 思路: 直接dp就可以求解,dp[i]表示以第i位结尾的递增子 ...
- LinkedHashMap简明
LinkedHashMap 构造方法摘要 inkedHashMap() 构造一个带默认初始容量 (16) 和加载因子 (0.75) 的空插入顺序LinkedHashMap 实例. LinkedHash ...
- Spring(5)——Spring 和数据库编程
传统 JDBC 回顾 JDBC 我们一定不陌生,刚开始学习的时候,我们写过很多很多重复的模板代码: public Student getOne(int id) { String sql = " ...
- Extensions in UWP Community Toolkit - ListViewExtensions
概述 UWP Community Toolkit Extensions 中有一个为 ListView 提供的扩展 - ListViewExtensions,本篇我们结合代码详细讲解 ListView ...
- Spring-cloud(二)注册服务提供者搭建
上文已经写了如何去搭建注册中心,仅有注册中心是远远不够的,所以我们需要注册到注册中心并提供服务的节点,这里称为注册服务提供者 前提 阅读上文,并成功搭建注册中心,环境无需改变 项目搭建 这里我们需要新 ...