springboot3.0.2,security6.0.1,jwt,token:body提交登录

点我下载完整源码

1pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.2</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gzz</groupId>
    <artifactId>spring-security-01</artifactId>
    <version>1.0</version>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2 jwtTools.java

package com.gzz.common;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

/**
 * @summary【JWT创建】工具
 * @author 高振中
 * @date 2023-03-01 20:20:20
 **/
public class JwtTools {

    public static void main(String[] args) {
        System.out.println(prase(create(555L)));
        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.DAY_OF_MONTH, 1);
        System.out.println(expires.getTime());
    }

    public static final String SECRET = "jwt_test";
    public static final Algorithm algorithm = Algorithm.HMAC256(SECRET);

    public static String create(Long id) {
        Map<String, Object> headers = new HashMap<>();
        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.DAY_OF_MONTH, 1);// 一天
        return JWT.create()
                .withHeader(headers) // 第一部分Header
                .withClaim("userId", id)// 第二部分Payload
                .withExpiresAt(expires.getTime()) // 第三部分Signature
                .sign(algorithm);
    }

    public static Long prase(String token) {
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        return verify.getClaim("userId").asLong();
    }

}

3 登录表单提交改成body(JSON)提交

package com.gzz.filter;

import java.io.IOException;
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 com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 表单提交改成body(JSON)提交
 */
@Slf4j
public class BodyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        User user = null;
        try {
            user = new ObjectMapper().readValue(request.getInputStream().readAllBytes(), User.class);
            log.info("user={}", user);
        } catch (IOException e) {
            log.error("user={},exception={}", user, e.getMessage(), e);
        }
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        setDetails(request, authRequest);
        return getAuthenticationManager().authenticate(authRequest);
    }
}

4 spring-security主配置类

package com.gzz.config;

import org.springframework.beans.factory.annotation.Autowired;
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.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.gzz.filter.BodyAuthenticationFilter;
import com.gzz.sys.UserService;

/**
 * @summary spring-security主配置类
 * @author 高振中
 * @date 2023-02-18 22:20:20
 **/
@Configuration
public class SecurityConfig {
    @Autowired
    private LoginSuccess loginSuccess;
    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity security) throws Exception {
        
        BodyAuthenticationFilter authFilter = new BodyAuthenticationFilter();
        authFilter.setAuthenticationSuccessHandler(loginSuccess); //重点
        authFilter.setAuthenticationManager(authenticationConfiguration.getAuthenticationManager());
        
        security//
                .authorizeHttpRequests(auth -> auth //
                        .requestMatchers("/index.html", "/fonts/**","/login").permitAll() // 这些请求(url)无需授权
                        .anyRequest())
                .formLogin((auth) -> auth//
                        .loginPage("/index.html") //
                        .loginProcessingUrl("/login") //
                        .permitAll())
                .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)//重点
                .csrf(csrf -> csrf.disable());
        return security.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private UserService service;

    public void configureGlobal(@Autowired AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(service).passwordEncoder(passwordEncoder());
    }

}

5 前端 vue3 element-ui axios

<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>body方式登录</title>
</head>
<head>
<link rel='stylesheet' type='text/css' href='fonts/element.css'>
<script type='text/javascript' src='fonts/vue.min.js'></script>
<script type='text/javascript' src='fonts/element-plus.js'></script>
<script type='text/javascript' src='fonts/axios.min.js'></script>
</head>
<body style='margin: 10px 0 10px 0'>
<h2>body方式登录,同时返回token</h2>
    <div id='app'>
      <el-row>
        <el-form-item label="用户名" prop="name">
          <el-input placeholder="请输入用户名" v-model="form.username" @keyup.enter.native="doLogin" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" v-model="form.password" @keyup.enter.native="doLogin" />
        </el-form-item>
        <el-button @click="doLogin()" type="primary">登录</el-button>
      </el-row> 
    </div>
</body>
<script>
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.interceptors.response.use(res => res.data);
const app =Vue.createApp({
    data() {
        return { form: { username: "gzz", password: "1234" } }
    },
    methods: {
        doLogin(){
            axios.post("/login",this.form).then((res) => {
                console.log(res);
                if (res.code == 200) {
                    this.$message.success("登录成功!");
                } else
                    this.$message.error(res.msg);
                });
        }
    }
});app.use(ElementPlus);app.mount("#app");
</script>
</html>

6 登录成功处理器

package com.gzz.config;

import java.io.IOException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.gzz.common.JwtTools;
import com.gzz.common.ResponseTools;
import com.gzz.common.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @summary 登录成功处理器
 * @author 高振中
 * @date 2023-02-18 22:20:20
 **/
@Component
public class LoginSuccess implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SysUser user = (SysUser) authentication.getPrincipal();
        String token = JwtTools.create(user.getId());
        user.setToken(token);
        ResponseTools.write(response, Result.success(user, "登录成功,返回token"));
    }
}

7 往客户端写JSON格式的文本工具

package com.gzz.common;

import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @summary 往客户端写JSON格式的文本工具
 * @author 高振中
 * @date 2023-02-18 22:20:20
 **/
public final class ResponseTools {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static final void write(HttpServletResponse response, Result<?> result) throws JsonProcessingException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(mapper.writeValueAsString(result));
    }
}

点我下载完整源码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,014评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,796评论 3 386
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,484评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,830评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,946评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,114评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,182评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,927评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,369评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,678评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,832评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,533评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,166评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,885评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,128评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,659评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,738评论 2 351

推荐阅读更多精彩内容