SpringSecurity登录使用JSON格式数据

在使用SpringSecurity中,大伙都知道默认的登录数据是通过key/value的形式来传递的,默认情况下不支持JSON格式的登录数据,如果有这种需求,就需要自己来解决,本文主要和小伙伴来聊聊这个话题。

基本登录方案

在说如何使用JSON登录之前,我们还是先来看看基本的登录吧,本文为了简单,SpringSecurity在使用中就不连接数据库了,直接在内存中配置用户名和密码,具体操作步骤如下:

1.创建Spring Boot工程

首先创建SpringBoot工程,添加SpringSecurity依赖,如下:

<dependency>	
    <groupId>org.springframework.boot</groupId>	
    <artifactId>spring-boot-starter-security</artifactId>	
</dependency>	
<dependency>	
    <groupId>org.springframework.boot</groupId>	
    <artifactId>spring-boot-starter-web</artifactId>	
</dependency>
2.添加Security配置

创建SecurityConfig,完成SpringSecurity的配置,如下:

@Configuration	
public class SecurityConfig extends WebSecurityConfigurerAdapter {	
    @Bean	
    PasswordEncoder passwordEncoder() {	
        return new BCryptPasswordEncoder();	
    }	
    @Override	
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {	
        auth.inMemoryAuthentication().withUser("zhangsan").password("$2a$10$2O4EwLrrFPEboTfDOtC0F.RpUMk.3q3KvBHRx7XXKUMLBGjOOBs8q").roles("user");	
    }	
    @Override	
    public void configure(WebSecurity web) throws Exception {	
    }	
    @Override	
    protected void configure(HttpSecurity http) throws Exception {	
        http.authorizeRequests()	
                .anyRequest().authenticated()	
                .and()	
                .formLogin()	
                .loginProcessingUrl("/doLogin")	
                .successHandler(new AuthenticationSuccessHandler() {	
                    @Override	
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {	
                        RespBean ok = RespBean.ok("登录成功!",authentication.getPrincipal());	
                        resp.setContentType("application/json;charset=utf-8");	
                        PrintWriter out = resp.getWriter();	
                        out.write(new ObjectMapper().writeValueAsString(ok));	
                        out.flush();	
                        out.close();	
                    }	
                })	
                .failureHandler(new AuthenticationFailureHandler() {	
                    @Override	
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {	
                        RespBean error = RespBean.error("登录失败");	
                        resp.setContentType("application/json;charset=utf-8");	
                        PrintWriter out = resp.getWriter();	
                        out.write(new ObjectMapper().writeValueAsString(error));	
                        out.flush();	
                        out.close();	
                    }	
                })	
                .loginPage("/login")	
                .permitAll()	
                .and()	
                .logout()	
                .logoutUrl("/logout")	
                .logoutSuccessHandler(new LogoutSuccessHandler() {	
                    @Override	
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {	
                        RespBean ok = RespBean.ok("注销成功!");	
                        resp.setContentType("application/json;charset=utf-8");	
                        PrintWriter out = resp.getWriter();	
                        out.write(new ObjectMapper().writeValueAsString(ok));	
                        out.flush();	
                        out.close();	
                    }	
                })	
                .permitAll()	
                .and()	
                .csrf()	
                .disable()	
                .exceptionHandling()	
                .accessDeniedHandler(new AccessDeniedHandler() {	
                    @Override	
                    public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e) throws IOException, ServletException {	
                        RespBean error = RespBean.error("权限不足,访问失败");	
                        resp.setStatus(403);	
                        resp.setContentType("application/json;charset=utf-8");	
                        PrintWriter out = resp.getWriter();	
                        out.write(new ObjectMapper().writeValueAsString(error));	
                        out.flush();	
                        out.close();	
                    }	
                });	
    }	
}

这里的配置虽然有点长,但是很基础,配置含义也比较清晰,首先提供BCryptPasswordEncoder作为PasswordEncoder,可以实现对密码的自动加密加盐,非常方便,然后提供了一个名为 zhangsan的用户,密码是 123,角色是 user,最后配置登录逻辑,所有的请求都需要登录后才能访问,登录接口是 /doLogin,用户名的key是username,密码的key是password,同时配置登录成功、登录失败以及注销成功、权限不足时都给用户返回JSON提示,另外,这里虽然配置了登录页面为 /login,实际上这不是一个页面,而是一段JSON,在LoginController中提供该接口,如下:

