SpringBoot整合SpringSecurity前后端分离实现JSON登录

在前后端分离项目中,通常是通过json格式数据传递信息,但是SpingSecurity中默认获取登录账号密码方式为通过表单提交的key/value形式过去,具体官方源码处理方式如下:

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);
	}

但是如果要处理json数据进行登录,我们可以重写UsernamePasswordAuthenticationFilter类中attemptAuthentication方法实现

创建自定义过滤器LoginAuthenticationFilter
public class LoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        //如果是application/json类型,做如下处理
        if(request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)||request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
            //以json形式处理数据
            String username = null;
            String password = null;

            try {
            	//将请求中的数据转为map
                Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                username = map.get("username");
                password = map.get("password");
            } catch (IOException e) {
                e.printStackTrace();
            }
            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);
        }
        //否则使用官方默认处理方式
        return super.attemptAuthentication(request, response);
    }
}
编写SpringSecurity配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  	@Bean
    LoginAuthenticationFilter loginAuthenticationFilter() throws Exception {
        LoginAuthenticationFilter filter = new LoginAuthenticationFilter();
        filter.setFilterProcessesUrl("/doLogin");
        filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                Hr hr = (Hr) authentication.getPrincipal();
                hr.setPassword(null);
                RespResult result = RespResult.ok("登录成功", hr);
                String msg = new ObjectMapper().writeValueAsString(result);
                writer.write(msg);
                writer.flush();
                writer.close();
            }
        });
        filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                RespResult result = RespResult.error("登录失败");;
                if (e instanceof BadCredentialsException) {
                    result.setMsg("用户名或密码错误,请检查");
                }else if(e instanceof LockedException){
                    result.setMsg("账户被锁定,请联系管理员");
                }else if(e instanceof CredentialsExpiredException){
                    result.setMsg("密码已过期,请联系管理员");
                }else if(e instanceof AccountExpiredException){
                    result.setMsg("账户已过期,请联系管理员");
                }else if(e instanceof DisabledException){
                    result.setMsg("账户被禁用,请联系管理员");
                }
                String msg = new ObjectMapper().writeValueAsString(result);
                writer.write(msg);
                writer.flush();
                writer.close();
            }
        });
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = resp.getWriter();
                        RespResult result = RespResult.ok("注销退出成功");
                        String msg = new ObjectMapper().writeValueAsString(result);
                        writer.write(msg);
                        writer.flush();
                        writer.close();
                    }
                })
                .permitAll()
                .and()
                .csrf().disable();

        http.addFilterAt(loginAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
    }
}
测试

成功

Spring Security是一个提供认证、授权和防止常见攻击的框架,它可以很好地与Spring Boot进行整合。当我们使用Spring Security进行前后端分离时,通常会使用JWT(JSON Web Token)来实现身份验证和授权。 具体的步骤如下: 1. 引入依赖:在pom.xml文件中添加Spring Security和JWT的依赖。 2. 配置Spring Security:创建一个继承自WebSecurityConfigurerAdapter的配置类,重写configure方法来配置安全规则和认证管理器。可以通过@EnableWebSecurity注解启用Spring Security。 3. 实现用户认证:创建一个实现UserDetailsService接口的类,用来从数据库或其他数据源中获取用户信息并进行认证。 4. 实现JWT的生成和验证:创建一个JWT工具类,用于生成和验证JWT。可以使用第三方库(如jjwt)来简化操作。 5. 自定义登录和登出的处理:根据具体需求,可以自定义登录失败处理和登出处理。可以通过实现AuthenticationEntryPoint接口和LogoutSuccessHandler接口来处理。 6. 配置跨域支持:如果前后端分离,前后端可能存在跨域问题。可以通过配置CorsFilter来解决跨域问题。 7. 接口保护和授权:根据需要,可以在接口上添加相应的注解来实现访问控制和权限管理。 总结一下,Spring Boot结合Spring Security和JWT,可以很好地实现前后端分离的身份验证和授权。通过配置安全规则、实现用户认证、实现JWT的生成和验证、自定义处理、跨域支持以及接口保护和授权等步骤,我们可以实现一个安全可靠的前后端分离应用程序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot整合SpringSecurity前后端分离版](https://blog.csdn.net/weixin_44283656/article/details/125166541)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值