SpringSecurity -- 入门使用

文章目录

什么是 SpringSesurity ?

在我们的开发中,安全还是有些必要的

用 拦截器 和 过滤器 写代码还是比较麻烦。
SpringSecuritySpringBoot 的底层安全默认选型。一般我们需要认证和授权,这也是它的核心功能。我们仅仅需要导入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理
认证:验证当前访问系统的用户 是不是本系统的用户,并且要具体哪一个用户
授权:经过认证后判断当前用户是否有权限进行某个操作

细节

登录过程

负责我们在登录页面填写的用户和密码登录的请求,入门案例主要由他负责。

使用方法

总结到代码之中。



复制代码
// 开启 web 安全
@EnableWebSecurity
public class springSecurityConfig extends WebSecurityConfigurerAdapter { // 然后我们继承 web安全配置 适配器


    // 链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().  // authorize 授权
                antMatchers("/").permitAll()  //  ant ==> 蚂蚁    matcher ==> 匹配器 permitAll ==> 允许所有
                .antMatchers("/test1/**").hasRole("vip1")  //  role角色
                .antMatchers("/test2/**").hasRole("vip2")
                .antMatchers("/test3/**").hasRole("vip3");

        // 如果没有用户的情况下,则会跳转到 login 页面       // 登录加工的url
        http.formLogin().loginPage("/toLogin").usernameParameter("name").passwordParameter("pwd").loginProcessingUrl("/Login");

//                 http.formLogin()
//                   .loginPage("/toLogin") // 设置登录页面URL
//                   .loginProcessingUrl("/Login") // 设置表单提交的URL 个人感觉:应该是需要认证的模块
//                   .failureUrl("/login-error") // 登录失败后的重定向URL
//                   .defaultSuccessUrl("/home", true) // 登录成功后的默认重定向URL
//                .and()
//                  .logout()
//                   .logoutSuccessUrl("/"); // 注销成功后的重定向URL

        // 开启记住我功能
        http.rememberMe().rememberMeParameter("jiZhuWo");

        http.csrf().disable();  // 关闭脚本跨站攻击
        // 开启注销功能
        http.logout().logoutSuccessUrl("/index");  // 注销成功后,回到 "/index" 之中。
    }

    // 认证
    @Override // 最新版本需要密码加密
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {  // Authentication 认证 Manager 管理者
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) // Memory 记忆
                .withUser("xj").password(new BCryptPasswordEncoder().encode("abc")).roles("vip1","vip2")  // memory ==> 记忆
                .and()
                .withUser("test").password(new BCryptPasswordEncoder().encode("cba")).roles("vip3");
    }
}

我们可以看到,拥有这个功能,不仅提供了权限、安全等,还另外 省去了写登录后台、过滤器等大量繁杂的代码,十分的方便

相关推荐
西索斯coding2 分钟前
doubao-seed-2.1-turbo 调用一直 401 怎么办?pro 版同样的 Key 却正常——5 分钟排查定位指南
java·服务器·数据库·ai
旧梦95279 分钟前
Java SortedMap 接口详解:从入门到实战
java·开发语言
莫陌尛.13 分钟前
Java_this构造方法
java·开发语言
2601_9622972532 分钟前
C# vs Java vs Python:YOLO工业部署性能对比实战
java·python·c·工业视觉·性能对比
计算机毕设定制辅导-无忧学长34 分钟前
《基于SpringBoot的马术俱乐部管理系统》
java·spring boot·后端
摇滚侠35 分钟前
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 JDBC 事务管理 阅读笔记 33
spring boot·笔记·后端
Dreams°12341 分钟前
【Java后端+Vue前后端分离:内网正常、公网访问异常|5个高频经典踩坑完整复盘】
java·开发语言·vue.js
学长毕业设计1 小时前
基于SpringBoot的民间艺术传承管理系统(源码+文档+讲解视频)
java·spring boot·后端
小蒜学长1 小时前
基于Springboot+Vue的环保行动志愿者招募系统设计与实现(代码+数据库+LW)
java·数据库·vue.js·spring boot·后端
cfm_29141 小时前
Spring事务
数据库·spring·oracle