springsecurity前后端跨域和分离登陆问题_abstractauthenticationprocessingfilter 跨域问题-程序员宅基地

技术标签: vue  问题  # springsecurity  

引入

在这里插入图片描述
在后端获取用户名、密码不为null

        System.out.println(request.getParameter("username"));
        System.out.println(request.getParameter("password"));

在这里插入图片描述

当我把它写入前端
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
后端获取用户名、密码为null,不知道怎么搞的前端就是请求不成功了,postman测试的时候好好的,看了很长时间也不知道是怎么搞的,知道的朋友请在评论区回复一下

跨域

在这里插入图片描述
在这里插入图片描述

将springsecurity登陆转化为application/json

网上说的方法是写一个过滤器,重写一下UsernamePasswordAuthenticationFilter

/*
 * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.web.authentication;

import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Processes an authentication form submission. Called
 * {@code AuthenticationProcessingFilter} prior to Spring Security 3.0.
 * <p>
 * Login forms must present two parameters to this filter: a username and password. The
 * default parameter names to use are contained in the static fields
 * {@link #SPRING_SECURITY_FORM_USERNAME_KEY} and
 * {@link #SPRING_SECURITY_FORM_PASSWORD_KEY}. The parameter names can also be changed by
 * setting the {@code usernameParameter} and {@code passwordParameter} properties.
 * <p>
 * This filter by default responds to the URL {@code /login}.
 *
 * @author Ben Alex
 * @author Colin Sampaleanu
 * @author Luke Taylor
 * @since 3.0
 */
public class UsernamePasswordAuthenticationFilter extends
		AbstractAuthenticationProcessingFilter {
    
	// ~ Static fields/initializers
	// =====================================================================================

	public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
	public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";

	private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
	private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
	private boolean postOnly = true;

	// ~ Constructors
	// ===================================================================================================

	public UsernamePasswordAuthenticationFilter() {
    
		super(new AntPathRequestMatcher("/login", "POST"));
	}

	// ~ Methods
	// ========================================================================================================

	public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {
    
		if (postOnly && !request.getMethod().equals("POST")) {
    
			throw new AuthenticationServiceException(
					"Authentication method not supported: " + request.getMethod());
		}

		String username = obtainUsername(request);
		String password = obtainPassword(request);

		if (username == null) {
    
			username = "";
		}

		if (password == null) {
    
			password = "";
		}

		username = username.trim();

		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
				username, password);

		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);

		return this.getAuthenticationManager().authenticate(authRequest);
	}

	/**
	 * Enables subclasses to override the composition of the password, such as by
	 * including additional values and a separator.
	 * <p>
	 * This might be used for example if a postcode/zipcode was required in addition to
	 * the password. A delimiter such as a pipe (|) should be used to separate the
	 * password and extended value(s). The <code>AuthenticationDao</code> will need to
	 * generate the expected password in a corresponding manner.
	 * </p>
	 *
	 * @param request so that request attributes can be retrieved
	 *
	 * @return the password that will be presented in the <code>Authentication</code>
	 * request token to the <code>AuthenticationManager</code>
	 */
	@Nullable
	protected String obtainPassword(HttpServletRequest request) {
    
		return request.getParameter(passwordParameter);
	}

	/**
	 * Enables subclasses to override the composition of the username, such as by
	 * including additional values and a separator.
	 *
	 * @param request so that request attributes can be retrieved
	 *
	 * @return the username that will be presented in the <code>Authentication</code>
	 * request token to the <code>AuthenticationManager</code>
	 */
	@Nullable
	protected String obtainUsername(HttpServletRequest request) {
    
		return request.getParameter(usernameParameter);
	}

	/**
	 * Provided so that subclasses may configure what is put into the authentication
	 * request's details property.
	 *
	 * @param request that an authentication request is being created for
	 * @param authRequest the authentication request object that should have its details
	 * set
	 */
	protected void setDetails(HttpServletRequest request,
			UsernamePasswordAuthenticationToken authRequest) {
    
		authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
	}

	/**
	 * Sets the parameter name which will be used to obtain the username from the login
	 * request.
	 *
	 * @param usernameParameter the parameter name. Defaults to "username".
	 */
	public void setUsernameParameter(String usernameParameter) {
    
		Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
		this.usernameParameter = usernameParameter;
	}

	/**
	 * Sets the parameter name which will be used to obtain the password from the login
	 * request..
	 *
	 * @param passwordParameter the parameter name. Defaults to "password".
	 */
	public void setPasswordParameter(String passwordParameter) {
    
		Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
		this.passwordParameter = passwordParameter;
	}

	/**
	 * Defines whether only HTTP POST requests will be allowed by this filter. If set to
	 * true, and an authentication request is received which is not a POST request, an
	 * exception will be raised immediately and authentication will not be attempted. The
	 * <tt>unsuccessfulAuthentication()</tt> method will be called as if handling a failed
	 * authentication.
	 * <p>
	 * Defaults to <tt>true</tt> but may be overridden by subclasses.
	 */
	public void setPostOnly(boolean postOnly) {
    
		this.postOnly = postOnly;
	}

	public final String getUsernameParameter() {
    
		return usernameParameter;
	}

	public final String getPasswordParameter() {
    
		return passwordParameter;
	}
}

