Spring Security--前后端json交互

简介: 前后端json交互

  successHandler

image.gif

onAuthenticationSuccess里的第一个参数是当前请求对象,第二个是响应对象,第三个是验证成功的用户信息

小技巧:ALT+enter生成lambda表达式

image.gif

我们准备一个ResBean

package org.ikun.security_demo.model;
public class ResBean {
    private Integer status;
    private String msg;
    private Object data;
    public static ResBean ok(String msg,Object data){
        return new ResBean(200,msg,data);
    }
    public static ResBean ok(String msg){
        return new ResBean(200,msg,null);
    }
    public static ResBean error(String msg,Object data){
        return new ResBean(204,msg,data);
    }
    public static ResBean error(String msg){
        return new ResBean(204,msg,null);
    }
    private ResBean(){
    }
    private ResBean(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
}

image.gif

Security里的代码

package org.ikun.security_demo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ikun.security_demo.model.ResBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //开始认证
        //设置登录,注销,表单登录不用拦截,其他请求要拦截
        http.authorizeRequests().antMatchers("/","/login.html").anonymous()
                //所有的请求,类似于shiro中的 /**
                .anyRequest()
                //必须要认证之后才能访问,类似于shiro的authc
                .authenticated()
                .and()
                //开始配置登录表单
                .formLogin()
                //配置登录页面,如果访问了一个需要登录以后才能访问的页面,那么就会自动登录到这个页面
                .loginPage("/login.html")
                //配置处理登录请求的接口,其实就是配置了过滤器里的拦截规则,将来的登录请求就会在过滤器中被处理
                .loginProcessingUrl("/doLogin")
                //配置登录表单中用户名的 key
                .usernameParameter("username")
                //配置登录表单中的密码 默认也是username 和 password
                .passwordParameter("password")
                //配置登录成功后访问的接口
               // .defaultSuccessUrl("/hello")
                //登录失败后访问的接口
                //.failureUrl("/login.html")
                //登录成功处理器
                .successHandler((request, response, authentication) -> {
                    response.setContentType("application/json;charset=utf-8");
                    ResBean resBean = ResBean.ok("登陆成功", authentication.getPrincipal());//getPrincipal()就是你的用户对象
                    String s = new ObjectMapper().writeValueAsString(resBean);
                    response.getWriter().write(s);
                })
                //关闭默认的csrf认证
                .and().csrf().disable();
    }
}

image.gif

登陆成功后,返回结果如下

image.gif

登录失败的回调亦然。failureHandler

image.gif

package org.ikun.security_demo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ikun.security_demo.model.ResBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //开始认证
        //设置登录,注销,表单登录不用拦截,其他请求要拦截
        http.authorizeRequests().antMatchers("/","/login.html").anonymous()
                //所有的请求,类似于shiro中的 /**
                .anyRequest()
                //必须要认证之后才能访问,类似于shiro的authc
                .authenticated()
                .and()
                //开始配置登录表单
                .formLogin()
                //配置登录页面,如果访问了一个需要登录以后才能访问的页面,那么就会自动登录到这个页面
                .loginPage("/login.html")
                //配置处理登录请求的接口,其实就是配置了过滤器里的拦截规则,将来的登录请求就会在过滤器中被处理
                .loginProcessingUrl("/doLogin")
                //配置登录表单中用户名的 key
                .usernameParameter("username")
                //配置登录表单中的密码 默认也是username 和 password
                .passwordParameter("password")
                //配置登录成功后访问的接口
               // .defaultSuccessUrl("/hello")
                //登录失败后访问的接口
                //.failureUrl("/login.html")
                //登录成功处理器
                .successHandler((request, response, authentication) -> {
                    response.setContentType("application/json;charset=utf-8");
                    ResBean resBean = ResBean.ok("登陆成功", authentication.getPrincipal());//getPrincipal()就是你的用户对象
                    String s = new ObjectMapper().writeValueAsString(resBean);
                    response.getWriter().write(s);
                })
                .failureHandler((request, response, exception) -> {
                    //登录失败可能有很多种原因
                    response.setContentType("application/json;charset=utf-8");
                    ResBean resBean = ResBean.ok("登陆失败");
                    if (exception instanceof BadCredentialsException){
                        resBean.setMsg("用户名或密码输入错误,登录失败");
                    }else if (exception instanceof UsernameNotFoundException){
                        //这个异常默认隐藏了,所以这个分支不会进来,怕有人试密码
                    }else if (exception instanceof LockedException){
                        resBean.setMsg("账户被锁定,登录失败");
                    }else if (exception instanceof AccountExpiredException){
                        resBean.setMsg("账户过期,登录失败");
                    }else if (exception instanceof CredentialsExpiredException){
                        resBean.setMsg("密码过期,登录失败");
                    }else if (exception instanceof DisabledException){
                        resBean.setMsg("账户被禁用,登录失败");
                    }
                    String s = new ObjectMapper().writeValueAsString(resBean);
                    response.getWriter().write(s);
                })
                //关闭默认的csrf认证
                .and().csrf().disable();
    }
}

