广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringSecurity 表单登录的实现
  • 250
分享到

SpringSecurity 表单登录的实现

2024-04-02 19:04:59 250人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录表单登录登录成功登录失败注销登录自定义注销成功的返回内容表单登录 @Configuration public class SecurityConfig extends WE

表单登录


@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

  • authorizeRequests表示开启权限配置,.anyRequest().authenticated()表示所有的请求都认证之后才能访问
  • and()方法返回HttpSecurity的实例
  • formLogin()表示开启表单登录配置
    • loginPage 配置登录页面地址
    • loginProcessingUrl 配置登录接口地址
    • defaultSuccessUrl 登录成功后的跳转地址
    • failureUrl表示登录失败后的跳转地址
    • usernameParameter表示登录用户名的参数名
    • passwordParameter 登录mima的参数名
    • permitAll()表示和登录相关的页面和接口不做拦截 直接通过

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


 .loginPage("/mylogin.html")  // 
                .loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/index.html")
                .failureHandler(new MyAuthenticationFailureHandler())
                .usernameParameter("uname")
                .passwordParameter("passwd")

csrf().disable()表示禁用CSRF防御功能

登录成功

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

defaultSuccessUrl 和successForwardUrl区别:

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

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

他们的接口都AuthenticationSuccessHandler

AuthenticationSuccessHandler有三个实现类

SimpleUrlAuthenticationSuccessHandler 继承 AbstractAuthenticationTargetUrlRequestHandler 通过他的handle方法处理请求

SavedRequestAwareAuthenticationSuccessHandler 在SimpleUrlAuthenticationSuccessHandler基础上增加了请求加缓存的功能,可以记录之前请求的地址,今儿在登录成功后重定向到开始访问的地址。
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);
        }
    }
}
  • 首先从requestCache中获取缓存下来的请求 如果没有获取到缓存请求,就说明用户在访问登录页面之前并没有访问其他页面,此时直接调用父类的onAuthenticationSuccess方法来处理,重定向到defaultSuccessUrl指定的地址。
  • 获取targetUrlParameter 拿到target参数后重定向地址。
  • 如果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()两个参数 第一个是注销成功的回调,第二个是具体的注销请求。

到此这篇关于SpringSecurity 表单登录的实现的文章就介绍到这了,更多相关SpringSecurity 表单登录内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringSecurity 表单登录的实现

