十二、SpringBoot 优雅的集成Spring Security

至于什么是Spring security ,主要两个作用,用户认证和授权。即我们常说的,用户只有登录了才能进行其他操作,没有登录的话就重定向到登录界面。有的用户有权限执行某一操作,而有的用户不能执行则是授权。算是一个项目安全框架。和shiro 框架一样。二者的不同大家可以百度小。Spring security 是Spring家族的一员,所以Springboot算是对Spring security 进行的天然的支持。

之所以这样说,spring security 被人诟病的配置繁琐复杂,在springboot中变的简单起来。如果我们只是demo 效果,可以做到0配置实现。

下面我们就一起来见识一下吧

依赖

我们在pom.xml 文件中引入Spring security 的statter

<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> 测试

我们先来0配置的看看。引入依赖以后,我们创建一个HelloController 内容如下:

@RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return "hello world"; } }

在这里插入图片描述


然后我们启动项目,按照我们正常的理解,直接访问

localhost:8080/hello

会返回hello world 。但结果却是重定向到了/login 。下面的界面是Spring security 自带的。

在这里插入图片描述


其实上面可以看到,Spring security 已经起作用了,没有登录不能访问 /hello 接口。

默认的用户名为 user;
密码在我们项目启动时控制台有打印,每次都会不一样,随机生成的。

在这里插入图片描述


我们输入账号密码,再试试

在这里插入图片描述


可以看到,在登录之后,我们在请求 /hello 会直接返回hello world , 那是不是只要登录一次,后面就可以一直访问呢?当然不是的,登录成功之后,会将信息保存在session 中,再登录的时候,就会通过session 校验,这样就可以访问到了,当session过期获取我们手动清理掉后,就需要重新登录了。我们来试试。打开控制台,application 中的cookies 中的jsessionid 清理掉。

在这里插入图片描述


我们接着请求试试,可以发现删除后,就会重新回到登录界面。

在这里插入图片描述

简单配置用户和密码

上面我们使用的默认的用户名和密码,但是实际上我们肯定不会这么做的,上面只是说明springboot 完全的集成了Spring security 。下面我们先来简单的配置用户名密码,之所以这样说,因为我们实际过程中应该还是不会这么用的。之所以要讲,让大家了解的更全面,也为下面铺垫。

application.properties 中配置

首先我们来简单的,我们可以直接在application.properties 中配置用户名和密码。来代替默认用户名和密码的效果。

spring.security.user.name=quellanan spring.security.user.password=123456 spring.security.user.roles=admin

分别是设置用户名,密码,角色。我们这里暂时只用了用户认证,所以角色设不设置无所谓。配置好这些之后我们重启项目在界面上试试再。

在这里插入图片描述


没有问题,但是没有什么用,我们实际中是不会这么干的吧。

内存中配置

在内存中配置的话,相对来说要复杂点,我们创建一个config 包,在包下创建SecurityConfig 类继承 WebSecurityConfigurerAdapter

@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .passwordEncoder(passwordEncoder()) // 指定加密方式 .withUser("qaz").password(passwordEncoder().encode("123456")).roles("admin") .and() .withUser("test").password(passwordEncoder().encode("123456")).roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { // BCryptPasswordEncoder:Spring Security 提供的加密工具 return new BCryptPasswordEncoder(); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zydwzy.html