丢代码地址

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实现权限控制的更多相关文章

  1. Spring Boot中使用 Spring Security 构建权限系统

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...

  2. Spring Boot中使用Spring Security进行安全控制

    我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面.要实现访问控制的方法多种多样,可以通过Aop.拦截器实现,也可以通过框架实现(如:Apache ...

  3. 【swagger】1.swagger提供开发者文档--简单集成到spring boot中【spring mvc】【spring boot】

    swagger提供开发者文档 ======================================================== 作用:想使用swagger的同学,一定是想用它来做前后台 ...

  4. Spring Boot中集成Spring Security 专题

    check to see if spring security is applied that the appropriate resources are permitted: @Configurat ...

  5. Spring Boot 中使用 Spring Security, OAuth2 跨域问题 (自己挖的坑)

    使用 Spring Boot 开发 API 使用 Spring Security + OAuth2 + JWT 鉴权,已经在 Controller 配置允许跨域: @RestController @C ...

  6. spring-boot-starter-security Spring Boot中集成Spring Security

    spring security是springboot支持的权限控制系统. security.basic.authorize-mode 要使用权限控制模式. security.basic.enabled ...

  7. Spring Boot 中应用Spring data mongdb

    摘要 本文主要简单介绍下如何在Spring Boot 项目中使用Spring data mongdb.没有深入探究,仅供入门参考. 文末有代码链接 准备 安装mongodb 需要连接mongodb,所 ...

  8. spring boot中扩展spring mvc 源码分析

    首先,确认你是对spring boot的自动配置相关机制是有了解的,如果不了解请看我spring boot相关的源码分析. 通常的使用方法是继承自org.springframework.boot.au ...

  9. Spring boot后台搭建二集成Shiro权限控制

    上一篇文章,实现了用户验证 查看,接下来实现下权限控制 权限控制,是管理资源访问的过程,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等 Apache Shir ...

随机推荐

  1. Web系统Login拦截器

    所需要导入的包类:import org.springframework.web.servlet.HandleInterceptor;(拦截器要继承该类) public class loginInter ...

  2. css3兼容IE8的方案 各个ie的hack

    虽然现在很多项目已经对低版本IE不要求了,但是还有部分公司对IE8还是很执着的,咱作为屌丝前端程序员不能和老板说前端潮流,不能说趋势,只能动脑子了,下面就分享一些css3兼容ie8的方案思路.主要是实 ...

  3. Object.defineProperties()和Object.defineProperty()方法

    Object.defineProperty() 方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性, 并返回这个对象. 语法:Object.defineProperty(obj, pro ...

  4. Python入门之函数的装饰器

    本章目录: 装饰器: 一.为什么要用装饰器 二.什么是装饰器 三.无参装饰器 四.装饰器语法糖 五.认证装饰器实现 六.叠加多个装饰器 七.带参装饰器 ======================== ...

  5. centos单机安装zookeeper+kafaka

    环境如下: CentOS-7-x86_64zookeeper-3.4.11kafka_2.12-1.1.0 一.zookeeper下载与安装1)下载zookeeper [root@localhost ...

  6. Java-Maven(五):Eclipse&Maven下创建java工程&web工程

    本章文章主要学习集成了maven插件的eclipse下,创建java project和web project的步骤. 创建java工程  第一步:使用使用maven project来创建java pr ...

  7. CNN中减少网络的参数的三个思想

    CNN中减少网络的参数的三个思想: 1) 局部连接(Local Connectivity) 2) 权值共享(Shared Weights) 3) 池化(Pooling) 局部连接 局部连接是相对于全连 ...

  8. 【原创】公司各个阶段 CTO 需要做什么?(下篇)

    假设一个公司发展有以下几个阶段: 0 :创始阶段: 0.5 :有产品但无管理阶段: 1 :经过 1年的发展初步稳定的阶段: 1+ :稳步发展阶段. 上一篇文章中,我们聊了公司在初创阶段,CTO 需要做 ...

  9. Linux 定时执行shell脚本命令之crontab

    crontab可以在指定的时间执行一个shell脚本以及执行一系列Linux命令 例如:服务器管理员定时备份数据库数据.日志等 详解: 常用命令: crontab –e //修改 crontab 文件 ...

  10. JavaScript push() 方法

    定义和用法: push() :可向数组的末尾添加一个或多个元素,并返回新的长度. 语法 arrayObject.push(newelement1,newelement2,....,newelement ...