spring secutity 入门 1

SpringSecurity 特点:

⚫ 和 Spring 无缝整合。

⚫ 全面的权限控制。

⚫ 专门为 Web 开发而设计。

    ◼旧版本不能脱离 Web 环境使用。

    ◼新版本对整个框架进行了分层抽取,分成了核心模块和 Web 模块。单独 引入核心模块就可以脱离 Web 环境。

⚫ 重量级。

 

 

 

 


 

创建SpringBoot项目,导入依赖

你随便访问个页面会被拦截:

 

 

 

账号默认user  密码控制台有

 

 

 


 

 

他本质就是个过滤器链

介绍三个比较基本的过滤器:

FilterSecurityInterceptor:是一个方法级的权限过滤器, 基本位于过滤链的最底部。

ExceptionTranslationFilter:是个异常过滤器,用来处理在认证授权过程中抛出的异常

UsernamePasswordAuthenticationFilter :对/login 的 POST 请求做拦截,校验表单中用户 名,密码。

可以去看看源码。

 

基本原理:

 

 

 

设置账户名和密码【配置设置】

直接在配置中配置即可,例:

 

 

 

这种方式非常2B!

 

 

配置类配置账号密码:

复制代码
package com.example.springsecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 1.继承 WebSecurityConfigurerAdapter
 * 2.如果需要加密密码就 BCryptPasswordEncoder 加密【看代码】  需要手动 new 一个 PasswordEncoder
 * 3.设置账户名,密码,角色
 */

@Configuration
public class securityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //加密
        String password = passwordEncoder.encode("xianyu123");
        //下面密码已加密
        auth.inMemoryAuthentication().withUser("xianyu").password(password).roles("角色");
    }

    @Bean
    PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
    }
}
View Code
复制代码

 

自定义编写账户密码:

第一步,也是继承WebSecurityConfigurerAdapter,然后重写configure,也要记得给PasswordEncoder @Bean一下 然后看下图:

 第二步:新建service,模拟一下数据从后端过来:

 

 为什么返回User类?  自己看源码即可。

  

 

posted @   咸瑜  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2021-06-09 8. 颜色和样式 - BootStrap
2021-06-09 clear 清除浮动 CSS
2021-06-09 17. JSP - 使用过滤器控制访问登录权限
2021-06-09 Session - 什么时候创建?
2020-06-09 C语言利用for循环打印菱形
点击右上角即可分享
微信分享提示