Compare commits
7
Commits
f1f401b37e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f3f2f987c | ||
|
|
d9f709de3d | ||
|
|
94d72c5f46 | ||
|
|
55143e9d8d | ||
|
|
49c4604f5e | ||
|
|
5d7be9d883 | ||
|
|
2f7b6fed35 |
+33
@@ -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
@@ -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
|
||||
#
|
||||
# https://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.7/apache-maven-3.9.7-bin.zip
|
||||
@@ -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
|
||||
#
|
||||
# https://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 "$@"
|
||||
@@ -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 https://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"
|
||||
@@ -0,0 +1,128 @@
|
||||
<?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.3</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.gw</groupId>
|
||||
<artifactId>test</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>test</name>
|
||||
<description>test</description>
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection/>
|
||||
<developerConnection/>
|
||||
<tag/>
|
||||
<url/>
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!--mysql 数据库驱动依赖-->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- mybatis plus 依赖-->
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>3.5.7</version>
|
||||
</dependency>
|
||||
|
||||
<!--hutool工具包-->
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
<version>5.8.11</version>
|
||||
</dependency>
|
||||
|
||||
<!-- spring security-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
<version>2.5.5</version>
|
||||
</dependency>
|
||||
<!-- jwt-->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<version>0.9.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.xiaoymin</groupId>
|
||||
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
|
||||
<version>4.5.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.swagger</groupId>-->
|
||||
<!-- <artifactId>swagger-annotations</artifactId>-->
|
||||
<!-- <version>1.6.6</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springframework.boot</groupId>-->
|
||||
<!-- <artifactId>spring-boot-starter-jdbc</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</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>jakarta.annotation</groupId>
|
||||
<artifactId>jakarta.annotation-api</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<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>
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.gw.test;
|
||||
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@MapperScan("com.gw.test.mapper")
|
||||
public class TestApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TestApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
// 设置允许跨域请求的域名
|
||||
.allowedOriginPatterns("*")
|
||||
// 是否允许cookie
|
||||
.allowCredentials(true)
|
||||
// 设置允许的请求方式
|
||||
.allowedMethods("GET", "POST", "DELETE", "PUT")
|
||||
// 设置允许的header属性
|
||||
.allowedHeaders("*")
|
||||
// 跨域允许时间
|
||||
.maxAge(3600);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* SpringSecurity白名单资源路径配置
|
||||
* Created by macro on 2018/11/5.
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "secure.ignored")
|
||||
public class IgnoreUrlsConfig {
|
||||
|
||||
private List<String> urls = new ArrayList<>();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
|
||||
@Configuration
|
||||
public class OpenApiConfig {
|
||||
@Bean
|
||||
public OpenAPI api() {
|
||||
return new OpenAPI().info(new Info().title("Test").version("v1.0.0").description( "接口测试"))
|
||||
.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
|
||||
.components(new Components().addSecuritySchemes(HttpHeaders.AUTHORIZATION,new SecurityScheme()
|
||||
.name(HttpHeaders.AUTHORIZATION).type(SecurityScheme.Type.HTTP).scheme("Bearer ")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import com.gw.test.filters.*;
|
||||
import com.gw.test.utils.JWTUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class SecurityBeanConfig {
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// public IgnoreUrlsConfig ignoreUrlsConfig() {
|
||||
// return new IgnoreUrlsConfig();
|
||||
// }
|
||||
|
||||
@Bean
|
||||
public JWTUtil jWTUtil() {
|
||||
return new JWTUtil();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
|
||||
return new RestfulAccessDeniedHandler();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
|
||||
return new RestAuthenticationEntryPoint();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(UserDetailsService userDetailsService, JWTUtil jwtTokenUtil){
|
||||
return new JwtAuthenticationTokenFilter(userDetailsService,jwtTokenUtil);
|
||||
}
|
||||
|
||||
// @ConditionalOnBean(name = "dynamicSecurityService")
|
||||
@Bean
|
||||
@Autowired
|
||||
public DynamicAccessDecisionManager dynamicAccessDecisionManager() {
|
||||
return new DynamicAccessDecisionManager();
|
||||
}
|
||||
|
||||
// @ConditionalOnBean(name = "dynamicSecurityService")
|
||||
@Bean
|
||||
// @Lazy
|
||||
public DynamicSecurityMetadataSource dynamicSecurityMetadataSource(DynamicSecurityService dynamicSecurityService) {
|
||||
// log.error("=============={}",dynamicSecurityService.loadDataSource());
|
||||
return new DynamicSecurityMetadataSource(dynamicSecurityService);
|
||||
}
|
||||
|
||||
// @ConditionalOnBean(name = "dynamicSecurityService")
|
||||
@Bean
|
||||
// @Lazy
|
||||
public DynamicSecurityFilter dynamicSecurityFilter(DynamicSecurityMetadataSource dynamicSecurityMetadataSource,IgnoreUrlsConfig ignoreUrlsConfig){
|
||||
// log.error("======动态权限注解支持启动========{}",dynamicSecurityMetadataSource);
|
||||
return new DynamicSecurityFilter(dynamicSecurityMetadataSource,ignoreUrlsConfig);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import com.gw.test.filters.*;
|
||||
import com.gw.test.utils.JWTUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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.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.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConfig {
|
||||
// private final JWTUtil jwtUtil;
|
||||
|
||||
private final IgnoreUrlsConfig ignoreUrlsConfig;
|
||||
|
||||
private final RestfulAccessDeniedHandler restfulAccessDeniedHandler;
|
||||
|
||||
private final RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
||||
|
||||
private final JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
|
||||
|
||||
@Autowired(required = false)
|
||||
private DynamicSecurityService dynamicSecurityService;
|
||||
|
||||
@Autowired(required = false)
|
||||
private DynamicSecurityFilter dynamicSecurityFilter;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
|
||||
|
||||
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.authorizeRequests();
|
||||
//不需要保护的资源路径允许访问
|
||||
for (String url : ignoreUrlsConfig.getUrls()) {
|
||||
log.error("[{}] [{}]", "白名单路径", url);
|
||||
registry.requestMatchers(url).permitAll();
|
||||
}
|
||||
//允许跨域请求的OPTIONS请求
|
||||
registry.requestMatchers(HttpMethod.OPTIONS)
|
||||
.permitAll();
|
||||
|
||||
// 任何请求需要身份认证
|
||||
registry.anyRequest()
|
||||
.authenticated()
|
||||
// 关闭跨站请求防护及不使用session
|
||||
.and()
|
||||
.exceptionHandling(exception -> exception
|
||||
.accessDeniedHandler(restfulAccessDeniedHandler)
|
||||
.authenticationEntryPoint(restAuthenticationEntryPoint))
|
||||
// 自定义JWT认证过滤器
|
||||
.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(dynamicSecurityFilter, FilterSecurityInterceptor.class);
|
||||
return httpSecurity.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import com.gw.test.filters.DynamicSecurityService;
|
||||
import com.gw.test.service.IGuoWeiService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.access.SecurityConfig;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 后台用户安全配置
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Configuration
|
||||
public class UserSecurityConfig {
|
||||
|
||||
private final IGuoWeiService service;
|
||||
|
||||
// private final IApiService apiService;
|
||||
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() {
|
||||
//获取登录用户信息
|
||||
return service::loadUserByUsername;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DynamicSecurityService dynamicSecurityService() {
|
||||
log.error("========动态权限配置加载========");
|
||||
return () -> {
|
||||
Map<String, ConfigAttribute> map = new ConcurrentHashMap<>();
|
||||
Map<String,String> apis = new HashMap<>();
|
||||
apis.put("/guowei/list","查询所有");
|
||||
apis.put("/guowei/update","修改");
|
||||
apis.put("/guowei/delete","删除");
|
||||
apis.put("/guowei/add","添加");
|
||||
for (String api : apis.keySet()) {
|
||||
// map.put(api,new SecurityConfig(apis.get(api)));
|
||||
map.put(api,new SecurityConfig(api));
|
||||
}
|
||||
return map;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
|
||||
//@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
@Autowired
|
||||
// LoginInterceptor loginInterceptor;
|
||||
/**
|
||||
* 跨域配置
|
||||
*/
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")//
|
||||
.allowedOriginPatterns("*")//
|
||||
.allowedMethods("POST", "GET", "OPTIONS")//
|
||||
.maxAge(3600)//
|
||||
.allowCredentials(true);//
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
|
||||
// 对所有访问路径,都通过MyInterceptor类型的拦截器进行拦截
|
||||
// registry.addInterceptor(loginInterceptor)//
|
||||
// .addPathPatterns("/**")//
|
||||
// // 放行登陆接口
|
||||
// .excludePathPatterns("/**/login/**")//
|
||||
// .excludePathPatterns("/**/ip/**")
|
||||
// // swagger需要放行的资源
|
||||
// .excludePathPatterns("/favicon.ico")//
|
||||
// .excludePathPatterns("/error")//
|
||||
// .excludePathPatterns("/doc.html")//
|
||||
// .excludePathPatterns("/webjars/**")//
|
||||
// .excludePathPatterns("/swagger/**")//
|
||||
// .excludePathPatterns("/v3/api-docs/**")//
|
||||
// .excludePathPatterns("/swagger-resources/**")//
|
||||
// .excludePathPatterns("/swagger-ui/**")
|
||||
// .excludePathPatterns("/IpCheck/**")//
|
||||
// ;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.gw.test.controller;
|
||||
|
||||
|
||||
import com.gw.test.domain.Result;
|
||||
import com.gw.test.domain.vo.LoginVo;
|
||||
import com.gw.test.entity.GuoWei;
|
||||
import com.gw.test.service.IGuoWeiService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 前端控制器
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/guowei")
|
||||
@Tag(name = "用户管理",description = "用户管理接口")
|
||||
public class GuoWeiController {
|
||||
|
||||
private final IGuoWeiService service;
|
||||
|
||||
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
|
||||
@Operation(summary = "用户列表",description = "用户列表接口",security = { @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) })
|
||||
@GetMapping("/list")
|
||||
public Result<List<GuoWei>> list(){
|
||||
return Result.ok(service.list());
|
||||
}
|
||||
|
||||
// @SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
|
||||
// @Operation(summary = "添加用户",description = "添加用户接口")
|
||||
// @PostMapping("/add")
|
||||
// public Result<Void> save(@RequestBody GuoWei guoWei) {
|
||||
// service.save(guoWei);
|
||||
// return Result.ok();
|
||||
// }
|
||||
|
||||
|
||||
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
|
||||
@Operation(summary = "删除用户",description = "删除用户接口")
|
||||
@DeleteMapping("/delete")
|
||||
public Result<Void> delete(@RequestParam("id") Integer id) {
|
||||
service.removeById(id);
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
|
||||
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
|
||||
@Operation(summary = "用户修改",description = "用户列修改口")
|
||||
@PostMapping("/update")
|
||||
public Result<Void> update(@RequestBody GuoWei guoWei) {
|
||||
service.updateById(guoWei);
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
@Operation(summary = "用户登录",description = "用户登录接口")
|
||||
@PostMapping("/login")
|
||||
public Result<LoginVo> login(String username, String password) {
|
||||
log.error("========>username:{},password:{}",username,password);
|
||||
LoginVo login = service.login(username, password);
|
||||
if (login != null) return Result.ok(login);
|
||||
return Result.error("用户名或密码错误");
|
||||
}
|
||||
|
||||
@Operation(summary = "用户注册",description = "用户注册接口")
|
||||
@PostMapping("/register")
|
||||
public Result<Void> register(GuoWei guoWei) {
|
||||
boolean re = service.register(guoWei);
|
||||
if (re)
|
||||
return Result.ok();
|
||||
else
|
||||
return Result.error("注册失败");
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.gw.test.domain;
|
||||
|
||||
import com.gw.test.enums.ResultCode;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 定义一个R类,用于封装响应数据
|
||||
* @since 2021-09-04
|
||||
*/
|
||||
@Data
|
||||
public class Result<T> {
|
||||
/**
|
||||
* 响应码
|
||||
*/
|
||||
private int code;
|
||||
/**
|
||||
* 响应消息
|
||||
*/
|
||||
private String msg;
|
||||
/**
|
||||
* 响应数据
|
||||
*/
|
||||
private T data;
|
||||
|
||||
/**
|
||||
* 返回一个成功的响应
|
||||
*/
|
||||
public static Result<Void> ok() {
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回一个成功的响应,带有消息和数据
|
||||
* @param msg 消息内容
|
||||
* @param data 数据
|
||||
* @return 成功响应
|
||||
*/
|
||||
public static <T> Result<T> ok(String msg,T data){
|
||||
return new Result<>(200, msg, data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> unauthorized(T data){
|
||||
return new Result<>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> forbidden(T data){
|
||||
return new Result<>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 返回一个成功的响应,仅带有数据
|
||||
* @param data 数据
|
||||
* @return 成功响应
|
||||
*/
|
||||
public static <T> Result<T> ok(T data) {
|
||||
return new Result<>(200, "OK", data);
|
||||
}
|
||||
|
||||
// public static <T> R<T> ok(T data,String msg) {
|
||||
// return new R<>(200, msg, data);
|
||||
// }
|
||||
|
||||
/**
|
||||
* 返回一个错误的响应
|
||||
* @param msg 消息内容
|
||||
* @return 错误响应
|
||||
*/
|
||||
public static <T> Result<T> error(String msg) {
|
||||
return new Result<>(500, msg, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回一个错误的响应,带有错误码和消息
|
||||
* @param code 错误码
|
||||
* @param msg 消息内容
|
||||
* @return 错误响应
|
||||
*/
|
||||
public static <T> Result<T> error(int code, String msg) {
|
||||
return new Result<>(code, msg, null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
*/
|
||||
public Result() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数,带有参数
|
||||
* @param code 响应码
|
||||
* @param msg 响应消息
|
||||
* @param data 响应数据
|
||||
*/
|
||||
public Result(int code, String msg, T data) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断响应是否成功
|
||||
* @return true-成功,false-失败
|
||||
*/
|
||||
public boolean success(){
|
||||
return code == 200;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.gw.test.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LoginVo {
|
||||
private int id;
|
||||
|
||||
private String username;
|
||||
|
||||
private String token;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.gw.test.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
*
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Accessors(chain = true)
|
||||
@TableName("guo_wei")
|
||||
@Schema($schema = "GuoWei对象",description = "")
|
||||
public class GuoWei implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema($schema = "主键")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema($schema = "用户名")
|
||||
private String username;
|
||||
|
||||
@Schema($schema = "密码")
|
||||
private String password;
|
||||
|
||||
@Schema($schema = "创建时间")
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private String createTime;
|
||||
|
||||
@Schema($schema = "手机号")
|
||||
private String phoneNumber;
|
||||
|
||||
@Schema($schema = "权限")
|
||||
private String permissions;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.gw.test.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class User implements UserDetails {
|
||||
private GuoWei entity;
|
||||
|
||||
private List<String> authorities;
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return this.authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return entity.getPassword();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return entity.getUsername();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.gw.test.enums;
|
||||
|
||||
/**
|
||||
* API返回码接口
|
||||
* Created by macro on 2019/4/19.
|
||||
*/
|
||||
public interface IErrorCode {
|
||||
/**
|
||||
* 返回码
|
||||
*/
|
||||
int getCode();
|
||||
|
||||
/**
|
||||
* 返回信息
|
||||
*/
|
||||
String getMessage();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.gw.test.enums;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* API返回码封装类
|
||||
* Created by macro on 2019/4/19.
|
||||
*/
|
||||
//@Data
|
||||
public enum ResultCode implements IErrorCode {
|
||||
SUCCESS(200, "操作成功"),
|
||||
FAILED(500, "操作失败"),
|
||||
VALIDATE_FAILED(404, "参数检验失败"),
|
||||
UNAUTHORIZED(401, "暂未登录或token已经过期"),
|
||||
FORBIDDEN(403, "没有相关权限");
|
||||
private final int code;
|
||||
private final String message;
|
||||
|
||||
private ResultCode(int code, String message) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.AccessDecisionManager;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.authentication.InsufficientAuthenticationException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* 判断用户是否有访问权限
|
||||
*/
|
||||
@Slf4j
|
||||
public class DynamicAccessDecisionManager implements AccessDecisionManager {
|
||||
|
||||
@Override
|
||||
public void decide(Authentication authentication, Object object,
|
||||
Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
|
||||
// 当接口未被配置资源时直接放行
|
||||
// if (CollUtil.isEmpty(configAttributes)) {
|
||||
// return;
|
||||
// }
|
||||
if (configAttributes== null || configAttributes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (ConfigAttribute configAttribute : configAttributes) {
|
||||
//将访问所需资源或用户拥有资源进行比对
|
||||
String needAuthority = configAttribute.getAttribute();
|
||||
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
|
||||
log.error("needAuthority:{},grantedAuthority:{}", needAuthority, grantedAuthority.getAuthority());
|
||||
if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AccessDeniedException("抱歉,您没有访问权限");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(ConfigAttribute configAttribute) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> aClass) {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import com.gw.test.config.IgnoreUrlsConfig;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.access.SecurityMetadataSource;
|
||||
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
|
||||
import org.springframework.security.access.intercept.InterceptorStatusToken;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.PathMatcher;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 权限过滤器,实现基于路径的动态权限过滤
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class DynamicSecurityFilter extends AbstractSecurityInterceptor implements Filter {
|
||||
|
||||
|
||||
private final DynamicSecurityMetadataSource dynamicSecurityMetadataSource;
|
||||
|
||||
|
||||
private final IgnoreUrlsConfig ignoreUrlsConfig;
|
||||
|
||||
@Autowired
|
||||
public void setMyAccessDecisionManager(DynamicAccessDecisionManager dynamicAccessDecisionManager) {
|
||||
super.setAccessDecisionManager(dynamicAccessDecisionManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
// log.error("进入动态权限过滤器");
|
||||
HttpServletRequest request = (HttpServletRequest) servletRequest;
|
||||
FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
|
||||
//OPTIONS请求直接放行
|
||||
if(request.getMethod().equals(HttpMethod.OPTIONS.toString())){
|
||||
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
|
||||
return;
|
||||
}
|
||||
//白名单请求直接放行
|
||||
PathMatcher pathMatcher = new AntPathMatcher();
|
||||
for (String path : ignoreUrlsConfig.getUrls()) {
|
||||
// log.error("=============>ignor:{},{}",path,request.getRequestURI());
|
||||
if(pathMatcher.match(path,request.getRequestURI())){
|
||||
log.error("=============>白名单请求直接放行{},{}",request.getRequestURI(),path);
|
||||
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
|
||||
return;
|
||||
}
|
||||
}
|
||||
//此处会调用AccessDecisionManager中的decide方法进行鉴权操作
|
||||
InterceptorStatusToken token = super.beforeInvocation(fi);
|
||||
try {
|
||||
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
|
||||
} finally {
|
||||
super.afterInvocation(token, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getSecureObjectClass() {
|
||||
return FilterInvocation.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SecurityMetadataSource obtainSecurityMetadataSource() {
|
||||
return dynamicSecurityMetadataSource;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import cn.hutool.core.util.URLUtil;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.PathMatcher;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 动态权限数据源,获取动态权限规则
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
|
||||
|
||||
private static Map<String, ConfigAttribute> configAttributeMap = null;
|
||||
// @Autowired
|
||||
private final DynamicSecurityService dynamicSecurityService;
|
||||
|
||||
@PostConstruct
|
||||
public void loadDataSource() {
|
||||
configAttributeMap = dynamicSecurityService.loadDataSource();
|
||||
}
|
||||
|
||||
public void clearDataSource() {
|
||||
configAttributeMap.clear();
|
||||
configAttributeMap = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
|
||||
if (configAttributeMap == null) this.loadDataSource();
|
||||
List<ConfigAttribute> configAttributes = new ArrayList<>();
|
||||
//获取当前访问的路径
|
||||
String url = ((FilterInvocation) o).getRequestUrl();
|
||||
String path = URLUtil.getPath(url);
|
||||
// log.error("------DynamicSecurityMetadataSource:请求url:{}",url);
|
||||
PathMatcher pathMatcher = new AntPathMatcher();
|
||||
//获取访问该路径所需资源
|
||||
for (String pattern : configAttributeMap.keySet()) {
|
||||
if (pathMatcher.match(pattern, path)) {
|
||||
log.error("------DynamicSecurityMetadataSource:匹配到url:{}:{}",pattern,configAttributeMap.get(pattern));
|
||||
configAttributes.add(configAttributeMap.get(pattern));
|
||||
}
|
||||
}
|
||||
// 未设置操作请求权限,返回空集合
|
||||
return configAttributes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ConfigAttribute> getAllConfigAttributes() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> aClass) {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 动态权限相关业务接口
|
||||
*/
|
||||
public interface DynamicSecurityService {
|
||||
/**
|
||||
* 加载资源ANT通配符和资源对应MAP
|
||||
*/
|
||||
Map<String, ConfigAttribute> loadDataSource();
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import com.gw.test.utils.JWTUtil;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* JWT登录授权过滤器
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
|
||||
// private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
|
||||
|
||||
private final UserDetailsService userDetailsService;
|
||||
|
||||
private final JWTUtil jwtTokenUtil;
|
||||
|
||||
@Value("${jwt.tokenHeader}")
|
||||
private String tokenHeader;
|
||||
|
||||
@Value("${jwt.tokenHead}")
|
||||
private String tokenHead;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
// log.error("================JWT过滤器执行=================");
|
||||
// log.error(request.getRequestURI());
|
||||
String authHeader = request.getHeader(this.tokenHeader);
|
||||
if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
|
||||
String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
|
||||
String username = jwtTokenUtil.getUserNameFromToken(authToken);
|
||||
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
|
||||
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.gw.test.domain.Result;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 未登录或者token失效时的返回结果
|
||||
*/
|
||||
@Slf4j
|
||||
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Cache-Control","no-cache");
|
||||
// response.setHeader("authorization", authException.getMessage());
|
||||
// log.error("code{},msg:{}", ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage());
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("application/json");
|
||||
response.getWriter().println(JSONUtil.parse(Result.unauthorized(authException.getMessage())));
|
||||
response.getWriter().flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.gw.test.domain.Result;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 自定义无权限访问的返回结果
|
||||
*/
|
||||
public class RestfulAccessDeniedHandler implements AccessDeniedHandler{
|
||||
@Override
|
||||
public void handle(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
AccessDeniedException e) throws IOException, ServletException {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Cache-Control","no-cache");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("application/json");
|
||||
response.getWriter().println(JSONUtil.parse(Result.forbidden(e.getMessage()+"没有权限访问该资源....")));
|
||||
response.getWriter().flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.gw.test.mapper;
|
||||
|
||||
import com.gw.test.entity.GuoWei;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Mapper 接口
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
//@Mapper
|
||||
public interface GuoWeiMapper extends BaseMapper<GuoWei> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.gw.test.service;
|
||||
|
||||
import com.gw.test.domain.vo.LoginVo;
|
||||
import com.gw.test.entity.GuoWei;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 服务类
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
public interface IGuoWeiService extends IService<GuoWei> {
|
||||
|
||||
UserDetails loadUserByUsername(String s);
|
||||
|
||||
LoginVo login(String username, String password);
|
||||
|
||||
boolean register(GuoWei guoWei);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.gw.test.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.gw.test.domain.vo.LoginVo;
|
||||
import com.gw.test.entity.GuoWei;
|
||||
import com.gw.test.entity.User;
|
||||
import com.gw.test.mapper.GuoWeiMapper;
|
||||
import com.gw.test.service.IGuoWeiService;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.gw.test.utils.JWTUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 服务实现类
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class GuoWeiServiceImpl extends ServiceImpl<GuoWeiMapper, GuoWei> implements IGuoWeiService {
|
||||
private final JWTUtil JWTUtil;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String s) {
|
||||
QueryWrapper<GuoWei> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq("username", s);
|
||||
List<GuoWei> list = list(wrapper);
|
||||
if (list.isEmpty()) return null;
|
||||
GuoWei guoWei = list.getFirst();
|
||||
return new User(guoWei, Arrays.stream(guoWei.getPermissions().split(",")).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginVo login(String username, String password) {
|
||||
User user = (User) loadUserByUsername(username);
|
||||
if (user == null) return null;
|
||||
|
||||
if (!passwordEncoder.matches(password, user.getPassword())) return null;
|
||||
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
LoginVo re = new LoginVo();
|
||||
|
||||
re.setId(user.getEntity().getId());
|
||||
re.setUsername(user.getUsername());
|
||||
re.setToken(JWTUtil.generateToken(user));
|
||||
|
||||
return re;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean register(GuoWei guoWei) {
|
||||
Long count = lambdaQuery()
|
||||
.eq(GuoWei::getUsername, guoWei.getUsername())
|
||||
.count();
|
||||
|
||||
if (count > 0) return false;
|
||||
|
||||
guoWei.setPassword(passwordEncoder.encode(guoWei.getPassword()));
|
||||
return save(guoWei);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.gw.test.utils;
|
||||
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
public class JWTUtil {
|
||||
// private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
|
||||
private static final String CLAIM_KEY_USERNAME = "sub";
|
||||
private static final String CLAIM_KEY_CREATED = "created";
|
||||
@Value("${jwt.secret}")
|
||||
private String secret;
|
||||
@Value("${jwt.expiration}")
|
||||
private Long expiration;
|
||||
@Value("${jwt.tokenHead}")
|
||||
private String tokenHead;
|
||||
|
||||
/**
|
||||
* 根据负责生成JWT的token
|
||||
*/
|
||||
private String generateToken(Map<String, Object> claims) {
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setExpiration(generateExpirationDate())
|
||||
.signWith(SignatureAlgorithm.HS512, secret)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从token中获取JWT中的负载
|
||||
*/
|
||||
private Claims getClaimsFromToken(String token) {
|
||||
Claims claims = null;
|
||||
try {
|
||||
claims = Jwts.parser()
|
||||
.setSigningKey(secret)
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
} catch (Exception e) {
|
||||
log.info("JWT格式验证失败:{}", token);
|
||||
}
|
||||
return claims;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token的过期时间
|
||||
*/
|
||||
private Date generateExpirationDate() {
|
||||
return new Date(System.currentTimeMillis() + expiration * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从token中获取登录用户名
|
||||
*/
|
||||
public String getUserNameFromToken(String token) {
|
||||
String username;
|
||||
try {
|
||||
Claims claims = getClaimsFromToken(token);
|
||||
username = claims.getSubject();
|
||||
} catch (Exception e) {
|
||||
username = null;
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证token是否还有效
|
||||
*
|
||||
* @param token 客户端传入的token
|
||||
* @param userDetails 从数据库中查询出来的用户信息
|
||||
*/
|
||||
public boolean validateToken(String token, UserDetails userDetails) {
|
||||
if (userDetails == null || token == null)
|
||||
return false;
|
||||
String username = getUserNameFromToken(token);
|
||||
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断token是否已经失效
|
||||
*/
|
||||
private boolean isTokenExpired(String token) {
|
||||
Date expiredDate = getExpiredDateFromToken(token);
|
||||
return expiredDate.before(new Date());
|
||||
}
|
||||
|
||||
/**
|
||||
* 从token中获取过期时间
|
||||
*/
|
||||
private Date getExpiredDateFromToken(String token) {
|
||||
Claims claims = getClaimsFromToken(token);
|
||||
return claims.getExpiration();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据用户信息生成token
|
||||
*/
|
||||
public String generateToken(UserDetails userDetails) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
|
||||
claims.put(CLAIM_KEY_CREATED, new Date());
|
||||
return generateToken(claims);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当原来的token没过期时是可以刷新的
|
||||
*
|
||||
* @param oldToken 带tokenHead的token
|
||||
*/
|
||||
public String refreshHeadToken(String oldToken) {
|
||||
// if(StrUtil.isEmpty(oldToken)){
|
||||
// return null;
|
||||
// }
|
||||
if(oldToken == null || oldToken.isEmpty()) return null;
|
||||
String token = oldToken.substring(tokenHead.length());
|
||||
// if(StrUtil.isEmpty(token)){
|
||||
// return null;
|
||||
// }
|
||||
if(token.isEmpty()) return null;
|
||||
//token校验不通过
|
||||
Claims claims = getClaimsFromToken(token);
|
||||
if(claims==null){
|
||||
return null;
|
||||
}
|
||||
//如果token已经过期,不支持刷新
|
||||
if(isTokenExpired(token)){
|
||||
return null;
|
||||
}
|
||||
//如果token在30分钟之内刚刷新过,返回原token
|
||||
if(tokenRefreshJustBefore(token,30*60)){
|
||||
return token;
|
||||
}else{
|
||||
claims.put(CLAIM_KEY_CREATED, new Date());
|
||||
return generateToken(claims);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断token在指定时间内是否刚刚刷新过
|
||||
* @param token 原token
|
||||
* @param time 指定时间(秒)
|
||||
*/
|
||||
private boolean tokenRefreshJustBefore(String token, int time) {
|
||||
Claims claims = getClaimsFromToken(token);
|
||||
Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
|
||||
Date refreshDate = new Date();
|
||||
//刷新时间在创建时间的指定时间内
|
||||
return refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
spring:
|
||||
application:
|
||||
name: test
|
||||
|
||||
datasource:
|
||||
url: jdbc:mysql://222.186.15.41:3306/testapi
|
||||
username: testapi
|
||||
password: BYGAxwj4PZi4GZsA
|
||||
|
||||
server:
|
||||
port: 8080
|
||||
|
||||
|
||||
mybatis-plus:
|
||||
global-config:
|
||||
db-config:
|
||||
column-format: "`%s`"
|
||||
configuration:
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
map-underscore-to-camel-case: true
|
||||
|
||||
knife4j:
|
||||
enable: true #开启增强模式
|
||||
setting:
|
||||
language: zh_cn
|
||||
|
||||
springdoc:
|
||||
group-configs:
|
||||
- group: 'test'
|
||||
packages-to-scan: com.gw.test.controller
|
||||
# 配置Swagger UI的访问路径和排序方式
|
||||
swagger-ui:
|
||||
path: /doc.html # Swagger UI的访问路径
|
||||
# tags-sorter: alpha # 按字母顺序排序标签
|
||||
# operations-sorter: alpha # 按字母顺序排序操作
|
||||
# 配置API文档的访问路径
|
||||
api-docs:
|
||||
path: /docs # API文档的访问路径
|
||||
|
||||
jwt:
|
||||
tokenHeader: Authorization #JWT存储的请求头
|
||||
secret: guowei #JWT加解密使用的密钥
|
||||
expiration: 604800 #JWT的超期限时间(60*60*24*7)
|
||||
tokenHead: 'Bearer ' #JWT负载中拿到开头
|
||||
|
||||
secure:
|
||||
ignored:
|
||||
urls:
|
||||
- /webjars/**
|
||||
- /favicon.ico
|
||||
- /swagger/**
|
||||
- /swagger-resources/**
|
||||
- /docs/**
|
||||
- /error
|
||||
- /v3/api-docs/**
|
||||
- /swagger-ui/**
|
||||
- /swagger-ui.html
|
||||
- /doc.html
|
||||
- /guowei/login
|
||||
- /guowei/register
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.gw.test.mapper.GuoWeiMapper">
|
||||
|
||||
<!-- 通用查询映射结果 -->
|
||||
<resultMap id="BaseResultMap" type="com.gw.test.entity.GuoWei">
|
||||
<id column="id" property="id" />
|
||||
<result column="username" property="username" />
|
||||
<result column="password" property="password" />
|
||||
<result column="create_time" property="createTime" />
|
||||
<result column="phone_number" property="phoneNumber" />
|
||||
<result column="permissions" property="permissions" />
|
||||
</resultMap>
|
||||
|
||||
</mapper>
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.gw.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class TestApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user