image.gif

我们看一下效果

image.gif

ok没问题

最后介绍一个exceptionHandling

用户未登录就访问某一个页面,就会触发这个方法

.exceptionHandling()
                //用户未登录就访问某一个页面,就会触发这个方法
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setContentType("application/json;charset=utf-8");
                    ResBean resBean = ResBean.error("尚未登录,请登录");
                    String s = new ObjectMapper().writeValueAsString(resBean);
                    response.getWriter().write(s);
                })

image.gif

效果如下:

image.gif


相关文章
|
4月前
|
JSON 安全 Java
什么是JWT?如何使用Spring Boot Security实现它?
什么是JWT?如何使用Spring Boot Security实现它?
904 5
|
27天前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——封装统一返回的数据结构
本文介绍了在Spring Boot中封装统一返回的数据结构的方法。通过定义一个泛型类`JsonResult<T>`,包含数据、状态码和提示信息三个属性,满足不同场景下的JSON返回需求。例如,无数据返回时可设置默认状态码"0"和消息"操作成功!",有数据返回时也可自定义状态码和消息。同时,文章展示了如何在Controller中使用该结构,通过具体示例(如用户信息、列表和Map)说明其灵活性与便捷性。最后总结了Spring Boot中JSON数据返回的配置与实际项目中的应用技巧。
99 0
|
27天前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——使用 fastJson 处理 null
本文介绍如何使用 fastJson 处理 null 值。与 Jackson 不同,fastJson 需要通过继承 `WebMvcConfigurationSupport` 类并覆盖 `configureMessageConverters` 方法来配置 null 值的处理方式。例如,可将 String 类型的 null 转为 "",Number 类型的 null 转为 0,避免循环引用等。代码示例展示了具体实现步骤,包括引入相关依赖、设置序列化特性及解决中文乱码问题。
55 0
|
27天前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——Spring Boot 默认对Json的处理
本文介绍了在Spring Boot中返回Json数据的方法及数据封装技巧。通过使用`@RestController`注解,可以轻松实现接口返回Json格式的数据,默认使用的Json解析框架是Jackson。文章详细讲解了如何处理不同数据类型(如类对象、List、Map)的Json转换,并提供了自定义配置以应对null值问题。此外,还对比了Jackson与阿里巴巴FastJson的特点,以及如何在项目中引入和配置FastJson,解决null值转换和中文乱码等问题。
58 0
|
27天前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot中的全局异常处理——定义返回的统一 json 结构
本课主要讲解Spring Boot中的全局异常处理方法。在项目开发中,各层操作难免会遇到各种异常,若逐一处理将导致代码耦合度高、维护困难。因此,需将异常处理从业务逻辑中分离,实现统一管理与友好反馈。本文通过定义一个简化的JsonResult类(含状态码code和消息msg),结合全局异常拦截器,展示如何封装并返回标准化的JSON响应,从而提升代码质量和用户体验。
41 0
|
3月前
|
JSON 人工智能 JavaScript
大语言模型下的JSON数据格式交互
本文作者总结了在解析JSON过程中遇到的一些问题和解决方案。
|
5月前
|
JSON 前端开发 JavaScript
聊聊 Go 语言中的 JSON 序列化与 js 前端交互类型失真问题
在Web开发中,后端与前端的数据交换常使用JSON格式,但JavaScript的数字类型仅能安全处理-2^53到2^53间的整数,超出此范围会导致精度丢失。本文通过Go语言的`encoding/json`包,介绍如何通过将大整数以字符串形式序列化和反序列化,有效解决这一问题,确保前后端数据交换的准确性。
105 4
|
6月前
|
人工智能 缓存 Java
深入解析Spring AI框架:在Java应用中实现智能化交互的关键
【10月更文挑战第12天】Spring AI 是 Spring 框架家族的新成员,旨在满足 Java 应用程序对人工智能集成的需求。它支持自然语言处理、图像识别等多种 AI 技术,并提供与云服务(如 OpenAI、Azure Cognitive Services)及本地模型的无缝集成。通过简单的配置和编码,开发者可轻松实现 AI 功能,同时应对模型切换、数据安全及性能优化等挑战。
508 3
|
6月前
|
JSON 前端开发 Java
【Spring】“请求“ 之传递 JSON 数据
【Spring】“请求“ 之传递 JSON 数据
125 2
|
5月前
|
存储 JSON 监控
公司用什么软件监控电脑:JSON 在监控信息交互中的应用探索
在现代企业管理中,电脑监控软件广泛应用于保障信息安全和提升工作效率。JSON(JavaScript Object Notation)因其简洁和易读性,在监控信息的收集、传输和处理中扮演着关键角色。本文介绍了 JSON 在监控数据结构、信息传输及服务器端处理中的具体应用,展示了其在高效监控系统中的重要性。
62 0

热门文章

最新文章