96SEO 2026-07-24 11:24 1
如果没看过入门篇1的小伙伴建议先看一下入门篇1SpringSecurity入门篇

书接上回。我们了解到了基本的关于SpringSecurity的知识而且依靠于内置的登录页完成了基本用法的展示,但是在实际开发过程当中,我们当然要用自己的登录页,而且是前后端分离的项目,接下来我们讲述一下如何实现前后端分离而且指定我们自己写的登录页。
我们先看一下整体的流程图。有一个大概的印象
前端是Vite+Vue3+JS编写,如果不会的话理解就好了。
接下来是部分router.js的代码,可以展示我的登录页面的地址与home页面的地址
{ path: '/'。redirect: '/login' // 默认重定向到登录页面 },{ path: '/login',name: 'Login',component: => import,// 懒加载登录页面 meta: { title: '登录',requiresAuth: false // 不需要登录 } },{ path: '/home',name: 'Home',component: => import,// 懒加载主页 meta: { title: '首页',requiresAuth: true // 需要登录 } },
可以看到,我们的实体类LoginUse实现了一个叫UserDetails的接口,Spring Security是一个合约驱动的框架。它定义了一套标准接口,你的登录类必须实现这些接口。框架才知道:
当使用者登录时Spring Security 执行以下流程:
使用者提交登录 → Security框架调用 → 你的UserDetailsService → 返回UserDetails对象 → Security验证密码 → 创建认证令牌
import org.springframework.security.core.userdetails.UserDetailsService;按理说,public interface LoginUserService extends UserDetailsService {
}
这回可以看到,我们并没有重新创建一个UserDetails的实现类,而是直接返回了我们的LoginUser对象。原因就是我们在刚刚的LoginUser实体类中实现了UserDetails
import com.example.entity.LoginUser;老实说,import com.example.mapper.LoginUserMapper;import com.example.service.LoginUserService;import jakarta.annotation.Resource;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;
@Service public class LoginUserServiceImpl implements LoginUserService {
@Resource private LoginUserMapper loginUserMapper;
@Override public UserDetails loadUserByUsername throws UsernameNotFoundException { LoginUser user = loginUserMapper.getUserByUsername;怎么说呢,if { throw new UsernameNotFoundException;} return user;说起来,} }
接下来是很关键的SecurityConfig文件。我们绝大部分要实现的功能都得通过这个config,我们先看代码,接下来我会逐步的讲解。
import com.example.handle.FailAunticationFailureHandler;import com.example.handle.MyAunticationSuccessHandler;import jakarta.annotation.Resource;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;话说回来,import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;import org.springframework.security.crypto.bcrypt.娱乐ryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.SecurityFilterChain;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.CorsConfigurationSource;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;其实,
@Configuration public class SecurityConfig {
@Resource public MyAunticationSuccessHandler myAunticationSuccessHandler;
@Resource public FailAunticationFailureHandler failAunticationFailureHandler;
/** * 创建一个密码编码器供 Spring Security 使用 */ @Bean public PasswordEncoder passwordEncoder { return new 娱乐ryptPasswordEncoder;说起来,}
@Bean public CorsConfigurationSource configurationSource { CorsConfiguration configuration = new CorsConfiguration;configuration.setAllowedOriginPatterns); // 允许所有来源,生产环境建议指定具体域名 configuration.setAllowedMethods);// 允许所有请求方法 configuration.setAllowedHeaders);// 允许所有请求头 configuration.setAllowCredentials;说起来,// 允许携带凭据
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource;source.registerCorsConfiguration;return source;}
/** * 创建一个 SecurityFilterChain 对象,用于配置 Spring Security 的安全过滤链 */ @Bean public SecurityFilterChain securityFilterChain throws Exception { httpSecurity .formLogin -> formLogin.loginProcessingUrl .successHandler .failureHandler ) .authorizeHttpRequests -> authorize.requestMatchers.permitAll .anyRequest.aunticated) .csrf //支持跨域请求 .cors -> { cors.configurationSource;}),return httpSecurity.build;其实,} }
是编码加密器PasswordEncoder 。这个我们在上篇中讲过 PasswordEncoder 是 Spring Security 中 专门负责密码加密和验证 的接口。想要使用 Spring Security 就必须配置一个加密器,而我们选的是 娱乐ryptPasswordEncoder
/**
* 创建一个密码编码器供 Spring Security 使用
*/
@Bean
public PasswordEncoder passwordEncoder {
return new 娱乐ryptPasswordEncoder;}
接下来就是下面这段代码,这是 Spring Security 中配置CORS 的代码。当你的前端应用要访问后端 API(如运行在 http://localhost:
@Bean
public CorsConfigurationSource configurationSource {
CorsConfiguration configuration = new CorsConfiguration;configuration.setAllowedOriginPatterns);// 允许所有来源,生产环境建议指定具体域名
configuration.setAllowedMethods);// 允许所有请求方法
configuration.setAllowedHeaders);// 允许所有请求头
configuration.setAllowCredentials;// 允许携带凭据
}
. 过滤器链SecurityFilterChain
先来讲一下两个参数:
-
HttpSecurity :Spring Security 的主要配置对象,用它来配置安全规则
-
自动注入前面定义的
CorsConfigurationSource 配置
formLogin.loginProcessingUrl
//.usernameParameter 如果前端的使用者名与密码不叫username和password。需要指定参数名 //.passwordParameter 而这个例子当中我们的使用者名与security里面需求的一样,所以不用特别指定 .successHandler // 登录成功处理器 如果登录成功,则会执行里面的代码 .failureHandler // 登录失败处理器 如果登录失败,则会执行里面的代码 )
.authorizeHttpRequests -> authorize.requestMatchers .permitAll .anyRequest .aunticated )
.csrf
// 支持跨域请求
.cors -> {
cors.configurationSource;}),return httpSecurity.build;}
第一部分上述代码是表单配置
-
formLogin :启用表单登录
-
作用 :告诉Spring Security使用基于表单的登录方式
-
默认行为 :如果不配置,Spring Security 会自动生成一个登录页面
. loginProcessingUrl :指定登录页
-
作用 :指定登录表单提交的URL
-
处理流程 :
使用者提交 POST 请求到 /login 提交 username 和 password 参数 Spring Security 自动拦截这个请求 调用 UserDetailsService 验证使用者名密码 验证成功 → 调用 successHandler 验证失败 → 调用 failureHandler
第二部分上述代码是请求授权配置
-
authorizeHttpRequests - 请求授权
-
作用 :配置哪些请求需要认证。哪些不需要
-
执行时机 :在请求到达Controller之前进行拦截检查
-
requestMatchers.permitAll
-
作用 :匹配指定方法,允许所有人访问
-
为什么需要 :登录页面本身必须能被未登录使用者访问
-
它可以匹配多种模式
authorizeHttpRequests.permitAll // 多个方法 .requestMatchers.permitAll // 所有public开头的方法 .requestMatchers.permitAll // 指定HTTP方法 .requestMatchers.permitAll // Swagger文档
3. .anyRequest.aunticated
* 作用 :其他所有请求都需要认证
-
执行顺序 :Spring Security 按顺序 检查规则
-
关键原则 : 先匹配的规则先生效!
` 错误示例:
// ❌ 错误:anyRequest 匹配所有请求,后面的规则永远不会生效。authorizeHttpRequests.aunticated // 这个匹配所有!.requestMatchers.permitAll // 永远执行不到这里)
// ✅ 正确:先配置不需要认证的,再配置需要认证的。authorizeHttpRequests.permitAll // 先匹配:登录页不需要认证 .anyRequest.aunticated // 后匹配:其他都需要认证)
至于第三部分。CSRF 防护配置.csrf`
* 全称 :Cross-Site Request Forgery
* 攻击原理 :使用者登录A网站后访问恶意网站B,B网站诱导浏览器向A网站发送请求
* 防御机制 :要求请求携带一个随机的Token
-
为什么要禁用?
-
前后端分离 :前端可能是React/Vue,不是服务端渲染的页面
-
无状态API :使用JWT等无状态认证。没有Session
-
至于方便,开发阶段可以禁用,生产环境应重新考虑
从第四部分来看,CORS 跨域配置 .cors => { cors.configurationSource;})
1. 为什么需要这个配置?虽然我们刚刚定义了
Cors Configuration Source
Bean。
`**但还需要告诉
CORS
安全使用它**
因为 CORS 有自己的处理机制,如果我们不指定,他就会用默认的。其实,
Auntication Success Handler 是 Spring Security 中的一个关键接口。用于 处理使用者认证成功后的行为。
1. 控制认证成功后的重定向当使用者登录成功后决定跳转到哪个页面记录日志、更新最终 登录时间、设置会话等
.
.
.
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback