Browse Source

6.16框架搭建

622
huangqizhen 2 weeks ago
commit
3e75cc5ce1
  1. 2
      .gitattributes
  2. 33
      .gitignore
  3. 19
      .mvn/wrapper/maven-wrapper.properties
  4. 259
      mvnw
  5. 149
      mvnw.cmd
  6. 118
      pom.xml
  7. 13
      src/main/java/com/example/demo/DemoApplication.java
  8. 102
      src/main/java/com/example/demo/Util/BaseDES.java
  9. 100
      src/main/java/com/example/demo/Util/BaseDES2.java
  10. 7
      src/main/java/com/example/demo/Util/CheckIfNullUtil.java
  11. 107
      src/main/java/com/example/demo/Util/DESGB.java
  12. 227
      src/main/java/com/example/demo/Util/GoldTistV2.java
  13. 193
      src/main/java/com/example/demo/Util/JWTUtil.java
  14. 27
      src/main/java/com/example/demo/Util/ReplaceStreamFilter.java
  15. 122
      src/main/java/com/example/demo/Util/RequestWrapper.java
  16. 22
      src/main/java/com/example/demo/Util/TokenPayload.java
  17. 54
      src/main/java/com/example/demo/Util/UploadUtil.java
  18. 46
      src/main/java/com/example/demo/config/RedisConfig.java
  19. 17
      src/main/java/com/example/demo/config/WebClientConfig.java
  20. 16
      src/main/java/com/example/demo/config/WebConfig.java
  21. 49
      src/main/java/com/example/demo/domain/vo/Result.java
  22. 26
      src/main/java/com/example/demo/password/PasswordGenerator.java
  23. 146
      src/main/java/com/example/demo/security/SecurityConfig.java
  24. 292
      src/main/java/com/example/demo/security/TokenFilter.java
  25. 43
      src/main/java/com/example/demo/security/UploadFilter.java
  26. 91
      src/main/resources/application.yml
  27. 13
      src/test/java/com/example/demo/DemoApplicationTests.java

2
.gitattributes

@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

33
.gitignore

@ -0,0 +1,33 @@
HELP.md
target/
.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

19
.mvn/wrapper/maven-wrapper.properties

@ -0,0 +1,19 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.10/apache-maven-3.9.10-bin.zip

259
mvnw

@ -0,0 +1,259 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

149
mvnw.cmd

@ -0,0 +1,149 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

118
pom.xml

@ -0,0 +1,118 @@
<?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 https://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.3.12</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>demo</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>3.0.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

13
src/main/java/com/example/demo/DemoApplication.java

@ -0,0 +1,13 @@
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

102
src/main/java/com/example/demo/Util/BaseDES.java

