SpringSecurity 表单登录

简介: SpringSecurity 表单登录

SpringSecurity 表单登录

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/mylogin.html")
                .loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/index.html")
                .failureHandler(new MyAuthenticationFailureHandler())
                .usernameParameter("uname")
                .passwordParameter("passwd")
                .permitAll()
                .and()
                .logout()
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/logout1", "GET"),
                        new AntPathRequestMatcher("/logout2", "POST")))
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .defaultLogoutSuccessHandlerFor((req,resp,auth)->{
                    resp.setContentType("application/json;charset=utf-8");
                    Map<String, Object> result = new HashMap<>();
                    result.put("status", 200);
                    result.put("msg", "使用 logout1 注销成功!");
                    ObjectMapper om = new ObjectMapper();
                    String s = om.writeValueAsString(result);
                    resp.getWriter().write(s);
                },new AntPathRequestMatcher("/logout1","GET"))
                .defaultLogoutSuccessHandlerFor((req,resp,auth)->{
                    resp.setContentType("application/json;charset=utf-8");
                    Map<String, Object> result = new HashMap<>();
                    result.put("status", 200);
                    result.put("msg", "使用 logout2 注销成功!");
                    ObjectMapper om = new ObjectMapper();
                    String s = om.writeValueAsString(result);
                    resp.getWriter().write(s);
                },new AntPathRequestMatcher("/logout2","POST"))
                .and()
                .csrf().disable();
    }
}

springSecurity需要自定义配置值 基本都是继承WebSecurityConfigurerAdapter

  1. authorizeRequests表示开启权限配置,.anyRequest().authenticated()表示所有的请求都认证之后才能访问
  2. and()方法返回HttpSecurity的实例
  3. formLogin()表示开启表单登录配置

    • loginPage 配置登录页面地址
    • loginProcessingUrl 配置登录接口地址
    • defaultSuccessUrl 登录成功后的跳转地址
    • failureUrl表示登录失败后的跳转地址
    • usernameParameter表示登录用户名的参数名
    • passwordParameter 登录密码的参数名
    • permitAll()表示和登录相关的页面和接口不做拦截 直接通过

    其中loginProcessingUrl usernameParameter passwordParameter要和登录表单的配置一致。

     .loginPage("/mylogin.html")  // 
                    .loginProcessingUrl("/doLogin")
                    .defaultSuccessUrl("/index.html")
                    .failureHandler(new MyAuthenticationFailureHandler())
                    .usernameParameter("uname")
                    .passwordParameter("passwd")
  4. csrf().disable()表示禁用CSRF防御功能

登录成功

用户登录成功后除了defaultSuccessUrl方法可以实现登录成功的跳转之外,successForwardUrl也可以实现登录成功后的跳转,

defaultSuccessUrl 和successForwardUrl区别:

  1. defaultSuccessUrl表示当用户登录成功后,会自动重定向到登录之前的地址,如果用户本身就是访问的登录页面,登录成功后就会重定向到defaultSuccessUrl指定页面
  2. successForwardUrl不会考虑用户之前的访问地址,登录成功后通过服务器端跳转到successForwardUrl所指定的页面。

defaultSuccessUrl是客户端跳转重定向,successForwardUrl是通过服务端实现的跳转。

他们的接口都AuthenticationSuccessHandler

AuthenticationSuccessHandler有三个实现类

  1. SimpleUrlAuthenticationSuccessHandler 继承 AbstractAuthenticationTargetUrlRequestHandler 通过他的handle方法处理请求
  2. SavedRequestAwareAuthenticationSuccessHandler 在SimpleUrlAuthenticationSuccessHandler基础上增加了请求加缓存的功能,可以记录之前请求的地址,今儿在登录成功后重定向到开始访问的地址。
  3. ForwardAuthenticationSuccessHandler 是服务端的跳转

SavedRequestAwareAuthenticationSuccessHandler