本文链接: https://www.lsjlt.com/news/160159.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringSecurity 表单登录的实现
    目录表单登录登录成功登录失败注销登录自定义注销成功的返回内容表单登录 @Configuration public class SecurityConfig extends We...
    99+
    2022-11-12
  • springSecurity实现简单的登录功能
    前言 1、不使用数据库,实现一个简单的登录功能,只有在登录后才能访问我们的接口2、springSecurity提供了一种基于内存的验证方法(使用自己定义的用户,不使用默认的) 一、实...
    99+
    2022-11-13
  • springsecurity集成cas实现单点登录过程
    目录cas流程下面代码解决的问题具体代码使用总结cas流程 如下 用户发送请求,后台服务器验证ticket(票据信息),未登录时,用户没有携带,所以验证失败,将用户重定向到cas服务...
    99+
    2023-02-16
    spring security spring security集成cas cas实现单点登录
  • SpringSecurity OAuth2如何实现单点登录和登出功能
    这篇文章将为大家详细讲解有关SpringSecurity OAuth2如何实现单点登录和登出功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1. 单点登录单点登录即有多个子系统,有一个认证中心...
    99+
    2023-06-29
  • SpringSecurity使用单点登录的权限功能
    目录背景Spring Security实现已经有了单点登录页面,Spring Security怎么登录,不登录可以拿到权限吗Authentication继续分析结论如何手动登录Spr...
    99+
    2022-11-13
  • Java SpringSecurity+JWT如何实现登录认证
    这篇文章主要介绍了Java SpringSecurity+JWT如何实现登录认证的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Java SpringSecurity+JWT如何实现登录认证文...
    99+
    2023-07-02
  • React实现登录表单的示例代码
    作为一个Vue用户,是时候扩展一下React了,从引入antd、配置less、router,终于实现了一个简单的登录表单。 代码如下: import React from 'r...
    99+
    2022-11-12
  • Springboot+SpringSecurity实现图片验证码登录的示例
    这个问题,网上找了好多,结果代码都不全,找了好多,要不是就自动注入的类注入不了,编译报错,要不异常捕获不了浪费好多时间,就觉得,框架不熟就不能随便用,全是坑,气死我了,最后改了两天....
    99+
    2022-11-13
  • Vue3实现登录表单验证功能
    目录一.实现思路与效果图二.实现具体过程三.完整代码与效果图一.实现思路与效果图 使用async-validator 插件,阿里出品的 antd 和 ElementUI 组件库中表单...
    99+
    2022-11-13
  • SpringSecurity实现退出登录和退出处理器
    在系统中一般都有退出登录的操作。退出登录后,Spring Security进行了以下操作: 清除认证状态销毁HttpSession对象跳转到登录页面 配置退出登录的路径和退出后跳转的...
    99+
    2022-11-13
  • SpringSecurity整合springBoot、redis实现登录互踢功能
    背景 基于我的文章——《SpringSecurity整合springBoot、redis token动态url权限校验》。要实现的功能是要实现一个用户不可以同时在两台设备上登录,有两...
    99+
    2022-11-12
  • Springboot+SpringSecurity怎么实现图片验证码登录
    本文小编为大家详细介绍“Springboot+SpringSecurity怎么实现图片验证码登录”,内容详细,步骤清晰,细节处理妥当,希望这篇“Springboot+SpringSecurity怎么实现图片验证码登录”文章能帮助大家解决疑惑...
    99+
    2023-06-30
  • Bootstrap中怎么实现表格、表单、登录页面
    这篇文章将为大家详细讲解有关Bootstrap中怎么实现表格、表单、登录页面,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1.表格<!doctype ht...
    99+
    2022-10-19
  • springsecurity结合jwt实现用户重复登录处理
    目录背景方案思路图核心代码背景 近日,客户针对我司系统做一些列漏洞扫描,最后总结通用漏洞有如下: 用户重复登录接口未授权接口越权访问 针对以上漏洞,分三篇文章分别记录解决方案,供后续...
    99+
    2022-11-13
  • SpringSecurity整合springBoot、redis实现登录互踢功能的示例
    这篇文章主要介绍了SpringSecurity整合springBoot、redis实现登录互踢功能的示例,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。背景要实现的功能是要实现...
    99+
    2023-06-15
  • vue ElementUI的from表单实现登录效果的示例
    目录1.通过ElementUI构建基本的样式2.用点击提交按钮将 将账号密码框内的内容 传给后台数据总结1.通过ElementUI构建基本的样式     &nbs...
    99+
    2022-11-12
  • SpringSecurity基于散列加密方案实现自动登录
    目录前言一. 自动登录简介1. 为什么要自动登录2. 自动登录的实现方案二. 基于散列加密方案实现自动登录1. 配置加密令牌的key2. 配置SecurityConfig类3. 添加...
    99+
    2022-11-12
  • SpringSecurity实现前后端分离登录token认证详解
    目录 1. SpringSecurity概述 1.1 权限框架 1.1.1 Apache Shiro 1.1.2 SpringSecurity 1.1.3 权限框架的选择 1.2 授权和认证 1.3 SpringSecurity的功能 ...
    99+
    2023-08-31
    spring java spring boot
  • Python3.x实现网页登录表单提交功
            最近失业,在网上投了很多简历,据说刷新后,简历可以排在前面!于是就想起来做一个刷新简历的小程序,碰巧在学习Python,也懒得打开慢慢的vs了。         桌面建立“简历刷新.txt”,大家都懂的,后缀修改为py,打...
    99+
    2023-01-31
    表单 网页
  • 使用React怎么实现一个登录表单
    这篇文章将为大家详细讲解有关使用React怎么实现一个登录表单,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。代码如下:import React from ...
    99+
    2023-06-14
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作