@RestController	
@ResponseBody	
public class LoginController {	
    @GetMapping("/login")	
    public RespBean login() {	
        return RespBean.error("尚未登录,请登录");	
    }	
    @GetMapping("/hello")	
    public String hello() {	
        return "hello";	
    }	
}

这里 /login只是一个JSON提示,而不是页面, /hello则是一个测试接口。

OK,做完上述步骤就可以开始测试了,运行SpringBoot项目,访问 /hello接口,结果如下:

640?wx_fmt=png

此时先调用登录接口进行登录,如下:

640?wx_fmt=png

登录成功后,再去访问 /hello接口就可以成功访问了。

使用JSON登录

上面演示的是一种原始的登录方案,如果想将用户名密码通过JSON的方式进行传递,则需要自定义相关过滤器,通过分析源码我们发现,默认的用户名密码提取在UsernamePasswordAuthenticationFilter过滤器中,部分源码如下:

public class UsernamePasswordAuthenticationFilter extends	
        AbstractAuthenticationProcessingFilter {	
    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;	
    public UsernamePasswordAuthenticationFilter() {	
        super(new AntPathRequestMatcher("/login", "POST"));	
    }	
    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);	
    }	
    protected String obtainPassword(HttpServletRequest request) {	
        return request.getParameter(passwordParameter);	
    }	
    protected String obtainUsername(HttpServletRequest request) {	
        return request.getParameter(usernameParameter);	
    }	
    //...	
    //...	
}

从这里可以看到,默认的用户名/密码提取就是通过request中的getParameter来提取的,如果想使用JSON传递用户名密码,只需要将这个过滤器替换掉即可,自定义过滤器如下:

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {	
    @Override	
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {	
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)	
                || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {	
            ObjectMapper mapper = new ObjectMapper();	
            UsernamePasswordAuthenticationToken authRequest = null;	
            try (InputStream is = request.getInputStream()) {	
                Map<String,String> authenticationBean = mapper.readValue(is, Map.class);	
                authRequest = new UsernamePasswordAuthenticationToken(	
                        authenticationBean.get("username"), authenticationBean.get("password"));	
            } catch (IOException e) {	
                e.printStackTrace();	
                authRequest = new UsernamePasswordAuthenticationToken(	
                        "", "");	
            } finally {	
                setDetails(request, authRequest);	
                return this.getAuthenticationManager().authenticate(authRequest);	
            }	
        }	
        else {	
            return super.attemptAuthentication(request, response);	
        }	
    }	
}

这里只是将用户名/密码的获取方案重新修正下,改为了从JSON中获取用户名密码,然后在SecurityConfig中作出如下修改:

@Override	
protected void configure(HttpSecurity http) throws Exception {	
    http.authorizeRequests().anyRequest().authenticated()	
            .and()	
            .formLogin()	
            .and().csrf().disable();	
    http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);	
}	
@Bean	
CustomAuthenticationFilter customAuthenticationFilter() throws Exception {	
    CustomAuthenticationFilter filter = new CustomAuthenticationFilter();	
    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 out = resp.getWriter();	
            RespBean respBean = RespBean.ok("登录成功!");	
            out.write(new ObjectMapper().writeValueAsString(respBean));	
            out.flush();	
            out.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 out = resp.getWriter();	
            RespBean respBean = RespBean.error("登录失败!");	
            out.write(new ObjectMapper().writeValueAsString(respBean));	
            out.flush();	
            out.close();	
        }	
    });	
    filter.setAuthenticationManager(authenticationManagerBean());	
    return filter;	
}

将自定义的CustomAuthenticationFilter类加入进来即可,接下来就可以使用JSON进行登录了,如下:

640?wx_fmt=png

好了,本文就先介绍到这里,有问题欢迎留言讨论。