defaultSuccessUrl 对应的是SavedRequestAwareAuthenticationSuccessHandler

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
    SavedRequest savedRequest = this.requestCache.getRequest(request, response);
    if (savedRequest == null) {
        super.onAuthenticationSuccess(request, response, authentication);
    } else {
        String targetUrlParameter = this.getTargetUrlParameter();
        if (!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            this.clearAuthenticationAttributes(request);
            String targetUrl = savedRequest.getRedirectUrl();
            this.logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
            this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
        } else {
            this.requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
  1. 首先从requestCache中获取缓存下来的请求 如果没有获取到缓存请求,就说明用户在访问登录页面之前并没有访问其他页面,此时直接调用父类的onAuthenticationSuccess方法来处理,重定向到defaultSuccessUrl指定的地址。
  2. 获取targetUrlParameter 拿到target参数后重定向地址。
  3. 如果targetUrlParameter不存在或者alwaysUseDefaultTargetUrl为true 缓存下来的请求没有意义,直接调用父类的onAuthenticationSuccess方法完成重定向 。targetUrlParameter存在 则重定向到targetUrlParameter中,alwaysUseDefaultTargetUrl为true 走默认

ForwardAuthenticationSuccessHandler

successForwardUrl对应ForwardAuthenticationSuccessHandler

public class ForwardAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final String forwardUrl;

    public ForwardAuthenticationSuccessHandler(String forwardUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), () -> {
            return "'" + forwardUrl + "' is not a valid forward URL";
        });
        this.forwardUrl = forwardUrl;
    }

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        request.getRequestDispatcher(this.forwardUrl).forward(request, response);
    }
}

主要调用getRequestDispatcher进行服务端请求转发

自定义AuthenticationSuccessHandler 实现类

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler{
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> resp = new HashMap<>();
        resp.put("status", 200);
        resp.put("msg", "登录成功!");
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(resp);
        response.getWriter().write(s);
    }
}
.successHandler(new MyAuthenticationSuccessHandler())

通过HttpServletResponse对象返回登录成功的json给前端

登录失败

failureUrl表示登录失败后的重定向到配置的页面,重定向是客户端的跳转,不方便携带请求失败的异常信息。

failureForwardUrl是服务端的跳转,可以携带登录异常信息。登录失败,自动跳转回登录页面,将错误信息展示出来。

他们的配置的是AuthenticationFailureHandler接口的实现类

SimpleUrlAuthenticationFailureHandler

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.web.authentication;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

public class SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {
    protected final Log logger = LogFactory.getLog(this.getClass());
    private String defaultFailureUrl;
    private boolean forwardToDestination = false;
    private boolean allowSessionCreation = true;
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    public SimpleUrlAuthenticationFailureHandler() {
    }

    public SimpleUrlAuthenticationFailureHandler(String defaultFailureUrl) {
        this.setDefaultFailureUrl(defaultFailureUrl);
    }

    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (this.defaultFailureUrl == null) {
            this.logger.debug("No failure URL set, sending 401 Unauthorized error");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
        } else {
            this.saveException(request, exception);
            if (this.forwardToDestination) {
                this.logger.debug("Forwarding to " + this.defaultFailureUrl);
                request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);
            } else {
                this.logger.debug("Redirecting to " + this.defaultFailureUrl);
                this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl);
            }
        }

    }

    protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
        if (this.forwardToDestination) {
            request.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
        } else {
            HttpSession session = request.getSession(false);
            if (session != null || this.allowSessionCreation) {
                request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
            }
        }

    }
}

当用户构造SimpleUrlAuthenticationFailureHandler对象时候传入defaultFailureUrl,也就是登录失败时要跳转的url。在onAuthenticationFailure方法中

  • 如果defaultFailureUrl为null,直接通过response返回异常信息,否则调用saveException
  • saveException 如果forwardToDestination为true,表示通过服务器端跳转回到登录页面,此时就把异常信息放到request中。
  • 回到onAuthenticationFailure方法,如果forwardToDestination为true,就通过服务器端跳回到登录页面,否则重定向到登录页面。

