Commit dc85f68c authored by wujipeng's avatar wujipeng
Browse files

优化

parent e1ab41fe
......@@ -61,7 +61,18 @@
<dependency>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>1.19.0</version> <!-- 或最新版 -->
<version>1.19.0</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
......
package com.example.pipelinenetwork.config;
import com.example.pipelinenetwork.filter.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/login/in").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
\ No newline at end of file
......@@ -2,11 +2,14 @@ package com.example.pipelinenetwork.controller;
import com.example.pipelinenetwork.pojo.dto.LoginDTO;
import com.example.pipelinenetwork.result.Result;
import com.example.pipelinenetwork.util.JwtUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @Author: wujipeng
* @Description: TODO
......@@ -17,11 +20,17 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/login")
public class LoginController {
@Resource
private JwtUtil jwtUtil;
@PostMapping("/in")
public Result<String> loginIn(@RequestBody LoginDTO loginDTO) {
if (!loginDTO.getUsername().equals("admin") || !loginDTO.getPassword().equals("123456")) {
// 验证账号密码
if (!"admin".equals(loginDTO.getUsername()) || !"123456".equals(loginDTO.getPassword())) {
return Result.error(401, "账号或密码错误");
}
return Result.success("登录成功");
// 生成JWT Token
String token = jwtUtil.generateToken(loginDTO.getUsername());
return Result.success(token, "登录成功");
}
}
package com.example.pipelinenetwork.filter;
import com.example.pipelinenetwork.util.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtUtil jwtUtil;
public JwtAuthenticationFilter(JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws IOException {
try {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
if (jwtUtil.validateToken(token)) {
String username = jwtUtil.getUsernameFromToken(token);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
username, null, new ArrayList<>());
SecurityContextHolder.getContext().setAuthentication(authentication);
} else {
sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效");
return;
}
} else {
sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效");
return;
}
filterChain.doFilter(request, response);
} catch (Exception e) {
sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Authentication failed: " + e.getMessage());
}
}
private void sendErrorResponse(HttpServletResponse response, int status, String message) throws IOException {
response.setStatus(status);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(String.format("{\"code\": %d, \"message\": \"%s\"}", status, message));
}
}
\ No newline at end of file
package com.example.pipelinenetwork.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private long expiration;
/**
* 生成JWT Token
*/
public String generateToken(String username) {
Map<String, Object> claims = new HashMap<>();
claims.put("username", username);
return Jwts.builder()
.setClaims(claims)
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expiration))
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
/**
* 从Token中提取用户名
*/
public String getUsernameFromToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims.get("username", String.class);
}
/**
* 验证Token是否有效
*/
public boolean validateToken(String token) {
try {
Claims claims = getClaimsFromToken(token);
return !claims.getExpiration().before(new Date());
} catch (Exception e) {
return false;
}
}
/**
* 从Token中获取Claims
*/
private Claims getClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
}
\ No newline at end of file
......@@ -14,3 +14,8 @@ spring:
mybatis:
configuration:
map-underscore-to-camel-case: true
# JWT配置
jwt:
secret: MySecretKeyForJWTTokenGeneration2024VeryLongAndSecure
expiration: 86400000
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment