丢代码地址

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. css(1-1)样式表

    CSS Id 和 Class id 和 class 选择器 如果你要在HTML元素中设置CSS样式,你需要在元素中设置"id" 和 "class"选择器. id ...

  2. SpringCloud的服务网关zuul

    演示如何使用api网关屏蔽各服务来源 一.概念和定义 1.zuul最终还是使用Ribbon的,顺便测试一下Hystrix断路保护2.zuul也是一个EurekaClient,访问服务注册中心,获取元数 ...

  3. Python之IO模型

    IO模型介绍 为了更好地了解IO模型,我们需要事先回顾下:同步.异步.阻塞.非阻塞 同步(synchronous) IO和异步(asynchronous) IO,阻塞(blocking) IO和非阻塞 ...

  4. jenkins创建pipeline

    新建任务的时候,有两个流水线相关的任务类型,如下图.其中:流水线更加针对单主干模式的开发,在主干目录下放一个Jenkinsfile文件,其中该文件保存了从SCM拉代码.构建.测试.发布等等流程. 而M ...

  5. 27.C++- 智能指针

    智能指针 在C++库中最重要的类模板之一 智能指针实际上是将指针封装在一个类里,通过对象来管理指针. STL中的智能指针auto_ptr 头文件: <memory> 生命周期结束时,自动摧 ...

  6. Python系列-python内置函数

    abs(x) 返回数字的绝对值,参数可以是整数.也可以是浮点数.如果是复数,则返回它的大小 all(iterable) 对参数中的所有元素进行迭代,如果所有的元素都是True,则返回True,函数等价 ...

  7. SpringBoot(四):banner的控制

    banner在springboot中是一个支持可配(banner的样式,banner的颜色,banner的内容).是否显示. 1)banner显示内容配置: 默认springboot如果在src/re ...

  8. Struts(九):值栈(OGNL)

    引言 在我们开发过程中,往往会使用一个对像传递到一个具体的action中,之后到跳转页面中访问对应对象的具体的参数. 比如:我们搭建一个struts2项目: 回顾下如何搭建strut2: 1.下载的s ...

  9. 0415关于通过FILEBEAT,LOGSTASH,ES,KIBNA实现数据的采集

    如何通过FILEBEAT,LOGSTASH,ES,KIBNA实现数据的采集总体参考网址:https://www.olinux.org.cn/elk/1157.html官方网址:https://www. ...

  10. ubuntu临时修改ip,mac的方法示例

    ifconfig eth0 down ifconfig eth0 154.84.28.148 netmask 255.255.255.0 route add default gw 154.84.28. ...