自定义AuthenticationFailureHandler实现类

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> resp = new HashMap<>();
        resp.put("status", 500);
        resp.put("msg", "登录失败!" + exception.getMessage());
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(resp);
        response.getWriter().write(s);
    }
}

通过HttpServletResponse对象返回登录失败的json给前端

注销登录

.logout()
.logoutUrl("")
.logoutRequestMatcher(new OrRequestMatcher(
        new AntPathRequestMatcher("/logout1", "GET"),
        new AntPathRequestMatcher("/logout2", "POST")))
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessUrl("")
  • logout() 表示开启注销登录配置。
  • logoutUrl 指定注销登录请求地址,默认GET请求,路径logout
  • invalidateHttpSession 表示是否使session失效,默认为true
  • clearAuthentication 表示是否清除认证信息,默认为true
  • logoutSuccessUrl 表示注销登录后的跳转地址。
  • logoutRequestMatcher 匹配多个注销登录

自定义注销成功的返回内容

.logout()
.logoutRequestMatcher(new OrRequestMatcher(
        new AntPathRequestMatcher("/logout1", "GET"),
        new AntPathRequestMatcher("/logout2", "POST")))
.invalidateHttpSession(true)
.clearAuthentication(true)
.defaultLogoutSuccessHandlerFor((req,resp,auth)->{
    resp.setContentType("application/json;charset=utf-8");
    Map<String, Object> result = new HashMap<>();
    result.put("status", 200);
    result.put("msg", "使用 logout1 注销成功!");
    ObjectMapper om = new ObjectMapper();
    String s = om.writeValueAsString(result);
    resp.getWriter().write(s);
},new AntPathRequestMatcher("/logout1","GET"))
.defaultLogoutSuccessHandlerFor((req,resp,auth)->{
    resp.setContentType("application/json;charset=utf-8");
    Map<String, Object> result = new HashMap<>();
    result.put("status", 200);
    result.put("msg", "使用 logout2 注销成功!");
    ObjectMapper om = new ObjectMapper();
    String s = om.writeValueAsString(result);
    resp.getWriter().write(s);
},new AntPathRequestMatcher("/logout2","POST"))
.and()
.csrf().disable();

defaultLogoutSuccessHandlerFor()两个参数 第一个是注销成功的回调,第二个是具体的注销请求。

