Spring Security(Spring安全框架)学习笔记(三)——返回json格式数据,适用前后端分离场景

Spring Security(Spring安全框架)学习笔记(一)简介、自定义登录页面、放过静态资源
Spring Security(Spring安全框架)学习笔记(二)登录接口,登录参数,登录回调,注销登录
Spring Security(Spring安全框架)学习笔记(三)返回json格式数据,适用前后端分离场景
Spring Security(Spring安全框架)学习笔记(四)授权操作、权限继承
Spring Security(Spring安全框架)学习笔记(五)整合Mysql数据库

一、无状态登录&有状态登录

  1. 有状态登录:登录成功,服务端存session,在服务端维护用户登录状态。
  2. 无状态登录:JSON Web Token(JWT)
    jwt简介:是目前最流行的跨域身份验证解决方案。

二、代码

1、SecurityConfig.java

package com.hx.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
        // 密码加密实例
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance(); // 采用不加密方式
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 配置用户名,密码
        //这里的配置会覆盖properties配置文件中配置的账号密码
        // 配置多个使用and连接,一个就不用加and()
        auth.inMemoryAuthentication()
                .withUser("whx")
                .password("a")
                .roles("admin")
                .and()
                .withUser("hx")
                .password("a")
                .roles("user");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "images/**");        //放过静态资源下的js,css,img资源
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {    //http安全配置
        //authorizeRequests开启配置
        http.authorizeRequests()
                .anyRequest()           //anyRequest所有请求都拦截
                .authenticated()
                .and()
                .formLogin()                        //formLogin表单配置
                .loginPage("/login.html")           //loginPage指定登录页面(登录接口)
                .loginProcessingUrl("/doLogin")     //指定登录请求接口,若不配置则与指定的loginPage相同
                .usernameParameter("uname")         //指定请求用户名的name属性
                .passwordParameter("pwd")           //指定请求密码的name属性
                //登录成功的回调
                .successHandler((req,resp,authentication) -> {  //authentication:存储用户信息
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    //将用户信息以json格式返回给前端
                    out.write(new ObjectMapper().writeValueAsString(authentication.getPrincipal()));
                    out.flush();
                    out.close();
                })
                //登录失败的回调
                .failureHandler((req,resp,exception) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    //将错误信息以json格式返回给前端
                    out.write(new ObjectMapper().writeValueAsString(exception.getMessage()));
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")       //配置退出登录地址
                .logoutSuccessHandler((req,resp,authentication) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    //将错误信息以json格式返回给前端
                    out.write(new ObjectMapper().writeValueAsString("loginout success"));
                    out.flush();
                    out.close();
                })
                .and()
                .csrf().disable()                  //关闭csrf
                .exceptionHandling()
                .authenticationEntryPoint((req,resp,e) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    resp.setStatus(401);    //设置响应状态码,401
                    PrintWriter out = resp.getWriter();
                    //将错误信息以json格式返回给前端
                    out.write(new ObjectMapper().writeValueAsString("unlogin"));
                    out.flush();
                    out.close();
                });
    }
}

2、login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="/doLogin" method="post">	<!-- 必须指定为post请求,地址为login.html -->
		用户名:<input name="uname"> <br>	<!-- 指定名称username,遵循规范 -->
		密码:<input name="pwd"> <br>	<!-- 指定名称password,遵循规范 -->
		<button type="submit">提交</button>
	</form>
</body>
</html>

3、目录结构

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Huathy-雨落江南,浮生若梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值