@ -0,0 +1,102 @@
package com.example.demo.Util;
import javax.crypto.Cipher;
import java.security.Key;
public class BaseDES {
private static String strDefaultKey = "98hltleg";
private Cipher encryptCipher = null;
private Cipher decryptCipher = null;
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
while (intTmp < 0) {
intTmp = intTmp + 256;
}
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
public static byte[] hexStr2ByteArr(String strIn) {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
public BaseDES() throws Exception {
this(strDefaultKey);
}
public BaseDES(String strKey) throws Exception {
Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
public byte[] encrypt(byte[] arrB) throws Exception {
return encryptCipher.doFinal(arrB);
}
public String encrypt(String strIn) throws Exception {
return byteArr2HexStr(encrypt(strIn.getBytes()));
}
public byte[] decrypt(byte[] arrB) throws Exception {
return decryptCipher.doFinal(arrB);
}
public String decrypt(String strIn) throws Exception {
return new String(decrypt(hexStr2ByteArr(strIn)));
}
private Key getKey(byte[] arrBTmp) {
byte[] arrB = new byte[8];
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key;
}
public static void main(String args[]) {
try {
BaseDES d = new BaseDES();
String encryptedText = d.encrypt("94616995");
System.out.println("加密结果:" + encryptedText);
System.out.println("加密字符串:90005179》"+d.encrypt("90005179"));
System.out.println("解密字符串:6aaef5277c050f7ae383f816651098ff》"+d.decrypt("6aaef5277c050f7ae383f816651098ff"));
} catch (Exception e) {
e.printStackTrace();
}
}
}

100
src/main/java/com/example/demo/Util/BaseDES2.java

@ -0,0 +1,100 @@
package com.example.demo.Util;
import javax.crypto.Cipher;
import java.security.Key;
public class BaseDES2 {
private static String strDefaultKey = "gold20@)";
private Cipher encryptCipher = null;
private Cipher decryptCipher = null;
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
while (intTmp < 0) {
intTmp = intTmp + 256;
}
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
public static byte[] hexStr2ByteArr(String strIn) {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
public BaseDES2() throws Exception {
this(strDefaultKey);
}
public BaseDES2(String strKey) throws Exception {
Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
public byte[] encrypt(byte[] arrB) throws Exception {
return encryptCipher.doFinal(arrB);
}
public String encrypt(String strIn) throws Exception {
return byteArr2HexStr(encrypt(strIn.getBytes()));
}
public byte[] decrypt(byte[] arrB) throws Exception {
return decryptCipher.doFinal(arrB);
}
public String decrypt(String strIn) throws Exception {
return new String(decrypt(hexStr2ByteArr(strIn)));
}
private Key getKey(byte[] arrBTmp) {
byte[] arrB = new byte[8];
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key;
}
public static void main(String args[]) {
try {
BaseDES2 d = new BaseDES2();
String encryptedText = d.encrypt("30003761");
System.out.println("加密结果:" + encryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}

7
src/main/java/com/example/demo/Util/CheckIfNullUtil.java

@ -0,0 +1,7 @@
package com.example.demo.Util;
public class CheckIfNullUtil {
public static <T> T defaultIfNull(T value, T defaultValue) {
return value != null ? value : defaultValue;
}
}

107
src/main/java/com/example/demo/Util/DESGB.java

@ -0,0 +1,107 @@
package com.example.demo.Util;
import javax.crypto.Cipher;
import java.security.Key;
public class DESGB {
private static String strDefaultKey = "testhlsoft";
private Cipher encryptCipher = null;
private Cipher decryptCipher = null;
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
while (intTmp < 0) {
intTmp = intTmp + 256;
}
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
public static byte[] hexStr2ByteArr(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
public DESGB() throws Exception {
this(strDefaultKey);
}
public DESGB(String strKey) throws Exception {
Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
public byte[] encrypt(byte[] arrB) throws Exception {
return encryptCipher.doFinal(arrB);
}
public String encrypt(String strIn) throws Exception {
return byteArr2HexStr(encrypt(strIn.getBytes()));
}
public byte[] decrypt(byte[] arrB) throws Exception {
return decryptCipher.doFinal(arrB);
}
/**
* @功能描述: 解决中文乱码问题
* @开发人员: 弘历研发部 刘志红 2024-1-28上午11:27:38 创建
* @参数介绍: @param strIn
* @参数介绍: @return
* @参数介绍: @throws Exception
* @返回数据: String
* @版本编号: V1.0
*/
public String decrypt(String strIn) throws Exception {
return new String(decrypt(hexStr2ByteArr(strIn)),"UTF-8");
}
private Key getKey(byte[] arrBTmp) throws Exception {
byte[] arrB = new byte[8];
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key;
}
public static void main(String args[]) {
try {
DESGB d = new DESGB();
System.out.println(d.decrypt("d19f27abb3486c689304600788c604e700abf96d6bd1c9ca"));
} catch (Exception e) {
e.printStackTrace();
}
}
}

227
src/main/java/com/example/demo/Util/GoldTistV2.java

@ -0,0 +1,227 @@
package com.example.demo.Util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* @开发目的: 测试使用
* @开发人员: 弘历研发部 刘志红
* @开发时间: 2024-1-26下午1:42:18
* @软件版本: V1.0
*/
public class GoldTistV2 {
private static String url = "http://hcm.rzfwq.com/hwhcnewA/";
/**
* <pre>
* 发送不带参数的GET的HTTP请求
* </pre>
*
* @param reqUrl HTTP请求URL
* @return HTTP响应的字符串
*/
public static String doGet(String reqUrl) {
HttpURLConnection url_con = null;
String responseContent = null;
try {
StringBuffer params = new StringBuffer();
String queryUrl = reqUrl;
int paramIndex = reqUrl.indexOf("?");
if (paramIndex > 0) {
queryUrl = reqUrl.substring(0, paramIndex);
String parameters = reqUrl.substring(paramIndex + 1, reqUrl.length());
String[] paramArray = parameters.split("&");
for (int i = 0; i < paramArray.length; i++) {
String string = paramArray[i];
int index = string.indexOf("=");
if (index > 0) {
String parameter = string.substring(0, index);
String value = string.substring(index + 1, string.length());
params.append(parameter);
params.append("=");
params.append(URLEncoder.encode(value, "UTF-8"));
params.append("&");
}
}
params = params.deleteCharAt(params.length() - 1);
}
URL url = new URL(queryUrl);
url_con = (HttpURLConnection) url.openConnection();
url_con.setRequestMethod("GET");
System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(500000));// 单位毫秒jdk1.4换成这个,连接超时
System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(500000)); // 单位毫秒jdk1.4换成这个,读操作超时
// url_con.setConnectTimeout(5000);//单位毫秒jdk
// 1.5换成这个,连接超时
// url_con.setReadTimeout(5000);//单位毫秒jdk 1.5换成这个,读操作超时
url_con.setDoOutput(true);
byte[] b = params.toString().getBytes();
url_con.getOutputStream().write(b, 0, b.length);
url_con.getOutputStream().flush();
url_con.getOutputStream().close();
InputStream in = url_con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String tempLine = rd.readLine();
StringBuffer temp = new StringBuffer();
String crlf = System.getProperty("line.separator");
while (tempLine != null) {
temp.append(tempLine);
temp.append(crlf);
tempLine = rd.readLine();
}
responseContent = temp.toString();
rd.close();
in.close();
}
catch (IOException e) {
e.printStackTrace();
}finally {
if (url_con != null) {
url_con.disconnect();
}
}
return responseContent;
}
/**
* 生成 MD5 签名
*
* @param params 待签名的参数数组
* @param secretKey 密钥
* @return 签名的 MD5 哈希值若出现异常则返回 null
*/
public static String generateSignature(String[] params, String secretKey) {
// 将参数数组转换为列表以便进行排序
List<String> paramList = new ArrayList<String>();
Collections.addAll(paramList, params);
// 对参数列表进行排序
Collections.sort(paramList);
// 拼接排序后的参数
StringBuilder paramString = new StringBuilder();
for (String param : paramList) {
paramString.append(param);
}
// 拼接密钥
paramString.append(secretKey);
try {
// 获取 MD5 消息摘要实例
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算摘要明确指定字符编码为 UTF-8
byte[] digest = md.digest(paramString.toString().getBytes("UTF-8"));
// 将字节数组转换为十六进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/**
* @功能描述: 生成随机数
* @开发人员: 弘历研发部 刘志红 2024-1-25下午5:45:36 创建
* @参数介绍: @param len
* @参数介绍: @return
* @返回数据: String
* @版本编号: V1.0
*/
public static String RandomUid(int len){
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz23456789";
StringBuilder result = new StringBuilder();
Random rnd = new Random();
int strlen = characters.length();
while (result.length() < 8) { // length of the random string.
int index = (int) (rnd.nextFloat() * strlen);
result.append(characters.charAt(index));
}
return "JB"+result.toString();
}
/**
* 类型说明
*
55 免费金币 金币系统退商品
56 永久金币 金币系统退商品
57 任务金币 金币系统退商品
58 免费金币 金币系统退金币
59 任务金币 金币系统退金币
* @功能描述: 金币平台更新客户金币
* @开发人员: 弘历研发部 刘志红 2025-3-21下午1:58:13 创建
* @参数介绍: @param jwcode 账号
* @参数介绍: @param lx 类型
* @参数介绍: @param jbs 金币数量
* @参数介绍: @param remark 备注
* @参数介绍: @param yjjb 永久金币
* @参数介绍: @param czr 操作人
* @参数介绍: @param goodsname 商品名称
* @参数介绍: @return
* @返回数据: String 返回状态1加成功2减成功其他失败 -5 金币不足 -6 类型错误 -7签名错误
* @版本编号: V1.0
*/
public static String addCoinNew(String jwcode, int lx, double jbs,
String remark,double yjjb,String czr,String goodsname){
//查错误使用
String sjzfc = RandomUid(10);
String resp = "";
try {
DESGB desjbkc = new DESGB("Jbxt.205");
String sk = "jwcode="+jwcode+"&number="+jbs+"&uid="+sjzfc+"&remark="+
remark+"&czr="+czr+"&yjjb="+yjjb+"&czpt=4&goodsname="+goodsname+"&type="+lx;
System.out.println("签名前:"+sk);
String sign = generateSignature(sk.split("&"),"222251821eba7efab6d48e388b8f6baa");
sk = desjbkc.encrypt(new String(sk.getBytes(), "UTF-8"));
System.out.println(url+"goldUpdate_sign.gold?app=4&sk="+sk+"&sign="+sign);
resp = doGet(url+"goldUpdate_sign.gold?app=4&sk="+sk+"&sign="+sign);
}catch (Exception e){
System.out.println("加金币异常"+e.toString());
}
System.out.println(resp);
return resp;
}
public static void main(String[] args) throws Exception {
//调用demo
addCoinNew("94226013",64,1,"充1金币测试",0,"黄其振 ","文章11");
}
}

193
src/main/java/com/example/demo/Util/JWTUtil.java

@ -0,0 +1,193 @@
package com.example.demo.Util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
/**
* JWT的工具类
*/
public class JWTUtil {
//有效期为
public static final Long JWT_TTL = 24*60 * 60 *1000L;// 60 * 60 *1000 一个小时
//设置 密钥
public static final String JWT_KEY = "bobzyh";
public static String getUUID(){
String token = UUID.randomUUID().toString().replaceAll("-", "");
return token;
}
/**
* 用户信息创建JWT,默认有效期30分钟
* @param user
* @return
*/
public static String createJWT(UserDetails user) {
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(user);
System.out.println("用户的JSON");
System.out.println(json);
return createJWT(json, JWT_TTL);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
* 用户信息创建JWT, 指定有效期单位秒
* @param user
* @param ttlMillis
* @return
*/
public static String createJWT(UserDetails user, Long ttlMillis) {
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(user);
return createJWT(json, ttlMillis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
* 生成jtw
* @param subject token中要存放的数据json格式
* @return
*/
public static String createJWT(String subject) {
JwtBuilder builder = getJwtBuilder(subject, 30*60*1000L, getUUID());// 设置过期时间
return builder.compact();
}
/**
* 生成jtw
* @param subject token中要存放的数据json格式
* @param ttlMillis token超时时间
* @return
*/
public static String createJWT(String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
return builder.compact();
}
private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //加密算法
SecretKey secretKey = generalKey(); //密钥
long nowMillis = System.currentTimeMillis(); //当前时间
Date now = new Date(nowMillis);
if(ttlMillis==null){
ttlMillis= JWTUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis); //过期时间
return Jwts.builder()
.setId(uuid) //唯一的ID
.setSubject(subject) // 主题 可以是JSON数据
.setIssuer("sg") // 签发者
.setIssuedAt(now) // 签发时间
.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
.setExpiration(expDate);
}
/**
* 创建token
* @param id
* @param subject
* @param ttlMillis
* @return
*/
public static String createJWT(String id, String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
return builder.compact();
}
/**
* 生成加密后的秘钥 secretKey
* @return
*/
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getDecoder().decode(JWTUtil.JWT_KEY);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
/**
* 解析
*
* @param jwt
* @return
* @throws Exception
*/
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = generalKey();
System.out.println(jwt);
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(jwt)
.getBody();
}
/**
* 解析为用户
* @param jwt
* @return
* @throws Exception
*/
public static UserDetails getUserDetails(String jwt, Class<? extends UserDetails> cls) throws Exception {
Claims claims = JWTUtil.parseJWT(jwt);
String json = claims.getSubject();
ObjectMapper mapper = new ObjectMapper();
UserDetails user = null;
user = mapper.readValue(json, cls);
return user;
}
public static UserDetails getUserDetailsList(String jwt, Class<? extends UserDetails> ...cls) throws Exception {
Claims claims = JWTUtil.parseJWT(jwt);
String json = claims.getSubject();
ObjectMapper mapper = new ObjectMapper();
if (cls != null && cls.length > 0) {
for (Class<? extends UserDetails> cl : cls) {
try {
UserDetails user = mapper.readValue(json, cl);
return user;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
return null;
}
// public static void main(String[] args) throws Exception {
//
// // 加密
// String jwt = createJWT("2123");
// System.out.println(jwt);
//
// // 解密
// Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2Y2QzZGU0NWRiN2I0MjVlOWJlZTAzYzUyNjY2ODhhYiIsInN1YiI6IjIxMjMiLCJpc3MiOiJzZyIsImlhdCI6MTcxMDgzMTc4NCwiZXhwIjoxNzEwODM1Mzg0fQ.k6RPyIvKX-mrS26YbyaDNVLlihGqTQDeLj2gsrNokCk");
// String subject = claims.getSubject();
// System.out.println(subject);
//
// }
}

27
src/main/java/com/example/demo/Util/ReplaceStreamFilter.java

@ -0,0 +1,27 @@
package com.example.demo.Util;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
//替换HttpServletRequest
@Slf4j
public class ReplaceStreamFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("StreamFilter初始化...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletRequest requestWrapper = new RequestWrapper((HttpServletRequest) request);
chain.doFilter(requestWrapper, response);
}
@Override
public void destroy() {
log.info("StreamFilter销毁...");
}
}

122
src/main/java/com/example/demo/Util/RequestWrapper.java

@ -0,0 +1,122 @@
package com.example.demo.Util;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.Charset;
//包装HttpServletRequest目的是让其输入流可重复读
@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
/**
* 存储body数据的容器
*/
private final byte[] body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
// 将body数据存储起来
String bodyStr = getBodyString(request);
body = bodyStr.getBytes(Charset.defaultCharset());
}
/**
* 获取请求Body
*
* @param request request
* @return String
*/
public String getBodyString(final ServletRequest request) {
try {
return inputStream2String(request.getInputStream());
} catch (IOException e) {
log.error("", e);
throw new RuntimeException(e);
}
}
/**
* 获取请求Body
*
* @return String
*/
public String getBodyString() {
final InputStream inputStream = new ByteArrayInputStream(body);
return inputStream2String(inputStream);
}
/**
* 将inputStream里的数据读取出来并转换成字符串
*
* @param inputStream inputStream
* @return String
*/
private String inputStream2String(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
log.error("", e);
throw new RuntimeException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.error("", e);
}
}
}
return sb.toString();
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}

22
src/main/java/com/example/demo/Util/TokenPayload.java

@ -0,0 +1,22 @@
package com.example.demo.Util;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class TokenPayload {
@JsonProperty("token")
private String token;
private String jwcode;
private String password;
private String pageNum;
private String pageSize;
}

54
src/main/java/com/example/demo/Util/UploadUtil.java

@ -0,0 +1,54 @@
package com.example.demo.Util;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
public class UploadUtil {
/**
* 将文件保存到指定路径
* @return
*/
public static String save(MultipartFile file, String path) {
// 验证文件是不是传了
if (file.getSize() <= 0) {
return null;
}
// 验证文件夹是否存在
File pathFile = new File(path);
if (!pathFile.exists()) {
// 创建
if (!pathFile.mkdirs()) {
return null;
}
}
// 生UUID作为新的文件名
String fileName = UUID.randomUUID().toString();
String oldName = file.getOriginalFilename();
if (oldName.lastIndexOf(".")>=0) {
String suffix = oldName.substring(oldName.lastIndexOf("."));
fileName += suffix;
}
// 创建一个文件流
try (OutputStream out = new FileOutputStream(path + fileName) ){
// 把上传的文件,写到这个流里面
out.write(file.getBytes());
// 写成功了
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}

46
src/main/java/com/example/demo/config/RedisConfig.java

@ -0,0 +1,46 @@
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class RedisConfig {
@Autowired
CacheProperties cacheProperties;
@Bean
public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
CacheProperties.Redis redis = cacheProperties.getRedis();
if (redis.getTimeToLive() != null) {
config = config.entryTtl(redis.getTimeToLive());
}
if (!redis.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redis.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}

17
src/main/java/com/example/demo/config/WebClientConfig.java

@ -0,0 +1,17 @@
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient() {
return WebClient.builder()
.baseUrl("http://hwapi.rzfwq.com")
.build();
}
}

16
src/main/java/com/example/demo/config/WebConfig.java

@ -0,0 +1,16 @@
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${upload.path}")
private String path;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:" + path);
}
}

49
src/main/java/com/example/demo/domain/vo/Result.java

@ -0,0 +1,49 @@
package com.example.demo.domain.vo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code;
private String msg;
private Object data;
public static Result success(Integer code, String msg, Object data) {
return new Result(code, msg, data);
}
public static Result success(Integer code, Object data) {
return success(code, "操作成功", data);
}
public static Result success(String msg, Object data) {return success(200, msg, data);}
public static Result success(Object data){
return success(200, data);
}
public static Result success(){
return success(null);
}
public static Result error(Integer code, String msg, Object data){
return new Result(code, msg, data);
}
public static Result error(Integer code, String msg){
return error(code, msg, null);
}
public static Result error(String msg){
return error(0, msg);
}
public String toJson() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(this);
}
}

26
src/main/java/com/example/demo/password/PasswordGenerator.java

@ -0,0 +1,26 @@
package com.example.demo.password;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.Scanner;
public class PasswordGenerator {
public static void main(String[] args) {
// 创建 BCryptPasswordEncoder 实例
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// 使用 Scanner 读取用户输入的密码
Scanner scanner = new Scanner(System.in);
System.out.print("请输入原密码: ");
String rawPassword = scanner.nextLine();
// 生成加密后的密码
String encodedPassword = passwordEncoder.encode(rawPassword);
// 输出加密后的密码
System.out.println("加密后的密码: " + encodedPassword);
// 关闭 Scanner
scanner.close();
}
}

146
src/main/java/com/example/demo/security/SecurityConfig.java

@ -0,0 +1,146 @@
package com.example.demo.security;
import com.example.demo.domain.vo.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
/**
* SpringSecurity的配置文件
*/
@Configuration
@EnableWebSecurity // 开启Security的支持
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法注解
public class SecurityConfig {
@Autowired
TokenFilter tokenFilter;
// 核心配置 配置一个过滤器链
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
// 这里可以对httpSecurity进行详细的配置 链式调用的配置方式
http.formLogin(AbstractHttpConfigurer::disable) // 方法引用禁用表单登录
.logout(AbstractHttpConfigurer::disable) // 禁用默认退出
.csrf(AbstractHttpConfigurer::disable) // 禁用csrf的保护分布式的前后端分离的项目
// 设定CORS
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
// 禁用Session,
.sessionManagement( session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// 用户未登录的处理
.exceptionHandling( exception -> exception.authenticationEntryPoint(authenticationEntryPoint()))
// 用户权限不足的处理
.exceptionHandling( exception -> exception.accessDeniedHandler(accessDeniedHandler()))
// 配置路径拦截
.authorizeHttpRequests( request ->
request
.requestMatchers( HttpMethod.POST,
// 用户不登录就可以访问的路径
"/admin/login","/upload/**","/detailY/ERP","/home/java/haiwaiyanfa/gold1/**","/home/java/haiwaiyanfa/**").permitAll()
.requestMatchers(
"/error","alipay/**","/upload/**","/home/java/haiwaiyanfa/gold1/**","/home/java/haiwaiyanfa/**"
).permitAll()
.anyRequest().authenticated() // 其它路径必须要登录后才能访问
);
http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class); // 然后是TokenFilter
return http.build();
}
/**
* 1. 配置认证管理器
* @param config
* @return
* @throws Exception
*/
@Bean
protected AuthenticationManager authenticationManager(
AuthenticationConfiguration config ) throws Exception {
return config.getAuthenticationManager();
}
/**
* 2. 密码编码器
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 3. 用户未登录时的错误处理
* @return
*/
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
return ( request, response, authException) -> {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
response.setContentType("application/json; charset=utf-8");
response.getWriter().write(Result.error("用户未登录").toJson());
};
}
/**
* 4. 权限不足时的处理
* @return
*/
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return ( request, response, authException) -> {
response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403
response.setContentType("application/json; charset=utf-8");
response.getWriter().write(Result.error("当前用户权限不足!").toJson());
};
}
/**
* 5. 配置跨域请求
* @return
*/
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*"); // 允许任何的源
config.addAllowedMethod("*"); // 允许任何的HTTP请求方式
config.addAllowedHeader("*"); // 允许任何的HTTP头
config.setAllowCredentials(true); // 允许证书
config.setMaxAge(3600L); // 设置浏览器预检的时间
// 生成源
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}

292
src/main/java/com/example/demo/security/TokenFilter.java

@ -0,0 +1,292 @@
//package com.example.demo.security;
//
//
//import com.example.demo.Util.JWTUtil;
//import com.example.demo.Util.RequestWrapper;
//import com.example.demo.domain.entity.Admin;
//import jakarta.servlet.FilterChain;
//import jakarta.servlet.ServletException;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import org.springframework.core.annotation.Order;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
//import org.springframework.stereotype.Component;
//import org.springframework.util.ObjectUtils;
//import org.springframework.util.StringUtils;
//import org.springframework.web.filter.OncePerRequestFilter;
//import java.io.IOException;
//
//
//@Component
//public class TokenFilter extends OncePerRequestFilter {
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// // 取Token 生成登录信息
// String token = request.getHeader("token");
//
//
// System.out.println(token+"123132132");
//
// // token不为空
// if (StringUtils.hasText(token)){
// try {
// UserDetails userDetails = JWTUtil.getUserDetailsList(token, Admin.class);
// if ( ! ObjectUtils.isEmpty(userDetails)) {
// // 将这个用户注册到Security中
// UsernamePasswordAuthenticationToken authenticationToken
// = new UsernamePasswordAuthenticationToken(
// userDetails, null,
// userDetails.getAuthorities());
// authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// SecurityContextHolder.getContext().setAuthentication(authenticationToken);
// }
// } catch (Exception e) {
// e.printStackTrace();
// // Token无效
// }
// }
// // 过滤器放行
// filterChain.doFilter(request, response);
// }
//}
//package com.example.demo.security;
//
//import com.example.demo.Util.JWTUtil;
//import com.example.demo.Util.RequestWrapper;
//import com.example.demo.Util.TokenPayload;
//import com.example.demo.domain.entity.Admin;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import jakarta.servlet.FilterChain;
//import jakarta.servlet.ServletException;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import org.springframework.core.annotation.Order;
//import org.springframework.security.access.prepost.PreFilter;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
//import org.springframework.stereotype.Component;
//import org.springframework.util.ObjectUtils;
//import org.springframework.util.StringUtils;
//import org.springframework.web.filter.OncePerRequestFilter;
//import java.io.IOException;
//import java.io.InputStream;
//
//
//@Component
//public class TokenFilter extends OncePerRequestFilter {
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
// throws ServletException, IOException {
// // 使用RequestWrapper包装原始的HttpServletRequest使其输入流可以被重复读取
// RequestWrapper requestWrapper = new RequestWrapper(request);
// // 确保请求体只被读取一次
// boolean hasRequestBody = "POST".equals(requestWrapper.getMethod());
// System.out.println("/*-/*-/*"+requestWrapper.getBodyString());
// if (hasRequestBody) {
// // 获取输入流
// InputStream inputStream = requestWrapper.getInputStream();
// // 使用Jackson ObjectMapper解析JSON
// ObjectMapper objectMapper = new ObjectMapper();
// TokenPayload tokenPayload = objectMapper.readValue(inputStream, TokenPayload.class);
//
// // 检查tokenPayload中是否存在token属性并且这个属性不为空
// String token = tokenPayload.getToken();
// if (StringUtils.hasText(token)) {
// try {
// UserDetails userDetails = JWTUtil.getUserDetailsList(token, Admin.class);
// if (!ObjectUtils.isEmpty(userDetails)) {
// // 将这个用户注册到Security中
// UsernamePasswordAuthenticationToken authenticationToken
// = new UsernamePasswordAuthenticationToken(
// userDetails, null,
// userDetails.getAuthorities());
// authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(requestWrapper));
// SecurityContextHolder.getContext().setAuthentication(authenticationToken);
// }
// } catch (Exception e) {
// e.printStackTrace();
// // Token无效可以在这里添加相应的处理逻辑例如返回401状态码等
// }
// }
// }
// filterChain.doFilter(requestWrapper, response); // 注意这里使用requestWrapper
// }
//}
//package com.example.demo.security;
//
//import com.example.demo.Util.JWTUtil;
//import com.example.demo.Util.RequestWrapper;
//import com.example.demo.Util.TokenPayload;
//import com.example.demo.domain.entity.Admin;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import jakarta.servlet.FilterChain;
//import jakarta.servlet.ServletException;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import org.springframework.core.annotation.Order;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
//import org.springframework.stereotype.Component;
//import org.springframework.util.ObjectUtils;
//import org.springframework.util.StringUtils;
//import org.springframework.web.filter.OncePerRequestFilter;
//import java.io.IOException;
//import java.io.InputStream;
//
//@Component
//public class TokenFilter extends OncePerRequestFilter {
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
// throws ServletException, IOException {
// // 检查是否是上传请求
// boolean isUploadRequest = request.getRequestURI().startsWith("/upload");
// System.out.println(request.getRequestURI());
// System.out.println(isUploadRequest);
// if (isUploadRequest) {
// // 如果是上传请求直接将请求传递给下一个过滤器或目标资源
// filterChain.doFilter(request, response);
// return;
// } else {
// // 使用RequestWrapper包装原始的HttpServletRequest使其输入流可以被重复读取
// RequestWrapper requestWrapper = new RequestWrapper(request);
// System.out.println(request);
// // 确保请求体只被读取一次
// boolean hasRequestBody = "POST".equals(requestWrapper.getMethod());
// if (hasRequestBody) {
// // 获取输入流
// InputStream inputStream = requestWrapper.getInputStream();
// // 使用Jackson ObjectMapper解析JSON
// ObjectMapper objectMapper = new ObjectMapper();
// TokenPayload tokenPayload = objectMapper.readValue(inputStream, TokenPayload.class);
//
// // 检查tokenPayload中是否存在token属性并且这个属性不为空
// String token = tokenPayload.getToken();
// if (StringUtils.hasText(token)) {
// try {
// UserDetails userDetails = JWTUtil.getUserDetailsList(token, Admin.class);
// if (!ObjectUtils.isEmpty(userDetails)) {
// // 将这个用户注册到Security中
// UsernamePasswordAuthenticationToken authenticationToken
// = new UsernamePasswordAuthenticationToken(
// userDetails, null,
// userDetails.getAuthorities());
// authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(requestWrapper));
// SecurityContextHolder.getContext().setAuthentication(authenticationToken);
// }
// } catch (Exception e) {
// e.printStackTrace();
// // Token无效可以在这里添加相应的处理逻辑例如返回401状态码等
// }
// }
// }
// // 非上传请求继续执行过滤器链
// filterChain.doFilter(requestWrapper, response);
// }
// }
//}
package com.example.demo.security;
import com.example.demo.Util.JWTUtil;
import com.example.demo.Util.RequestWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
@Component
public class TokenFilter extends OncePerRequestFilter {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 检查是否是上传请求
boolean isErpRequest = request.getRequestURI().startsWith("/ERP") || request.getRequestURI().contains("ERP");
boolean isUploadRequest = request.getRequestURI().startsWith("/upload");
System.out.println(request.getRequestURI());
System.out.println(isUploadRequest);
if (isUploadRequest ) {
// 如果是上传请求直接将请求传递给下一个过滤器或目标资源
filterChain.doFilter(request, response);
return;
} else {
// 使用RequestWrapper包装原始的HttpServletRequest使其输入流可以被重复读取
RequestWrapper requestWrapper = new RequestWrapper(request);
System.out.println(request);
// 确保请求体只被读取一次
boolean hasRequestBody = "POST".equals(requestWrapper.getMethod());
if (hasRequestBody) {
// 获取输入流
InputStream inputStream = requestWrapper.getInputStream();
try {
// 尝试将输入流转换为Map<String, Object>
Map<String, Object> jsonMap = objectMapper.readValue(inputStream, new TypeReference<Map<String, Object>>() {});
// 提取并处理token字段
String token = (String) jsonMap.get("token");
if (StringUtils.hasText(token)) {
processToken(token, requestWrapper);
}
// 处理其他字段如recharge列表
// 这里可以根据需要进一步解析其他字段
} catch (JsonProcessingException e) {
e.printStackTrace();
// JSON解析失败可以在这里添加相应的处理逻辑例如返回400状态码等
}
}
// 非上传请求继续执行过滤器链
filterChain.doFilter(requestWrapper, response);
}
}
private void processToken(String token, HttpServletRequest request) {
if (StringUtils.hasText(token)) {
try {
UserDetails userDetails = JWTUtil.getUserDetailsList(token, Admin.class);
if (!ObjectUtils.isEmpty(userDetails)) {
// 将这个用户注册到Security中
UsernamePasswordAuthenticationToken authenticationToken
= new UsernamePasswordAuthenticationToken(
userDetails, null,
userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
} catch (Exception e) {
e.printStackTrace();
// Token无效可以在这里添加相应的处理逻辑例如返回401状态码等
}
}
}
}

43
src/main/java/com/example/demo/security/UploadFilter.java

@ -0,0 +1,43 @@
package com.example.demo.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartResolver;
import java.io.IOException;
@Component
public class UploadFilter extends OncePerRequestFilter {
private final MultipartResolver multipartResolver;
public UploadFilter(MultipartResolver multipartResolver) {
this.multipartResolver = multipartResolver;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 检查请求是否为上传请求这里假设上传请求的路径以 "/upload" 开头
boolean isUploadRequest = request.getRequestURI().startsWith("/upload");
System.out.println(isUploadRequest);
System.out.println("MultipartResolver: " + multipartResolver);
if (isUploadRequest ) {
System.out.println("执行upload-------------------------------");
// 如果是上传请求且Content-Type为multipart/form-data直接将请求传递给下一个过滤器或目标资源
filterChain.doFilter(request, response);
} else {
// 如果不是上传请求执行一些自定义逻辑
// 例如可以在这里添加令牌验证或其他安全检查
// 继续执行过滤器链
filterChain.doFilter(request, response);
}
}
}

91
src/main/resources/application.yml

@ -0,0 +1,91 @@
spring:
jackson:
deserialization:
fail-on-unknown-properties: false
datasource:
# mysql1:
# jdbc-url: jdbc:mysql://54.251.137.151:10701/hwgold?serverTimezone=Asia/Shanghai
# username: hwgold
# password: AGX4Z3YMxiCG3GR2
# driver-class-name: com.mysql.cj.jdbc.Driver
# hikari:
# pool-name: mysql1HikariCP
# maximum-pool-size: 10
mysql1:
jdbc-url: jdbc:mysql://39.101.133.168:3306/hwgold?serverTimezone=Asia/Shanghai
username: hwgold
password: AGX4Z3YMxiCG3GR2
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: mysql1HikariCP
maximum-pool-size: 10
mysql2:
jdbc-url: jdbc:mysql://39.101.133.168:3306/hljw?serverTimezone=Asia/Shanghai
username: hljw
password: 5dmWCCKfEk3TTeyn
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: mysql2HikariCP
maximum-pool-size: 10
mysql3:
jdbc-url: jdbc:mysql://121.89.234.155:3306/pay_xxcg_com?serverTimezone=Asia/Shanghai
username: pay_xxcg_com
password: 4hHmzxZH4rF4c5xr
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: mysql2HikariCP
maximum-pool-size: 10
application:
name: demo
cache:
type: redis
redis:
time-to-live: 3600000
use-key-prefix: true
cache-null-values: true
servlet:
multipart:
enabled: true
max-file-size: 10MB
max-request-size: 10MB
data:
redis:
database: 0
host: 54.251.137.151
port: 10703
password: 8912h12jhhajsd
timeout: 1000
lettuce:
pool:
max-active: 20
max-wait: -1
max-idle: 5
mybatis:
configuration:
mysql1:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mysql2:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mysql3:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
upload:
path: D:\upload
server:
port: 8080
logging:
level:
org.springframework.jdbc.core.JdbcTemplate: DEBUG
org.springframework.orm.jpa: DEBUG

13
src/test/java/com/example/demo/DemoApplicationTests.java

@ -0,0 +1,13 @@
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}
Loading…
Cancel
Save