相关文章
|
安全 物联网 5G
5g技术的优缺点是什么
5g技术的优缺点是什么
2436 0
|
2月前
|
人工智能 弹性计算 双11
2026年阿里云双十一大促开始:轻量、ECS、GPU云服务器与百炼Token Plan优惠价格整理
阿里云双十一是每年面向新老客户集中放 阿里云轻量应用服务器、阿里云ECS云服务器、阿里云GPU云服务器、阿里云百炼大模型服务平台 券、放价的一次年度大促,2026年的主战场覆盖 阿里云轻量应用服务器、阿里云ECS云服务器、阿里云GPU云服务器、阿里云百炼大模型服务平台 等主力产品。今年的双十一以“智惠就在11.11,AI就用阿里云”为主题,活动周期持续至11月30日,延续了“先定负载、再选机型、最后在活动窗口内下单”的理性购物理念,优惠从单纯的“首年低价”升级为“新购、续费、升级全链路可核算”。
297 1
|
2月前
|
人工智能 小程序 前端开发
把“免费“做成生意:20岁学生做40多个App废了40多个,第45个跑通月入21万——他赚的不是开发费,是“你懒得找“的钱
本文是「OPC一人公司通关手册」第35篇,聚焦一个20岁学生靠“免费物品聚合+订阅制”月入21万的真实案例。他不做交易、不卖货,而是将散落各处的白送家具、清仓库存、闲置转让等免费资源集中整理,用户花几元月费即可高效捡漏——赚的是“省时间”的钱。核心逻辑:信息差×AI提效×内容验证获客。(239字)
|
9月前
|
人工智能 JavaScript Linux
OpenClaw(Clawdbot)阿里云秒级部署|Kimi K2.5一键接入+常见问题解答
2026年,OpenClaw(原Clawdbot)凭借轻量化架构、秒级部署能力与强大的大模型集成生态,成为搭建专属AI助手的首选工具。阿里云依托轻量应用服务器与计算巢,为OpenClaw提供官方专属部署模板,实现真正意义上的秒级部署,全程无需手动配置环境、无需处理复杂依赖,搭配Kimi K2.5大模型,可快速构建具备超长上下文、深度推理、代码生成与联网搜索能力的AI机器人,满足个人与企业的智能交互、任务自动化、文档处理等核心需求。
1243 1
|
11月前
|
网络协议 前端开发 JavaScript
HTTP/2 特点解析,从 HTTP/1.1 的痛点到新一代协议的进化
HTTP/2 解决 HTTP/1.1 队头阻塞、低效传输等痛点,通过多路复用、二进制帧、头部压缩等技术大幅提升加载速度,支持服务器推送与流优先级,优化用户体验。虽仍受制于 TCP 丢包问题,但已是当前主流高性能协议,为迈向 HTTP/3 奠定基础。
1112 159
|
数据采集 JavaScript API
淘宝商品评论API实战:从数据获取到情感分析
淘宝商品评论API是开放平台提供的核心接口,支持获取文字、评分、多媒体等评论数据,具备实时性强、分类筛选、批量查询等特点,助力电商数据分析与用户行为研究,提升产品优化与服务质量。(238字)
|
6月前
|
存储 测试技术 数据库
Agent Memory主流产品横评与选型指南
本文横评10大Agent记忆方案,直击RAG与向量库的局限:缺乏时序追踪、一致性保障、分层管理与智能路由四大核心能力。从腾讯DB的高准确率、Zep的情节图谱、EverMemOS的多模态认知,到TiMem的五层时序树,全面解析各方案架构、性能与适用场景,助您科学选型。(239字)
|
11月前
|
存储 人工智能 弹性计算
2026 年阿里云企业级服务器优惠活动与报价解析
2026 年阿里云企业级服务器优惠以 “199 元 u1 实例” 为核心,覆盖基础办公、跨境业务、高性能计算等场景,同时通过轻量服务器、GPU 实例补充多元化需求。企业选型时需结合业务负载(并发量、数据量、地域覆盖),优先选择 “续费同价” 套餐锁定长期成本,搭配优惠券与组合采购进一步优化开支。如需获取实时库存与最新报价,可参考阿里云官方活动页面,确保配置与业务需求精准匹配。
|
人工智能 自然语言处理 JavaScript
通义灵码2.5实战评测:Vue.js贪吃蛇游戏一键生成
通义灵码基于自然语言需求,快速生成完整Vue组件。例如,用Vue 2和JavaScript实现贪吃蛇游戏:包含键盘控制、得分系统、游戏结束判定与Canvas动态渲染。AI生成的代码符合规范,支持响应式数据与事件监听,还能进阶优化(如增加启停按钮、速度随分数提升)。传统需1小时的工作量,使用通义灵码仅10分钟完成,大幅提升开发效率。操作简单:安装插件、输入需求、运行项目即可实现功能。
863 4
 通义灵码2.5实战评测:Vue.js贪吃蛇游戏一键生成
|
关系型数据库 分布式数据库 数据库
阿里云数据库收费价格:MySQL、PostgreSQL、SQL Server和MariaDB引擎费用整理
阿里云数据库提供多种类型,包括关系型与NoSQL,主流如PolarDB、RDS MySQL/PostgreSQL、Redis等。价格低至21元/月起,支持按需付费与优惠套餐,适用于各类应用场景。