▼往期精彩回顾▼ 2019新年福利,新书免费送! Docker教程 Redis教程 SpringCloud教程 Git教程 MongoDB教程 SpringBoot+Vue前后端分离开源项目-微人事 SpringBoot+Vue前后端分离开源项目-V部落

640?wx_fmt=png

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 您好,关于您的问题,我可以为您提供一些思路和建议。 首先,您可以使用 layui 发送基于 Ajax 的请求,向后端服务器发送登录请求。在发送请求之前,需要先获取用户输入的用户名和密码等登录信息。 其次,在发送登录请求时,需要将登录信息进行编码和加密,以保证登录信息的安全性。具体的编码和加密方式可以根据实际需要进行选择。 最后,后端服务器需要进行身份认证和权限控制,确保用户登录信息的有效性和合法性。在这个过程中,可以使用 Spring Security 来进行身份认证和授权管理,以保证系统的安全性和可靠性。 总之,使用 layui 发送 Spring Security登录请求需要结合前端和后端的技术,同时需要对用户登录信息进行编码和加密,以确保系统的安全性和可靠性。 ### 回答2: Layui是一款轻量级的前端UI框架,而Spring Security 是一个功能强大的基于Spring框架的安全管理框架。要使用Layui发送Spring Security登录请求,可以按照以下步骤进行操作: 1. 引入Layui相关资源文件:在HTML页面中引入Layui的CSS和JS文件,确保页面正确加载Layui框架。 2. 创建登录表单:使用Layui的表单组件,创建一个登录表单,其中包括用户名和密码的输入框,以及一个发送登录请求的按钮。 3. 编写JavaScript代码:使用Layui的JavaScript API,监听登录按钮的点击事件,获取用户输入的用户名和密码,然后通过Ajax方式将数据JSON格式发送到后端。 4. 后端处理登录请求:在后端使用Spring Security框架,配置登录接口的URL和相应的权限控制等。在接收到登录请求后,对用户名和密码进行验证,验证通过后返回相应的登录成功提示信息。 5. 前端处理登录结果:前端在接收到后端返回的登录结果后,可以根据返回的信息,使用Layui的弹层组件,展示登录成功或登录失败的提示,并进行相应的跳转或处理。 总结起来,使用Layui发送Spring Security登录请求主要包括引入相关资源文件、创建登录表单、编写JavaScript代码、后端处理登录请求和前端处理登录结果等步骤。需要注意的是,Spring Security的配置和功能较为复杂,需要熟悉相关文档和进行适当的配置才能实现登录功能的完整实现。 ### 回答3: 为了使用Layui发送Spring Security登录请求,你可以按照以下步骤进行操作: 1. 引入Layui库和Spring Security库:首先,确保你的项目中已经引入了Layui和Spring Security的相关库文件。 2. 创建登录页面:使用Layui的表单组件创建登录页面。你可以使用Layui提供的表单元素,如文本框、密码框和提交按钮等。确保表单的提交方式是POST,并且表单的action属性指向Spring Security登录验证URL。 3. 编写Spring Security配置:在Spring Security的配置类中,配置登录相关的URL、用户名、密码等信息。确保登录URL与前端Layui页面的action属性值一致。 4. 处理登录请求:在Spring Security的配置类中,编写处理登录请求的方法。该方法接收前端传来的用户名和密码参数,并对其进行验证。验证成功后,可以进行用户权限的加载等操作。 5. 响应登录结果:在Spring Security的配置类中,配置登录成功或失败后的响应。可以根据验证的结果,返回对应的页面或信息给前端。 6. 进行Layui和Spring Security的整合:在Layui的登录页面中,添加点击提交按钮时触发的事件。在事件中获取用户输入的用户名和密码,并将其通过Ajax方式发送到Spring Security登录URL。 7. 处理响应结果:根据Spring Security返回的响应结果,对登录成功或失败进行相应的处理。你可以使用Layui的弹窗组件,来显示登录成功或失败的提示信息。 总结:使用Layui发送Spring Security登录请求,主要是通过前后端的协作,实现用户信息的传递和验证。前端使用Layui库创建登录页面和发起登录请求,后端使用Spring Security库配置验证的相关信息和处理登录请求的逻辑。通过这种方式,可以实现安全的用户登录功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值