前言
最近公司做项目用了若依框架,里面用到了SpringSecurity和JWT,对此技术不甚了解,于是就专门的找视频学习了一下,顺便记录一下自己的学习过程,方便加深记忆。
一、引入jar包
我们创建一个SpringBoot项目当我没有引入SpringSecurity的时候我们访问hello接口是正常访问的。
@RestController
public class TestController {
@RequestMapping("/hello")
public String hello(){
return "Hello World";
}
}
我们现在引入SpringSecurity试试,在pox.xml里面引入jar包
<!--spring security安全认证-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
我们重启项目访问一下,发现一个问题,就是浏览器跳到了一个登录页面,因为SpringSecurity里面有过滤器,他把所有的路径资源都设置成必须验证才能访问,否则跳到登录页面。
这个登录页面是SpringSecurity内部默认的。那我们登陆一下,用户名是user,密码是项目启动时idea的日志里Using generated security password后面的一串字符。
当然我们为了测试,可以在配置文件里加上
spring.security.user.name=root
spring.security.user.password=123
spring.security.user.roles=admin,super
来更改一下用户名和密码
点击Sign In按钮,就会出现我们期望的Hello World了。
二、配置路径权限
那现在问题来了,所有的接口路径都被拦截了,这可不行啊,因为我们每个项目都有一些路径是不需要登录验证就可以访问的,那我们怎么放开这些路径呢?
我们自定义一个config类,然后继承WebSecurityConfigurerAdapter,重写里面的configure方法。
permitAll表示无论是否认证都可以访问,authenticated表示需要认证才可以访问,还有一个anonymous表示匿名可以访问,anyRequest().authenticated()表示除了上面的hello其他所有路径都是需要认证的(注意:anyRequest().authenticated()要放在其他路径配置的下面)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/hello").permitAll()
.anyRequest().authenticated();
}
}
我们重新启动项目访问浏览器,很明显这次我们不需要登录就得到了我们想要的。
代码下载:代码下载地址
提取码:xxgz
结束语
下一篇我们试试自定义登录页面,毕竟官方的登录页面太简单了,也不方便改造😏。
我的个人博客地址:http://www.dbhx.vip