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