自定义的登陆过滤器

CustomAuthenticationFilter

package com.example.springboot_springsecurity_jwt_redis.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    
        //attempt Authentication when Content-Type is json
        if(request.getContentType().equals(MediaType.APPLICATION_JSON)
                ||request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
    

            //use jackson to deserialize json
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            try (InputStream is = request.getInputStream()){
    
                AuthenticationBean authenticationBean = mapper.readValue(is,AuthenticationBean.class);
                authRequest = new UsernamePasswordAuthenticationToken(
                        authenticationBean.getUsername(), authenticationBean.getPassword());
            }catch (IOException e) {
    
                e.printStackTrace();
                authRequest = new UsernamePasswordAuthenticationToken(
                        "", "");
            }finally {
    
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            }
        }

        //transmit it to UsernamePasswordAuthenticationFilter
        else {
    
            return super.attemptAuthentication(request, response);
        }
    }
}

AuthenticationBean

package com.example.springboot_springsecurity_jwt_redis.filters;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class AuthenticationBean {
    
    private String username;
    private String password;
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_42977003/article/details/106016161

智能推荐

(已解决)maven中 java.sql.SQLException: com.mysql.cj.jdbc.Driver 报错的解决方法-程序员宅基地

文章浏览阅读3w次,点赞13次,收藏14次。(已解决)maven中 java.sql.SQLException: com.mysql.cj.jdbc.Driver 报错的解决方法很明显是mysql连接驱动依赖的版本不匹配问题,一般出现在使用低版本连接驱动连接高版本mysql情况下,解决方法是在maven中央仓库中下载高版本的mysql连接驱动,获取在pom中加入如下坐标:<!--mysql驱动--> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector_java.sql.sqlexception: com.mysql.cj.jdbc.driver

Python+selinume+mysql爬取考拉商品信息_考拉商品图片python爬虫-程序员宅基地

文章浏览阅读695次。Python+selinume+mysql爬取考拉商品信息功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入环境:py..._考拉商品图片python爬虫

安装hive和mysql_安装hive和mysql,熟悉hive命令,熟练使用create、load、insert、alert-程序员宅基地

文章浏览阅读137次。====== 安装hive和myql =====安装myslqCentOS7自带有MariaDB而不是MySQL,MariaDB和MySQL一样也是开元的数据库解决方案:如果必须要安装MySQL,首先必须添加mysql社区repo通过输入命令#rpm -Uvh http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm获取mysql#yum install -y mysql-server启动mysql server服务_安装hive和mysql,熟悉hive命令,熟练使用create、load、insert、alert、show、desc

【VBA】使用vba进行文件批量重命名(自定义后缀,重复文件自动编号)_vba批量重命名文件-程序员宅基地

文章浏览阅读1w次,点赞2次,收藏29次。使用vba进行文件名的重命名和管理的过程中,经常会遇到要命名的文件名已存在,或者多个文件名需要命名成同一个名字,需要后面用括号数字区分的情况,可以参考以下解决办法_vba批量重命名文件

GUI的后浪,如何一代更比一代强?_mcu gui库-程序员宅基地

文章浏览阅读290次。 “美”“好”产品的用户体验,始于GUI设计新数字时代的人机沟通,交互场景都将融入视觉、触觉、手势或声音等多种感官体验,“美”和“好"则是设计和更新产品体验的两大重点。所谓”美“,颜值即正义,图形用户界面要酷炫;所谓”好“,指产品要好用,比如交互界面要流畅,续航时间长等。万物互联时代,出色的图形化用户界面(GUI)成为市场共识,与智能手机界面相似的 GUI 应用被广泛部署在物联网设备中。智能物联设备的应用场景中,低资源占用和低功耗需求是实现复杂图形用户界面不易跨越的技术难点。GUI 技术变革,普惠_mcu gui库

LabVIEW中局部变量、全局变量和引用及属性节点的相关_labview中隐藏前面板控件属于功能全局变量吗-程序员宅基地

文章浏览阅读1.2w次,点赞2次,收藏20次。局部变量和全局变量首先,使用局部变量和全局变量不符合数据流的思维方式,在不同的地方使用局部变量和全局变量,对于大的成语而言,不易判断数据的流向和操作的先后顺序,隐藏着“竞争”的危险。基于性能考虑,局部变量会复制数据缓冲区。从一个局部变量读取数据时,便为相关控件的数据创建了一个新的缓冲区。如此类推,将会大大增加内存开销。如使用局部变量将大量数据从程序框图上的某个地方传递到另一个地方,通常会使_labview中隐藏前面板控件属于功能全局变量吗

随便推点

代码缩进修改-程序员宅基地

文章浏览阅读340次。修改.editrc的indent为4'indent': [ 'error', 4, { SwitchCase: 1, flatTernaryExpressions: true } ], 修改webstorm的code style indent 4转载于:htt..._"switchcase\": 1, \"flatternaryexpressions\": false, \"ignorednodes\": [ \"propert"

Chrome 的审查元素功能有哪些奇技淫巧?-程序员宅基地

文章浏览阅读2k次。https://www.zhihu.com/question/34682699

Echarts高级进阶教程:图表渲染大数据量导致卡顿加载时间慢等问题的解决方案_echarts折线图线较多时首次渲染慢-程序员宅基地

文章浏览阅读1.7w次,点赞4次,收藏49次。项目需求定义何为大量数据在近期的Echarts数据可视化大屏的开发中,遇见了大量数据加载的情况。首先,定义何为大量数据?本文的大量数据是指10000+条数据或者10M+文件容积大小的数据。对于日常的Echarts渲染图表,无非是对接api接口→ajax获取数据→Echarts渲染图表,这样的流程。但是这么简单地过程中,遇见大量数据加载时,问题就变得复杂起来了。产生的现象首次加载时间过慢,友好性和体验性极差;筛选条件,如默认1个小时,筛选24小时以上的数据时,加载数据过慢;折线图拖动时,data_echarts折线图线较多时首次渲染慢

MongoDB增删改查Python实现示例_python mongo的增删改查-程序员宅基地

文章浏览阅读106次。用Python编写的基本的MongoDB增删改查实现示例_python mongo的增删改查

完美解决win10可选更新后,usb外接键盘失灵的问题_windows10usb键盘连不上-程序员宅基地

文章浏览阅读1.1w次,点赞9次,收藏10次。完美解决win10可选更新后,usb外接键盘失灵的问题当前我的电脑版本如下图win10版本号为2004,系统版本19041.546。昨天win10可选更新后,usb外接键盘莫名其妙失灵。经过一天的研究,发现是安装了libusb-win32驱动的原因。解决方法打开设备管理器,点击“查看” -> “显示隐藏的设备,这时候就可以看到安装的libsub-win32驱动程序这时候我们只要右键把它删除即可,完美解决问题。最后吐槽,win10的可选更新是真的坑。..._windows10usb键盘连不上

【展锐】双摄帧同步踩坑_多摄帧同步时序-程序员宅基地

文章浏览阅读2.4k次,点赞6次,收藏15次。导通配置步骤:sensor_config.xml文件主摄位置添加<SensorRole>dualcam_master</SensorRole>辅摄添加<SensorRole>dualcam_slave</SensorRole>驱动文件软同步导通sensor_ic_ops sensor_name_ops_tab中添加.read_aec_info = sensor_read_aec_info即可硬件帧同步导通在stream on函数中添加判断_多摄帧同步时序

推荐文章

热门文章

相关标签