spring security笔记

1.spring security的环境搭建

首先新建一个springboot项目,只够选web中的spring web依赖
img

然后在pom.xml导入相关依赖

        <!--thymeleaf模块-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

然后导入素材

项目所需要的素材我放到我的github上,需要的自取

相关security素材

导入资源并删掉多余的东西,如图
img

在application.properties配置文件里关掉thymeleaf模板缓存,以方便进行我们的测试

#关掉thymeleaf模板缓存,以方便进行我们的测试
spring.thymeleaf.cache=false

img

紧接着新建一个controller包,在包下编写一个controller类RouterController,作为我们的路由转发

img

完整代码如下:

package cn.dzp.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RouterController {
//使得访问/,/index,/index.html都能跳到主页
    @RequestMapping({"/","/index","/index.html"})
    public String index(){
        return "index";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }
//实现对level的三个页面的跳转,下面也是如此
    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id){
        return "views/level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id){
        return "views/level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id){
    return "views/level3/"+id;
    }
}

启动项目查看效果

img

点击对应的level等级页面也能跳转

img

2.用户认证和授权
"认证"(Authentication)
"授权"(Authorization)

这两个概念是通用的,而不是只在Spring security中存在

导入security依赖

<!--security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

创建一个config包,编写一个SecurityConfig类

完整代码如下:

package cn.dzp.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//链式编程
//    授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        首页所有人可以访问,功能页只有对应权限的人才能访问
//        请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("level1")
                .antMatchers("/level2/**").hasRole("level2")
                .antMatchers("/level3/**").hasRole("level3");
//        没有权限默认会跳到登录页面,需要开启登录的页面
        http.formLogin();
//        防止网站攻击:get;post
        http.csrf().disable();//关闭csrf(跨站请求伪造)功能,登出失败可能产生的原因
//        开启注销功能
        http.logout().logoutSuccessUrl("/");
    }
    //    认证,springboot 2.1.x可以直接使用,其他版本会报错(或者采用下面的密码编码解决)
    //    密码编码:PasswordEncoder
//    在spring security 5.0+新增了很多的加密方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        这些数据应该从数据库里读取,使用jdbcAuthentication()
//        目前方式是在内存中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("level1")
                .and()
                .withUser("dzp").password(new BCryptPasswordEncoder().encode("456789")).roles("level1","level2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("level3","level2","level1");
    }

}

登录最高权限账户
img

img

3.注销以及权限控制

由于本次使用到了thymeleaf与spring security的整合,所以需要导入依赖

<!-- security与themeleaf整合包       -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

并且要在index.html中导入对应的约束

xmlns:sec=“http://www.thymeleaf.org/thymeleaf-extras-springsecurity4”

在index.html实现对应的登录与注销
img

注意:运行会出现一下结果
img

这是因为springboot版本太高不支持,最低支持2.0.9.RELEASE版本

img

启动项目Springboot06SecurityApplicationTests会报错,修改下即可,因为降低了版本对应的导入也不相同

img

启动项目

img

然后登录,可以查看到对应的注销按钮和用户名

img

点击注销,成功回到首页,可以看到对应的用户名也清除掉了

img

再来看看实现的根据用户权限展示相对应的页面,展示我们用dzp用户更清楚

img

也成功实现

4.记住我以及首页定制

开启记住我功能(cookie的实现)

img

启动项目试试

虽然不好看,但是已经看到实现了remember me的功能
img

开启记住我登录root用户在关掉浏览器重新打开检查是否还存在root
img

可以看到再次打开有了remember me的cookie,说明成功
img

remember me默认保存的世界为14天==两周,如果清掉cookie,主页则会自动跳到首页(测试时间为2021.5.11)
img

img

自己定义登录页面
img
img
重启项目测试,确实跳转成功
img

注意坑:前端登录页面传的参数可能和默认的username,password不一样,则会传递参数失败,可以根据前端的name进行设置
img

http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
http.rememberMe().rememberMeParameter("remember");

重启项目测试
img
成功登录
img

ogin").usernameParameter(“user”).passwordParameter(“pwd”).loginProcessingUrl("/login");
http.rememberMe().rememberMeParameter(“remember”);


重启项目测试
[外链图片转存中...(img-Gp8YyACN-1650079088224)]
成功登录
[外链图片转存中...(img-voZqb0HB-1650079088224)]

到此关于security所有功能实现!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值