Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
yangxiujun
/
paidan_demo
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit cf781249
authored
Jul 13, 2023
by
chamberone
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
fix: 替换序列化工具
1 parent
2fae346c
Hide whitespace changes
Inline
Side-by-side
Showing
9 changed files
with
36 additions
and
742 deletions
project-gateway/pom.xml
project-gateway/src/main/java/com/dituhui/pea/gateway/auth/UserAuthService.java
project-gateway/src/main/java/com/dituhui/pea/gateway/commom/RedisConfig.java
project-gateway/src/main/java/com/dituhui/pea/gateway/commom/RedisService.java
project-gateway/src/main/java/com/dituhui/pea/gateway/config/AuthFilter.java
project-gateway/src/main/java/com/dituhui/pea/gateway/config/SleuthFilter.java
project-gateway/src/main/java/com/dituhui/pea/gateway/controller/TokenController.java
project-interface/src/main/java/com/dituhui/pea/pojo/UserLoginDTO.java
project-user/src/main/java/com/dituhui/pea/user/service/UserService.java
project-gateway/pom.xml
View file @
cf78124
...
...
@@ -50,6 +50,11 @@
<artifactId>
project-interface
</artifactId>
<version>
${revision}
</version>
</dependency>
<dependency>
<groupId>
com.google.code.gson
</groupId>
<artifactId>
gson
</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
...
...
project-gateway/src/main/java/com/dituhui/pea/gateway/auth/UserAuthService.java
deleted
100644 → 0
View file @
2fae346
package
com
.
dituhui
.
pea
.
gateway
.
auth
;
import
cn.hutool.core.util.ObjectUtil
;
import
cn.hutool.crypto.SecureUtil
;
import
com.dituhui.pea.enums.RedisKeyGroup
;
import
com.dituhui.pea.enums.StatusCodeEnum
;
import
com.dituhui.pea.enums.ThirdPartyEnum
;
import
com.dituhui.pea.exception.BusinessException
;
import
com.dituhui.pea.gateway.commom.RedisService
;
import
com.dituhui.pea.pojo.*
;
import
com.dituhui.pea.user.IUser
;
import
lombok.extern.slf4j.Slf4j
;
import
org.apache.commons.codec.digest.DigestUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.security.core.GrantedAuthority
;
import
org.springframework.security.core.authority.SimpleGrantedAuthority
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.crypto.bcrypt.BCrypt
;
import
java.io.IOException
;
import
java.util.*
;
/**
* 用户登录鉴权认证
*
* @author dk
*/
//@Component
@Slf4j
public
class
UserAuthService
{
@Autowired
private
RedisService
redisService
;
@Autowired
private
IUser
iUser
;
/**
* 获取用户认证token信息, 为了提高效率应该使用缓存
*/
public
UserDetails
getUserFromToken
(
UserAuthInfo
user
)
{
UserDetails
ud
=
null
;
if
(
null
!=
user
)
{
ud
=
createUser
(
user
.
getUserName
(),
user
.
getPassword
(),
new
String
[]{
user
.
getRole
()});
}
return
ud
;
}
/**
* 对输入参数签名
*
* @param params 参数
* @param secret 密钥
* @return
* @throws IOException
*/
public
String
signRequest
(
Map
<
String
,
String
>
params
,
String
secret
)
{
try
{
// 第一步:参数排序
String
[]
keys
=
params
.
keySet
().
toArray
(
new
String
[
0
]);
Arrays
.
sort
(
keys
);
// 第二步:把所有参数名和参数值串在一起
StringBuilder
query
=
new
StringBuilder
();
for
(
String
key
:
keys
)
{
String
value
=
params
.
get
(
key
);
if
(
StringUtils
.
isNotEmpty
(
key
)
&&
!
StringUtils
.
equalsIgnoreCase
(
key
,
"sign"
)
&&
StringUtils
.
isNotEmpty
(
value
))
{
query
.
append
(
key
).
append
(
value
);
}
}
// 第三步:使用MD5/HMAC加密
String
sign
=
DigestUtils
.
md5Hex
(
query
.
toString
()
+
secret
);
return
sign
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 根据手机号登录
* @param phone 手机号
* @return token
*/
public
String
loginByPhone
(
String
phone
)
{
WebResult
<
UserInfo
>
result
=
iUser
.
queryUserByPhone
(
phone
);
if
(!
result
.
getSuccess
()
&&
result
.
getCode
().
equals
(
StatusCodeEnum
.
USER_DOES_NOT_EXIST
.
getCode
()))
{
throw
new
BusinessException
(
StatusCodeEnum
.
USER_DOES_NOT_EXIST
);
}
UserInfo
userInfo
=
result
.
getResult
();
UserDetails
ud
=
createUser
(
userInfo
.
getAccount
(),
null
,
new
String
[]{
"user"
});
String
token
=
UUID
.
randomUUID
().
toString
().
replace
(
"-"
,
""
);
UserAuthInfo
userAuthInfo
=
new
UserAuthInfo
(
userInfo
.
getId
(),
ud
.
getUsername
(),
ud
.
getPassword
(),
"user"
);
// 设置一天后过期
redisService
.
set
(
RedisKeyGroup
.
authToken
+
":"
+
token
,
userAuthInfo
,
24
*
3600L
);
return
token
;
}
public
String
thirdLogin
(
ThirdUserInfo
thirdUserInfo
)
{
WebResult
<
UserInfo
>
result
=
iUser
.
queryUserByThirdParty
(
thirdUserInfo
.
getThirdId
(),
ThirdPartyEnum
.
valueOf
(
thirdUserInfo
.
getThirdType
()));
if
(!
result
.
getSuccess
()
&&
!
result
.
getCode
().
equals
(
StatusCodeEnum
.
USER_DOES_NOT_EXIST
.
getCode
()))
{
return
null
;
}
UserInfo
userInfo
=
result
.
getResult
();
// 用户不存在就初始化第三方信息
if
(
ObjectUtil
.
isEmpty
(
userInfo
))
{
// 微信小程序用户注册,必须手机号不为空才能注册
if
(
thirdUserInfo
.
getThirdType
().
equals
(
ThirdPartyEnum
.
WECHAT_MINI_PROGRAM
.
name
())
&&
StringUtils
.
isBlank
(
thirdUserInfo
.
getPhone
()))
{
throw
new
BusinessException
(
StatusCodeEnum
.
USER_DOES_NOT_EXIST
);
}
WebResult
<
UserInfo
>
trResult
=
iUser
.
thirdRegister
(
thirdUserInfo
);
if
(!
trResult
.
getSuccess
())
{
return
null
;
}
userInfo
=
trResult
.
getResult
();
}
UserDetails
ud
=
createUser
(
userInfo
.
getAccount
(),
userInfo
.
getPassword
(),
new
String
[]{
"user"
});
String
token
=
UUID
.
randomUUID
().
toString
().
replace
(
"-"
,
""
);
UserAuthInfo
userAuthInfo
=
new
UserAuthInfo
(
userInfo
.
getId
(),
ud
.
getUsername
(),
ud
.
getPassword
(),
"user"
);
// 设置一天后过期
redisService
.
set
(
RedisKeyGroup
.
authToken
+
":"
+
token
,
userAuthInfo
,
24
*
3600L
);
return
token
;
}
/**
* 登录,成功返回token
*
* @param userName
* @param password
* @return
*/
public
String
login
(
String
userName
,
String
password
)
{
UserDetails
ud
=
null
;
WebResult
<
UserInfo
>
userResult
=
null
;
System
.
out
.
println
(
"login ["
+
userName
+
"]["
+
password
+
"]"
);
try
{
userResult
=
iUser
.
queryUserByPhone
(
userName
);
}
catch
(
Throwable
e
)
{
// FIXME 代码调整
e
.
printStackTrace
();
}
UserInfo
userInfo
=
userResult
.
getResult
();
log
.
info
(
"login userInfo queryUserByPhone ["
+
userInfo
+
"]"
);
if
(
null
==
userInfo
)
{
try
{
userInfo
=
iUser
.
queryUserByAccount
(
userName
).
getResult
();
}
catch
(
Throwable
e
)
{
e
.
printStackTrace
();
}
}
log
.
info
(
"login userInfo queryUserByAccount ["
+
userInfo
+
"]"
);
if
(
null
!=
userInfo
)
{
try
{
if
(
StringUtils
.
equalsIgnoreCase
(
SecureUtil
.
md5
(
password
),
userInfo
.
getPassword
()))
{
ud
=
createUser
(
userName
,
password
,
new
String
[]{
"user"
});
}
else
if
(
BCrypt
.
checkpw
(
password
,
userInfo
.
getPassword
()))
{
ud
=
createUser
(
userName
,
password
,
new
String
[]{
"user"
});
}
}
catch
(
IllegalArgumentException
e
)
{
// 忽略参数版本错误
}
}
if
(
ud
!=
null
)
{
String
token
=
UUID
.
randomUUID
().
toString
().
replace
(
"-"
,
""
);
UserAuthInfo
userAuthInfo
=
new
UserAuthInfo
(
userInfo
.
getId
(),
ud
.
getUsername
(),
ud
.
getPassword
(),
"user"
);
// 设置一天后过期
redisService
.
set
(
RedisKeyGroup
.
authToken
.
toString
()
+
":"
+
token
,
userAuthInfo
,
24
*
3600L
);
return
token
;
}
else
{
return
null
;
}
}
/**
* 退出,移除token
*
* @param token token值
*/
public
void
logout
(
String
token
)
{
redisService
.
remove
(
RedisKeyGroup
.
authToken
.
toString
()
+
":"
+
token
);
}
private
UserDetails
createUser
(
String
userName
,
String
password
,
String
[]
roles
)
{
return
new
UserDetails
()
{
private
static
final
long
serialVersionUID
=
6905138725952656074L
;
@Override
public
Collection
<?
extends
GrantedAuthority
>
getAuthorities
()
{
Collection
<
GrantedAuthority
>
authorities
=
new
ArrayList
<
GrantedAuthority
>();
//这是增加了一种名为query的权限,可以使用 @hasAuthority("query") 来判断
SimpleGrantedAuthority
authority
=
new
SimpleGrantedAuthority
(
"query"
);
authorities
.
add
(
authority
);
//这是增加到xxx角色,可以用hasRole("xxx")来判断;需要注意所有的角色在这里增加时必须以ROLE_前缀,使用时则没有ROLES_前缀
for
(
String
role
:
roles
)
{
SimpleGrantedAuthority
sga
=
new
SimpleGrantedAuthority
(
"ROLE_"
+
role
);
authorities
.
add
(
sga
);
}
return
authorities
;
}
@Override
public
String
getPassword
()
{
return
password
;
}
@Override
public
String
getUsername
()
{
return
userName
;
}
@Override
public
boolean
isAccountNonExpired
()
{
return
true
;
}
@Override
public
boolean
isAccountNonLocked
()
{
return
true
;
}
@Override
public
boolean
isCredentialsNonExpired
()
{
return
true
;
}
@Override
public
boolean
isEnabled
()
{
return
true
;
}
};
}
}
project-gateway/src/main/java/com/dituhui/pea/gateway/commom/RedisConfig.java
View file @
cf78124
...
...
@@ -7,15 +7,24 @@ import org.springframework.data.redis.core.RedisTemplate;
import
org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
;
import
org.springframework.data.redis.serializer.StringRedisSerializer
;
import
com.fasterxml.jackson.annotation.JsonInclude
;
import
com.fasterxml.jackson.annotation.JsonTypeInfo
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
@Configuration
public
class
RedisConfig
{
@Bean
public
RedisTemplate
<
String
,
Object
>
redisTemplate
(
RedisConnectionFactory
connectionFactory
)
{
RedisTemplate
<
String
,
Object
>
redisTemplate
=
new
RedisTemplate
<>();
public
RedisTemplate
<
String
,
String
>
redisTemplate
(
RedisConnectionFactory
connectionFactory
)
{
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),
// ObjectMapper.DefaultTyping.EVERYTHING, JsonTypeInfo.As.PROPERTY);
RedisTemplate
<
String
,
String
>
redisTemplate
=
new
RedisTemplate
<>();
redisTemplate
.
setConnectionFactory
(
connectionFactory
);
redisTemplate
.
setKeySerializer
(
new
StringRedisSerializer
());
redisTemplate
.
setValueSerializer
(
new
GenericJackson2Json
RedisSerializer
());
redisTemplate
.
setValueSerializer
(
new
String
RedisSerializer
());
return
redisTemplate
;
}
...
...
project-gateway/src/main/java/com/dituhui/pea/gateway/commom/RedisService.java
View file @
cf78124
...
...
@@ -5,19 +5,20 @@ import org.springframework.data.redis.core.*;
import
org.springframework.stereotype.Component
;
import
java.io.Serializable
;
import
java.util.*
;
import
java.util.Date
;
import
java.util.List
;
import
java.util.Set
;
import
java.util.concurrent.TimeUnit
;
/**
* redis服务
*
* @author dk
*/
@Component
public
class
RedisService
{
@Autowired
private
RedisTemplate
redisTemplate
;
private
RedisTemplate
<
String
,
String
>
redisTemplate
;
/**
* 写入缓存
...
...
@@ -26,10 +27,10 @@ public class RedisService {
* @param value
* @return
*/
public
boolean
set
(
final
String
key
,
Object
value
)
{
public
boolean
set
(
final
String
key
,
String
value
)
{
boolean
result
=
false
;
try
{
ValueOperations
<
S
erializable
,
Object
>
operations
=
redisTemplate
.
opsForValue
();
ValueOperations
<
S
tring
,
String
>
operations
=
redisTemplate
.
opsForValue
();
operations
.
set
(
key
,
value
);
result
=
true
;
}
catch
(
Exception
e
)
{
...
...
@@ -45,10 +46,10 @@ public class RedisService {
* @param value
* @return
*/
public
boolean
set
(
final
String
key
,
Object
value
,
Long
expireTime
)
{
public
boolean
set
(
final
String
key
,
String
value
,
Long
expireTime
)
{
boolean
result
=
false
;
try
{
ValueOperations
<
S
erializable
,
Object
>
operations
=
redisTemplate
.
opsForValue
();
ValueOperations
<
S
tring
,
String
>
operations
=
redisTemplate
.
opsForValue
();
operations
.
set
(
key
,
value
);
redisTemplate
.
expire
(
key
,
expireTime
,
TimeUnit
.
SECONDS
);
result
=
true
;
...
...
@@ -59,166 +60,16 @@ public class RedisService {
}
/**
* 设置过期时间<br>
* 原始key
*
* @param key
* @param expriedDate
*/
public
boolean
setExpriedDate
(
String
key
,
Date
expriedDate
)
{
return
redisTemplate
.
expireAt
(
key
,
expriedDate
);
}
/**
* 批量删除对应的value
*
* @param keys
*/
public
void
remove
(
final
String
...
keys
)
{
for
(
String
key
:
keys
)
{
remove
(
key
);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public
void
removePattern
(
final
String
pattern
)
{
Set
<
Serializable
>
keys
=
redisTemplate
.
keys
(
pattern
);
if
(
keys
.
size
()
>
0
)
{
redisTemplate
.
delete
(
keys
);
}
}
/**
* 删除对应的value
*
* @param key
*/
public
void
remove
(
final
String
key
)
{
if
(
exists
(
key
))
{
redisTemplate
.
delete
(
key
);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public
boolean
exists
(
final
String
key
)
{
return
redisTemplate
.
hasKey
(
key
);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public
Object
get
(
final
String
key
)
{
Object
result
=
null
;
ValueOperations
<
S
erializable
,
Object
>
operations
=
redisTemplate
.
opsForValue
();
public
String
get
(
final
String
key
)
{
String
result
=
null
;
ValueOperations
<
S
tring
,
String
>
operations
=
redisTemplate
.
opsForValue
();
result
=
operations
.
get
(
key
);
return
result
;
}
/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/
public
void
hmSet
(
String
key
,
Object
hashKey
,
Object
value
)
{
HashOperations
<
String
,
Object
,
Object
>
hash
=
redisTemplate
.
opsForHash
();
hash
.
put
(
key
,
hashKey
,
value
);
}
/**
* 哈希获取数据
*
* @param key
* @param hashKey
* @return
*/
public
Object
hmGet
(
String
key
,
Object
hashKey
)
{
HashOperations
<
String
,
Object
,
Object
>
hash
=
redisTemplate
.
opsForHash
();
return
hash
.
get
(
key
,
hashKey
);
}
/**
* 列表添加
*
* @param k
* @param v
*/
public
void
lPush
(
String
k
,
Object
v
)
{
ListOperations
<
String
,
Object
>
list
=
redisTemplate
.
opsForList
();
list
.
rightPush
(
k
,
v
);
}
/**
* 列表获取
*
* @param k
* @param l
* @param l1
* @return
*/
public
List
<
Object
>
lRange
(
String
k
,
long
l
,
long
l1
)
{
ListOperations
<
String
,
Object
>
list
=
redisTemplate
.
opsForList
();
return
list
.
range
(
k
,
l
,
l1
);
}
/**
* 集合添加
*
* @param key
* @param value
*/
public
void
add
(
String
key
,
Object
value
)
{
SetOperations
<
String
,
Object
>
set
=
redisTemplate
.
opsForSet
();
set
.
add
(
key
,
value
);
}
/**
* 集合获取
*
* @param key
* @return
*/
public
Set
<
Object
>
setMembers
(
String
key
)
{
SetOperations
<
String
,
Object
>
set
=
redisTemplate
.
opsForSet
();
return
set
.
members
(
key
);
}
/**
* 有序集合添加
*
* @param key
* @param value
* @param scoure
*/
public
void
zAdd
(
String
key
,
Object
value
,
double
scoure
)
{
ZSetOperations
<
String
,
Object
>
zset
=
redisTemplate
.
opsForZSet
();
zset
.
add
(
key
,
value
,
scoure
);
}
/**
* 有序集合获取
*
* @param key
* @param scoure
* @param scoure1
* @return
*/
public
Set
<
Object
>
rangeByScore
(
String
key
,
double
scoure
,
double
scoure1
)
{
ZSetOperations
<
String
,
Object
>
zset
=
redisTemplate
.
opsForZSet
();
return
zset
.
rangeByScore
(
key
,
scoure
,
scoure1
);
}
}
project-gateway/src/main/java/com/dituhui/pea/gateway/config/AuthFilter.java
View file @
cf78124
...
...
@@ -15,13 +15,11 @@ import org.springframework.security.core.context.SecurityContextHolder;
import
org.springframework.stereotype.Component
;
import
org.springframework.web.server.ServerWebExchange
;
import
com.dituhui.pea.common.Result
;
import
com.dituhui.pea.common.ResultEnum
;
import
com.dituhui.pea.enums.RedisKeyGroup
;
import
com.dituhui.pea.gateway.commom.RedisService
;
import
com.dituhui.pea.pojo.UserLoginDTO
;
import
com.dituhui.pea.user.IUser
;
import
com.google.common.collect.Sets
;
import
com.google.gson.Gson
;
import
lombok.extern.slf4j.Slf4j
;
import
reactor.core.publisher.Mono
;
...
...
@@ -34,6 +32,7 @@ public class AuthFilter implements GlobalFilter, Ordered {
* 白名单
*/
private
static
final
Set
<
String
>
authWhiteList
=
Sets
.
newHashSet
(
"/pea-user/login"
,
"/pea-user/login/"
);
private
static
final
Gson
gson
=
new
Gson
();
@Autowired
RedisService
redisService
;
...
...
@@ -67,9 +66,9 @@ public class AuthFilter implements GlobalFilter, Ordered {
UserLoginDTO
userDTO
=
null
;
if
(
StringUtils
.
isNotEmpty
(
authToken
))
{
// 查询token对应的用户
Object
obj
=
redisService
.
get
(
RedisKeyGroup
.
authToken
+
":"
+
authToken
);
if
(
null
!=
obj
)
{
userDTO
=
(
UserLoginDTO
)
obj
;
String
value
=
redisService
.
get
(
RedisKeyGroup
.
authToken
+
":"
+
authToken
);
if
(
null
!=
value
)
{
userDTO
=
gson
.
fromJson
(
value
,
UserLoginDTO
.
class
)
;
}
}
if
(
userDTO
==
null
)
{
...
...
project-gateway/src/main/java/com/dituhui/pea/gateway/config/SleuthFilter.java
deleted
100644 → 0
View file @
2fae346
package
com
.
dituhui
.
pea
.
gateway
.
config
;
import
brave.Tags
;
import
brave.Tracer
;
import
brave.Tracing
;
import
brave.baggage.BaggageField
;
import
brave.baggage.BaggagePropagation
;
import
brave.baggage.BaggagePropagationConfig.SingleBaggageField
;
import
brave.propagation.B3Propagation
;
import
com.alibaba.fastjson.JSON
;
import
com.dituhui.pea.enums.RedisKeyGroup
;
import
com.dituhui.pea.enums.StatusCodeEnum
;
import
com.dituhui.pea.exception.BusinessException
;
import
com.dituhui.pea.gateway.auth.UserAuthService
;
import
com.dituhui.pea.gateway.commom.RedisService
;
import
com.dituhui.pea.pojo.UserAuthInfo
;
import
com.google.common.collect.Lists
;
import
lombok.extern.slf4j.Slf4j
;
import
org.apache.commons.collections.CollectionUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
org.apache.commons.lang3.time.DateUtils
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.cloud.gateway.filter.GatewayFilterChain
;
import
org.springframework.cloud.gateway.filter.GlobalFilter
;
import
org.springframework.core.Ordered
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.web.server.ServerWebExchange
;
import
reactor.core.publisher.Mono
;
import
java.util.*
;
//@Component
@Slf4j
public
class
SleuthFilter
implements
GlobalFilter
,
Ordered
{
@Value
(
"${auth.path:/test/**}"
)
private
String
authPath
;
/**
* 白名单
*/
private
static
final
String
[]
AUTH_WHITELIST
=
new
String
[]{
"/v1/user/getByAccount"
,
"/v1/user/getByPhone"
,
"/v1/user/getByThirdParty"
,
"/v1/user/register"
};
@Autowired
Tracer
tracer
;
@Autowired
UserAuthService
userAuthService
;
@Autowired
private
RedisService
redisService
;
@Override
public
Mono
<
Void
>
filter
(
ServerWebExchange
exchange
,
GatewayFilterChain
chain
)
{
String
authToken
=
null
;
String
url
=
exchange
.
getRequest
().
getPath
().
toString
();
// 下面的代码从Http Header的Authorization中获取token,也可以从其他header,cookie等中获取,看客户端怎么传递token
HttpHeaders
headers
=
exchange
.
getRequest
().
getHeaders
();
String
requestHeader
=
headers
.
getFirst
(
"Authorization"
);
if
(
requestHeader
!=
null
&&
requestHeader
.
startsWith
(
"Bearer "
))
{
authToken
=
requestHeader
.
substring
(
7
);
}
// String ak = exchange.getRequest().getQueryParams().getFirst("ak");
// String requestSign = exchange.getRequest().getQueryParams().getFirst("sign");
if
(
log
.
isTraceEnabled
())
{
log
.
trace
(
"token is "
+
authToken
);
}
UserAuthInfo
user
=
null
;
if
(
authToken
!=
null
)
{
//查询token对应的用户
user
=
getUserAuthInfoFromToken
(
authToken
);
if
(
null
!=
user
)
{
// 写入用户token
doTags
(
"token"
,
authToken
);
}
}
if
(
null
==
user
)
{
// 找不到用户登录信息,且在鉴权范围内的请求路径则被拦截
ArrayList
<
String
>
authPathList
=
Lists
.
newArrayList
(
authPath
.
split
(
","
));
authPathList
.
forEach
(
path
->
{
if
(
StringUtils
.
endsWith
(
path
,
"**"
))
{
path
=
StringUtils
.
substring
(
path
,
0
,
path
.
length
()
-
2
);
}
if
(
StringUtils
.
startsWith
(
url
,
path
))
{
// 白名单过滤
ArrayList
<
String
>
authWhiteList
=
Lists
.
newArrayList
(
AUTH_WHITELIST
);
if
(
CollectionUtils
.
isNotEmpty
(
authWhiteList
))
{
String
authWhite
=
authWhiteList
.
stream
().
filter
(
authWhitePath
->
StringUtils
.
startsWith
(
url
,
authWhitePath
))
.
findFirst
().
orElse
(
null
);
System
.
out
.
println
(
"authWhite: "
+
authWhite
);
if
(
null
==
authWhite
)
{
// 如果没有在白名单内,则抛出鉴权异常
throw
new
BusinessException
(
StatusCodeEnum
.
AUTH_FAILED
);
}
}
else
{
// 抛出鉴权异常
throw
new
BusinessException
(
StatusCodeEnum
.
AUTH_FAILED
);
}
}
});
}
else
{
// 授权和打标签用户信息
authentication
(
user
,
exchange
);
}
return
chain
.
filter
(
exchange
);
}
/**
* 授权和打标签用户信息
*
* @param user
*/
private
void
authentication
(
UserAuthInfo
user
,
ServerWebExchange
exchange
)
{
UserDetails
userDetails
=
this
.
userAuthService
.
getUserFromToken
(
user
);
// 把user设置到SecurityContextHolder内,以spring使用
UsernamePasswordAuthenticationToken
authentication
=
new
UsernamePasswordAuthenticationToken
(
userDetails
,
userDetails
.
getPassword
(),
userDetails
.
getAuthorities
());
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
if
(
StringUtils
.
isNotEmpty
(
user
.
getUserId
()))
{
// 写入用户id
doTags
(
"userId"
,
user
.
getUserId
());
}
// 客户端IP标签
doTags
(
"clientIp"
,
getRemoteIP
(
exchange
));
// 时间戳标签
String
t
=
exchange
.
getRequest
().
getQueryParams
().
getFirst
(
"t"
);
if
(
StringUtils
.
isEmpty
(
t
))
{
t
=
String
.
valueOf
(
System
.
currentTimeMillis
());
}
doTags
(
"t"
,
t
);
doTags
(
"isDebug"
,
exchange
.
getRequest
().
getQueryParams
().
getFirst
(
"isDebug"
));
}
/**
* 用户调用参数打标签
*
* @param name 参数名称
* @param value 参数值
*/
private
void
doTags
(
String
name
,
String
value
)
{
BaggageField
baggageField
=
BaggageField
.
create
(
name
);
baggageField
.
updateValue
(
value
);
Tracing
.
newBuilder
().
propagationFactory
(
BaggagePropagation
.
newFactoryBuilder
(
B3Propagation
.
FACTORY
)
.
add
(
SingleBaggageField
.
remote
(
baggageField
)).
build
());
Tags
.
BAGGAGE_FIELD
.
tag
(
baggageField
,
this
.
tracer
.
currentSpan
());
}
/**
* 客户端ip
*
* @param exchange
* @return
*/
private
String
getRemoteIP
(
ServerWebExchange
exchange
)
{
String
clientIp
=
""
;
if
(
StringUtils
.
isNotEmpty
(
exchange
.
getRequest
().
getHeaders
().
getFirst
(
"x-forwarded-for"
)))
{
clientIp
=
exchange
.
getRequest
().
getHeaders
().
getFirst
(
"x-forwarded-for"
);
}
else
if
(
StringUtils
.
isNotEmpty
(
exchange
.
getRequest
().
getHeaders
().
getFirst
(
"X-Forwarded-For"
)))
{
clientIp
=
exchange
.
getRequest
().
getHeaders
().
getFirst
(
"X-Forwarded-For"
);
}
else
if
(
StringUtils
.
isNotEmpty
(
exchange
.
getRequest
().
getRemoteAddress
().
getAddress
().
getHostAddress
()))
{
clientIp
=
exchange
.
getRequest
().
getRemoteAddress
().
getAddress
().
getHostAddress
();
}
if
(
"0:0:0:0:0:0:0:1"
.
equals
(
clientIp
))
{
clientIp
=
"127.0.0.1"
;
}
return
clientIp
;
}
/**
* 获取用户认证信息
*
* @param token
* @return
*/
private
UserAuthInfo
getUserAuthInfoFromToken
(
String
token
)
{
if
(
token
==
null
)
{
return
null
;
}
UserAuthInfo
userAuthInfo
=
(
UserAuthInfo
)
redisService
.
get
(
RedisKeyGroup
.
authToken
.
toString
()
+
":"
+
token
);
System
.
out
.
println
(
"token: "
+
token
);
System
.
out
.
println
(
"userAuthInfo: "
+
JSON
.
toJSONString
(
userAuthInfo
));
if
(
null
!=
userAuthInfo
)
{
// 设置一天后过期
Date
expiredDate
=
DateUtils
.
addMinutes
(
new
Date
(),
60
*
24
);
redisService
.
setExpriedDate
(
RedisKeyGroup
.
authToken
.
toString
()
+
":"
+
token
,
expiredDate
);
}
return
userAuthInfo
;
}
@Override
public
int
getOrder
()
{
return
-
1
;
}
}
project-gateway/src/main/java/com/dituhui/pea/gateway/controller/TokenController.java
deleted
100644 → 0
View file @
2fae346
package
com
.
dituhui
.
pea
.
gateway
.
controller
;
import
brave.Tracer
;
import
com.dituhui.pea.enums.StatusCodeEnum
;
import
com.dituhui.pea.gateway.auth.UserAuthService
;
import
com.dituhui.pea.pojo.ThirdUserInfo
;
import
com.dituhui.pea.pojo.UserInfo
;
import
com.dituhui.pea.pojo.WebResult
;
import
org.apache.commons.lang3.StringUtils
;
import
org.apache.commons.logging.Log
;
import
org.apache.commons.logging.LogFactory
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.web.bind.annotation.*
;
/**
* 用于管理登录和退出的controller
*
* @author dk
*/
//@RestController
//@RequestMapping("/token")
public
class
TokenController
{
private
final
static
Log
log
=
LogFactory
.
getLog
(
TokenController
.
class
);
@Autowired
UserAuthService
userAuthService
;
@Autowired
private
Tracer
tracer
;
/**
* 登录鉴权
*
* @param user 用户对象
* @return
*/
@PostMapping
(
value
=
"/login"
)
public
WebResult
login
(
@RequestBody
UserInfo
user
)
{
String
userName
=
user
.
getAccount
();
String
password
=
user
.
getPassword
();
String
token
=
userAuthService
.
login
(
userName
,
password
);
String
traceId
=
getTraceId
();
if
(
token
==
null
)
{
return
WebResult
.
failed
(
StatusCodeEnum
.
COMMON_ACCOUNT_ERROR
).
setTraceId
(
traceId
);
}
else
{
return
WebResult
.
ok
(
token
).
setTraceId
(
traceId
);
}
}
/**
* 根据手机号登录
* @param user 当前用户
* @return
*/
@PostMapping
(
value
=
"/loginByPhone"
)
public
WebResult
loginByPhone
(
@RequestBody
UserInfo
user
)
{
String
traceId
=
getTraceId
();
if
(
null
==
user
||
StringUtils
.
isBlank
(
user
.
getPhone
()))
{
return
WebResult
.
failed
(
StatusCodeEnum
.
COMMON_PARAM_EMPTY
).
setTraceId
(
traceId
);
}
String
token
=
userAuthService
.
loginByPhone
(
user
.
getPhone
());
return
WebResult
.
ok
(
token
).
setTraceId
(
traceId
);
}
/**
* 三方登录鉴权
*
* @param thirdUserInfo 第三方用户对象
* @return
*/
@PostMapping
(
value
=
"/thirdLogin"
)
public
WebResult
thirdLogin
(
@RequestBody
ThirdUserInfo
thirdUserInfo
)
{
String
token
=
userAuthService
.
thirdLogin
(
thirdUserInfo
);
String
traceId
=
getTraceId
();
if
(
token
==
null
)
{
return
WebResult
.
failed
(
StatusCodeEnum
.
COMMON_ACCOUNT_ERROR
).
setTraceId
(
traceId
);
}
else
{
return
WebResult
.
ok
(
token
).
setTraceId
(
traceId
);
}
}
/**
* 全局日志id
*
* @return
*/
private
String
getTraceId
()
{
String
traceId
=
null
;
if
(
null
!=
this
.
tracer
)
{
traceId
=
this
.
tracer
.
currentSpan
().
context
().
traceIdString
();
}
return
traceId
;
}
/**
* 退出登录
*
* @param authorization
* @return
*/
@RequestMapping
(
value
=
"/logout"
,
method
=
RequestMethod
.
GET
)
public
WebResult
logout
(
@RequestHeader
(
name
=
"Authorization"
)
String
authorization
)
{
if
(
authorization
!=
null
&&
authorization
.
startsWith
(
"Bearer "
))
{
String
token
=
authorization
.
substring
(
7
);
if
(
log
.
isTraceEnabled
())
{
log
.
trace
(
"will delete token : "
+
token
);
}
if
(
StringUtils
.
isNotEmpty
(
token
))
{
userAuthService
.
logout
(
token
);
}
}
return
WebResult
.
ok
(
true
).
setTraceId
(
getTraceId
());
}
}
project-interface/src/main/java/com/dituhui/pea/pojo/UserLoginDTO.java
View file @
cf78124
...
...
@@ -25,6 +25,6 @@ public class UserLoginDTO {
private
List
<
RoleInfo
>
roles
;
private
List
<
ResourceInfo
>
menus
;
//
private List<OrganizationDTO> auths;
private
List
<
OrganizationDTO
>
auths
;
}
project-user/src/main/java/com/dituhui/pea/user/service/UserService.java
View file @
cf78124
...
...
@@ -104,12 +104,6 @@ public class UserService {
userDTO
.
setToken
(
token
);
long
timestamp
=
System
.
currentTimeMillis
()
+
LIVE_TIME_MILLIS
;
redisService
.
set
(
RedisKeyGroup
.
authToken
+
":"
+
token
,
gson
.
toJson
(
userDTO
),
timestamp
/
1000
);
log
.
info
(
"test begin"
);
String
value
=
redisService
.
get
(
RedisKeyGroup
.
authToken
+
":"
+
token
);
UserLoginDTO
userDTO2
=
gson
.
fromJson
(
value
,
UserLoginDTO
.
class
);
log
.
info
(
"test {}"
,
userDTO2
);
return
Result
.
success
(
userDTO
);
}
else
{
return
Result
.
failed
(
"鉴权失败"
);
...
...
@@ -166,7 +160,7 @@ public class UserService {
}
return
orgs
;
}).
flatMap
(
a
->
a
.
stream
()).
collect
(
Collectors
.
toList
());
//
userDTO.setAuths(allOrgs);
userDTO
.
setAuths
(
allOrgs
);
}
}
}
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment