Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
T
traffic-signal-platform
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
signal
traffic-signal-platform
Commits
c580c2ef
Commit
c580c2ef
authored
May 22, 2025
by
zhouleilei
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
添加权限系统
parent
13b3d9ee
Changes
9
Hide whitespace changes
Inline
Side-by-side
Showing
9 changed files
with
704 additions
and
8 deletions
+704
-8
ResourceServerConfig.java
.../main/java/net/wanji/web/config/ResourceServerConfig.java
+1
-1
CrossConfigServiceImpl.java
...wanji/web/service/scheme/impl/CrossConfigServiceImpl.java
+2
-1
application-docker.properties
...-service/src/main/resources/application-docker.properties
+6
-6
pom.xml
signal-utc-service/pom.xml
+82
-0
IdentityResourceServerConfig.java
...nji/utc/config/security/IdentityResourceServerConfig.java
+91
-0
IdentitySwaggerConfig.java
.../net/wanji/utc/config/security/IdentitySwaggerConfig.java
+130
-0
IdentityTokenHelper.java
...va/net/wanji/utc/config/security/IdentityTokenHelper.java
+89
-0
OAuth2AccessTokenRestTemplate.java
...ji/utc/config/security/OAuth2AccessTokenRestTemplate.java
+161
-0
ResourceServerConfig.java
...a/net/wanji/utc/config/security/ResourceServerConfig.java
+142
-0
No files found.
signal-control-service/src/main/java/net/wanji/web/config/ResourceServerConfig.java
View file @
c580c2ef
...
...
@@ -109,6 +109,6 @@ public class ResourceServerConfig extends IdentityResourceServerConfig {
add
(
"/**/*.json"
);
add
(
"/**/*.js"
);
add
(
"/**/*.txt"
);
add
(
"/**"
);
//
add("/**");
}};
}
signal-control-service/src/main/java/net/wanji/web/service/scheme/impl/CrossConfigServiceImpl.java
View file @
c580c2ef
...
...
@@ -377,7 +377,8 @@ public class CrossConfigServiceImpl implements CrossConfigService {
QueryWrapper
<
BaseRidInfo
>
queryWrapper
=
new
QueryWrapper
<>();
queryWrapper
.
eq
(
"end_cross_id"
,
crossId
);
List
<
BaseRidInfo
>
ridList
=
baseRidInfoMapper
.
selectList
(
queryWrapper
);
Map
<
Integer
,
String
>
roadNameMap
=
ridList
.
stream
().
collect
(
Collectors
.
toMap
(
o
->
o
.
getInDir
(),
o
->
o
.
getName
()));
Map
<
Integer
,
String
>
roadNameMap
=
ridList
.
stream
().
collect
(
Collectors
.
toMap
(
o
->
o
.
getInDir
(),
o
->
o
.
getName
(),
(
existing
,
replacement
)
->
existing
));
for
(
Map
.
Entry
<
Integer
,
List
<
LaneInfoPO
>>
entry
:
collect
.
entrySet
())
{
Integer
key
=
entry
.
getKey
();
DirListElement
dirListElement
=
new
DirListElement
();
...
...
signal-feign-service/src/main/resources/application-docker.properties
View file @
c580c2ef
utc.service.url
=
http://
37.8.219.195
:32000/utc
utc.dt.service.url
=
http://
37.8.219.195
:39002/utc-dt
utc.hisense.service.url
=
http://
37.8.219.195
:39003/utc-hisense
control.url
=
http://
37.8.219.195
:32001/web
utc.service.url
=
http://
173.0.0.1
:32000/utc
utc.dt.service.url
=
http://
173.0.0.1
:39002/utc-dt
utc.hisense.service.url
=
http://
173.0.0.1
:39003/utc-hisense
control.url
=
http://
173.0.0.1
:32001/web
ehualu.url
=
http://37.12.182.29:30015
#
inforsuite.license-path=D:\\license
inforsuite.license-path
=
/license
inforsuite.license-path
=
D:
\\
license
#
inforsuite.license-path=/license
#
inforsuite.license-path
=
/data/license
\ No newline at end of file
signal-utc-service/pom.xml
View file @
c580c2ef
...
...
@@ -28,6 +28,80 @@
</properties>
<dependencies>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-security
</artifactId>
<version>
2.2.2.RELEASE
</version>
</dependency>
<dependency>
<groupId>
org.springframework.security.oauth
</groupId>
<artifactId>
spring-security-oauth2
</artifactId>
<version>
2.3.4.RELEASE
</version>
</dependency>
<dependency>
<groupId>
org.springframework.security.oauth.boot
</groupId>
<artifactId>
spring-security-oauth2-autoconfigure
</artifactId>
<version>
2.1.2.RELEASE
</version>
</dependency>
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt
</artifactId>
<version>
0.9.1
</version>
</dependency>
<!--log4j2 日志实现-->
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-log4j2
</artifactId>
<exclusions>
<exclusion>
<groupId>
org.apache.logging.log4j
</groupId>
<artifactId>
log4j-core
</artifactId>
</exclusion>
<exclusion>
<groupId>
org.apache.logging.log4j
</groupId>
<artifactId>
log4j-api
</artifactId>
</exclusion>
<exclusion>
<groupId>
org.apache.logging.log4j
</groupId>
<artifactId>
log4j-jul
</artifactId>
</exclusion>
<exclusion>
<groupId>
org.apache.logging.log4j
</groupId>
<artifactId>
log4j-slf4j-impl
</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>
org.apache.logging.log4j
</groupId>
<artifactId>
log4j-core
</artifactId>
</dependency>
<dependency>
<groupId>
org.apache.logging.log4j
</groupId>
<artifactId>
log4j-api
</artifactId>
</dependency>
<dependency>
<groupId>
org.apache.logging.log4j
</groupId>
<artifactId>
log4j-jul
</artifactId>
</dependency>
<dependency>
<groupId>
org.apache.logging.log4j
</groupId>
<artifactId>
log4j-slf4j-impl
</artifactId>
</dependency>
<!-- 权限系统 开始 -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
<!-- 权限系统 结束 -->
<dependency>
<groupId>
com.github.xiaoymin
</groupId>
<artifactId>
knife4j-spring-boot-starter
</artifactId>
...
...
@@ -95,6 +169,10 @@
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-tomcat
</artifactId>
</exclusion>
<exclusion>
<artifactId>
spring-boot-starter-logging
</artifactId>
<groupId>
org.springframework.boot
</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 中创中间件inforsuite-->
...
...
@@ -120,6 +198,10 @@
<artifactId>
spring-boot-starter-tomcat
</artifactId>
<groupId>
org.springframework.boot
</groupId>
</exclusion>
<exclusion>
<artifactId>
spring-boot-starter-logging
</artifactId>
<groupId>
org.springframework.boot
</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
...
...
signal-utc-service/src/main/java/net/wanji/utc/config/security/IdentityResourceServerConfig.java
0 → 100644
View file @
c580c2ef
package
net
.
wanji
.
utc
.
config
.
security
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
org.apache.commons.lang.StringUtils
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer
;
import
org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer
;
import
org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter
;
import
org.springframework.security.oauth2.provider.token.store.JwtTokenStore
;
import
javax.servlet.ServletException
;
import
javax.servlet.http.HttpServletResponse
;
import
java.util.HashMap
;
import
java.util.Map
;
/**
* @Description: 业务认证中心 默认资源服务器配置
* 提供默认resource、token、认证接口访问配置
* 用户一般需要重写configure(HttpSecurity http)方法自定义受保护资源,
* 如登录接口白名单或者swagger配置白名单
* @Author mapabc
* @Date 2020/4/12 21:01
*/
public
class
IdentityResourceServerConfig
implements
ResourceServerConfigurer
{
@Value
(
"${security.oauth2.client.client-id}"
)
private
String
resourceId
;
//私钥
private
final
String
SIGN_KEY
=
"dev"
;
@Override
public
void
configure
(
ResourceServerSecurityConfigurer
resources
)
{
//默认使用clientid 作为当前资源id
resources
.
resourceId
(
resourceId
).
stateless
(
true
);
//jwt token 配置
JwtAccessTokenConverter
accessTokenConverter
=
new
JwtAccessTokenConverter
();
accessTokenConverter
.
setSigningKey
(
SIGN_KEY
);
accessTokenConverter
.
setVerifierKey
(
SIGN_KEY
);
resources
.
tokenStore
(
new
JwtTokenStore
(
accessTokenConverter
));
//自定义鉴权失败返回值
resources
.
authenticationEntryPoint
((
request
,
response
,
authException
)
->
{
response
.
setContentType
(
"application/json"
);
response
.
setStatus
(
HttpServletResponse
.
SC_UNAUTHORIZED
);
Map
<
String
,
Object
>
result
=
new
HashMap
<>();
if
(
StringUtils
.
contains
(
authException
.
getMessage
(),
"Access token expired"
))
{
result
.
put
(
"code"
,
407
);
//参见com.wanji.common.framework.HttpCode,作为基础模块,不单独引入依赖
result
.
put
(
"message"
,
"token过期"
);
}
else
{
result
.
put
(
"code"
,
401
);
//参见com.wanji.common.framework.HttpCode,作为基础模块,不单独引入依赖
result
.
put
(
"message"
,
"鉴权失败"
);
}
result
.
put
(
"status"
,
"fail"
);
try
{
ObjectMapper
mapper
=
new
ObjectMapper
();
mapper
.
writeValue
(
response
.
getOutputStream
(),
result
);
}
catch
(
Exception
e
)
{
throw
new
ServletException
();
}
});
}
/**
* @Description: 配置受保护资源,示例如下
*
* http
* .authorizeRequests()
* .antMatchers(
* "/webjars/**",
* "/resources/**",
* "/swagger-ui.html",
* "/swagger-resources/**",
* "/v2/api-docs",
* "/getSwaggerToken",
* "/bp/systemsetting/sysUser/login",
* ).permitAll()
* .anyRequest().authenticated()
* .and()
* .csrf().disable();
*
* @param http
* @Author mapabc
* @Date 2020/4/17 14:48
**/
@Override
public
void
configure
(
HttpSecurity
http
)
throws
Exception
{
http
.
authorizeRequests
().
anyRequest
().
authenticated
();
}
}
signal-utc-service/src/main/java/net/wanji/utc/config/security/IdentitySwaggerConfig.java
0 → 100644
View file @
c580c2ef
package
net
.
wanji
.
utc
.
config
.
security
;
import
io.swagger.annotations.ApiOperation
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Lazy
;
import
org.springframework.security.oauth2.common.OAuth2AccessToken
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
springfox.documentation.builders.ApiInfoBuilder
;
import
springfox.documentation.builders.PathSelectors
;
import
springfox.documentation.builders.RequestHandlerSelectors
;
import
springfox.documentation.service.*
;
import
springfox.documentation.spi.DocumentationType
;
import
springfox.documentation.spi.service.contexts.SecurityContext
;
import
springfox.documentation.spring.web.plugins.Docket
;
import
javax.annotation.Resource
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.Collections
;
import
java.util.List
;
/**
* @Description: swagger2配置,集成oauth2鉴权,默认扫描ApiOperation注解
* @Author mapabc
* @Date 2020/4/15 16:11
*/
public
class
IdentitySwaggerConfig
{
@Value
(
"${security.oauth2.client.access-token-uri:http://localhost:15040/oauth/token}"
)
private
String
accessTokenUri
;
@Resource
@Lazy
OAuth2AccessTokenRestTemplate
restTemplate
;
@Bean
public
Docket
createRestApi
()
{
return
new
Docket
(
DocumentationType
.
SWAGGER_2
)
.
apiInfo
(
apiInfo
())
.
select
()
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.
apis
(
RequestHandlerSelectors
.
any
())
.
paths
(
PathSelectors
.
any
())
.
build
()
.
securitySchemes
(
Arrays
.
asList
(
securityHeaderScheme
()))
.
securityContexts
(
securityContexts
())
;
}
/**
* @return java.util.List<springfox.documentation.service.ApiKey>
* @Description: 配置全局鉴权header
* @Author mapabc
* @Date 2020/4/16 11:35
**/
private
SecurityScheme
securityHeaderScheme
()
{
return
new
ApiKey
(
"Authorization"
,
"tokenId"
,
"header"
);
}
/**
* @return springfox.documentation.service.OAuth
* @Description: 鉴权配置,todo 获取的token自动在请求使用时加进去
* @Author mapabc
* @Date 2020/4/16 11:38
**/
private
SecurityScheme
securityAuthSchema
()
{
return
new
OAuth
(
"Authorization"
,
Collections
.
singletonList
(
new
AuthorizationScope
(
"all"
,
"所有鉴权范围,认证服务器实际上不管这个"
)),
Collections
.
singletonList
(
new
ResourceOwnerPasswordCredentialsGrant
(
accessTokenUri
))
);
}
/**
* @return java.util.List<springfox.documentation.spi.service.contexts.SecurityContext>
* @Description: swagger 安全配置上下文
* @Author mapabc
* @Date 2020/4/16 11:34
**/
private
List
<
SecurityContext
>
securityContexts
()
{
List
<
SecurityContext
>
securityContexts
=
new
ArrayList
<>();
securityContexts
.
add
(
SecurityContext
.
builder
()
.
securityReferences
(
defaultAuth
())
.
forPaths
(
PathSelectors
.
any
())
.
build
());
return
securityContexts
;
}
/**
* @return java.util.List<springfox.documentation.service.SecurityReference>
* @Description: swagger 安全配置权限范围指定
* @Author mapabc
* @Date 2020/4/16 11:34
**/
private
List
<
SecurityReference
>
defaultAuth
()
{
AuthorizationScope
authorizationScope
=
new
AuthorizationScope
(
"all"
,
"全部访问权限"
);
AuthorizationScope
[]
authorizationScopes
=
new
AuthorizationScope
[
1
];
authorizationScopes
[
0
]
=
authorizationScope
;
List
<
SecurityReference
>
securityReferences
=
new
ArrayList
<>();
securityReferences
.
add
(
new
SecurityReference
(
"Authorization"
,
authorizationScopes
));
return
securityReferences
;
}
/**
* @return springfox.documentation.service.ApiInfo
* @Description: swagger 描述展示信息配置
* @Author mapabc
* @Date 2020/4/16 11:33
**/
public
ApiInfo
apiInfo
()
{
return
new
ApiInfoBuilder
()
.
title
(
"GIS云中台 API 接口服务"
)
.
description
(
"GISC-Restful Open API 文档"
)
.
version
(
"v1"
)
.
build
();
}
@ApiOperation
(
value
=
"token获取"
,
notes
=
"token获取"
,
response
=
String
.
class
)
@GetMapping
(
value
=
"/getSwaggerToken"
)
public
String
getSwaggerToken
()
throws
Exception
{
OAuth2AccessToken
auth2AccessToken
=
restTemplate
.
getTokenWithClientCredentialsGrantType
();
if
(
null
==
auth2AccessToken
)
{
return
"获取token失败,请检查配置!"
;
}
return
auth2AccessToken
.
getTokenType
()
+
" "
+
auth2AccessToken
.
getValue
();
}
}
signal-utc-service/src/main/java/net/wanji/utc/config/security/IdentityTokenHelper.java
0 → 100644
View file @
c580c2ef
package
net
.
wanji
.
utc
.
config
.
security
;
import
io.jsonwebtoken.Claims
;
import
io.jsonwebtoken.JwtParser
;
import
io.jsonwebtoken.Jwts
;
import
org.apache.commons.lang.StringUtils
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.security.oauth2.client.OAuth2ClientContext
;
import
org.springframework.security.oauth2.common.OAuth2AccessToken
;
import
org.springframework.stereotype.Component
;
import
java.util.Map
;
import
static
java
.
nio
.
charset
.
StandardCharsets
.
UTF_8
;
/**
* @Description: token 解析工具类,封装预置私钥读取方法及spring上下文中获取token方式
* @Author mapabc
* @Date 2020/6/17 11:00
*/
@Component
public
class
IdentityTokenHelper
{
@Value
(
"${security.oauth2.resource.jwt.key-value}"
)
private
String
signKey
;
@Autowired
OAuth2ClientContext
oAuth2ClientContext
;
public
static
final
String
TOKEN_EXTENSION_KEY
=
"jwt-ext"
;
/**
* @return io.jsonwebtoken.JwtParser
* @Description: 获取jwt token解析器,封装私钥操作
* 私钥自动读取security.oauth2.resource.jwt.key-value
* 使用前置条件1:spring 应用扫描路径需要覆盖 com.wanji.identity.auth
* <p>
* JwtParser使用token body示例:IdentityTokenHelper#getJwtParser().parseClaimsJws(auth2AccessToken.getValue()).getBody();
* @Author mapabc
* @Date 2020/6/17 12:16
**/
public
JwtParser
getJwtParser
()
{
if
(
StringUtils
.
isNotBlank
(
signKey
))
{
return
Jwts
.
parser
().
setSigningKey
(
signKey
.
getBytes
(
UTF_8
));
}
return
null
;
}
/**
* @param key 键
* @return java.lang.String 值,写入读取预置封装string
* @Description: 根据key查询token扩展参数中的value
* <p>
* 前置条件1:使用com.wanji.identity.auth.OAuth2AccessTokenRestTemplate 获取token被传入扩展参数,使用方式可参考示例
* @Author mapabc
* @Date 2020/6/17 12:12
* @see OAuth2AccessTokenRestTemplate#getTokenWithPasswordGrantType(String, String, Map)
* 前置条件2:spring 应用扫描路径需要覆盖 com.wanji.identity.auth
**/
public
String
getValueByKeyFromTokenBodyExtension
(
String
key
)
{
if
(
StringUtils
.
isNotBlank
(
signKey
))
{
OAuth2AccessToken
auth2AccessToken
=
oAuth2ClientContext
.
getAccessToken
();
if
(
null
!=
auth2AccessToken
)
{
Claims
claims
=
Jwts
.
parser
().
setSigningKey
(
signKey
.
getBytes
(
UTF_8
)).
parseClaimsJws
(
auth2AccessToken
.
getValue
()).
getBody
();
if
(
null
!=
claims
&&
null
!=
claims
.
get
(
TOKEN_EXTENSION_KEY
))
{
if
(
claims
.
get
(
TOKEN_EXTENSION_KEY
)
instanceof
Map
)
{
Map
extension
=
(
Map
)
claims
.
get
(
TOKEN_EXTENSION_KEY
);
return
(
String
)
extension
.
getOrDefault
(
key
,
""
);
}
}
}
}
return
""
;
}
public
String
getValueByKeyFromTokenBodyExtension
(
String
tokenValue
,
String
key
)
{
if
(
StringUtils
.
isNotBlank
(
signKey
))
{
Claims
claims
=
Jwts
.
parser
().
setSigningKey
(
signKey
.
getBytes
(
UTF_8
)).
parseClaimsJws
(
tokenValue
).
getBody
();
if
(
null
!=
claims
&&
null
!=
claims
.
get
(
TOKEN_EXTENSION_KEY
))
{
if
(
claims
.
get
(
TOKEN_EXTENSION_KEY
)
instanceof
Map
)
{
Map
extension
=
(
Map
)
claims
.
get
(
TOKEN_EXTENSION_KEY
);
return
(
String
)
extension
.
getOrDefault
(
key
,
""
);
}
}
}
return
""
;
}
}
signal-utc-service/src/main/java/net/wanji/utc/config/security/OAuth2AccessTokenRestTemplate.java
0 → 100644
View file @
c580c2ef
package
net
.
wanji
.
utc
.
config
.
security
;
import
com.alibaba.fastjson.JSON
;
import
com.alibaba.fastjson.JSONObject
;
import
org.apache.commons.lang.StringUtils
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.context.annotation.Lazy
;
import
org.springframework.http.*
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.core.userdetails.User
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails
;
import
org.springframework.security.oauth2.common.DefaultOAuth2AccessToken
;
import
org.springframework.security.oauth2.common.OAuth2AccessToken
;
import
org.springframework.security.oauth2.provider.endpoint.TokenEndpoint
;
import
org.springframework.util.LinkedMultiValueMap
;
import
org.springframework.util.MultiValueMap
;
import
org.springframework.web.client.RestTemplate
;
import
java.util.*
;
@Configuration
public
class
OAuth2AccessTokenRestTemplate
{
private
final
String
GRANT_TYPE_PASSWORD
=
"password"
;
private
final
String
GRANT_TYPE_CLIENT_CREDENTIALS
=
"client_credentials"
;
private
final
String
USERNAME
=
"username"
;
private
final
String
PASSWORD
=
"password"
;
private
final
String
GRANT_TYPE
=
"grant_type"
;
private
final
String
GRANT_SCOPE
=
"scope"
;
@Autowired
OAuth2ClientProperties
oAuth2ClientProperties
;
@Autowired
OAuth2ProtectedResourceDetails
oAuth2ProtectedResourceDetails
;
private
RestTemplate
restTemplate
;
@Autowired
@Lazy
TokenEndpoint
tokenEndpoint
;
public
OAuth2AccessTokenRestTemplate
()
{
}
private
RestTemplate
getRestTemplate
()
{
if
(
null
==
this
.
restTemplate
)
{
this
.
restTemplate
=
new
RestTemplate
();
}
return
this
.
restTemplate
;
}
public
OAuth2AccessToken
getTokenWithPasswordGrantType
(
String
username
,
String
password
,
Map
<
String
,
String
>
ext
)
throws
Exception
{
return
this
.
getToken
((
String
)
null
,
(
String
)
null
,
username
,
password
,
"password"
,
ext
);
}
public
OAuth2AccessToken
getTokenWithPasswordGrantType
(
String
username
,
String
password
)
throws
Exception
{
return
this
.
getTokenWithPasswordGrantType
(
username
,
password
,
(
Map
)
null
);
}
public
OAuth2AccessToken
getTokenWithPasswordGrantType
(
String
clientId
,
String
clientSecret
,
String
username
,
String
password
,
Map
<
String
,
String
>
ext
)
throws
Exception
{
return
this
.
getToken
(
clientId
,
clientSecret
,
username
,
password
,
"password"
,
ext
);
}
public
OAuth2AccessToken
getTokenWithPasswordGrantType
(
String
clientId
,
String
clientSecret
,
String
username
,
String
password
)
throws
Exception
{
return
this
.
getTokenWithPasswordGrantType
(
clientId
,
clientSecret
,
username
,
password
,
(
Map
)
null
);
}
public
OAuth2AccessToken
getTokenWithClientCredentialsGrantType
(
Map
<
String
,
String
>
ext
)
throws
Exception
{
return
this
.
getToken
((
String
)
null
,
(
String
)
null
,
(
String
)
null
,
(
String
)
null
,
"client_credentials"
,
ext
);
}
public
OAuth2AccessToken
getTokenWithClientCredentialsGrantType
()
throws
Exception
{
return
this
.
getTokenWithClientCredentialsGrantType
((
Map
)
null
);
}
public
OAuth2AccessToken
getTokenWithClientCredentialsGrantType
(
String
clientId
,
String
clientSecret
,
Map
<
String
,
String
>
ext
)
throws
Exception
{
return
this
.
getToken
(
clientId
,
clientSecret
,
(
String
)
null
,
(
String
)
null
,
"client_credentials"
,
ext
);
}
public
OAuth2AccessToken
getTokenWithClientCredentialsGrantType
(
String
clientId
,
String
clientSecret
)
throws
Exception
{
return
this
.
getTokenWithClientCredentialsGrantType
(
clientId
,
clientSecret
,
(
Map
)
null
);
}
public
OAuth2AccessToken
getTokenWithAuthorizationCodeGrantType
(
Map
<
String
,
String
>
ext
)
throws
Exception
{
return
null
;
}
public
OAuth2AccessToken
getTokenWithAuthorizationCodeGrantType
()
throws
Exception
{
return
this
.
getTokenWithAuthorizationCodeGrantType
((
Map
)
null
);
}
private
OAuth2AccessToken
getToken
(
String
clientId
,
String
clientSecret
,
String
username
,
String
password
,
String
grantType
,
Map
<
String
,
String
>
ext
)
throws
Exception
{
long
start
=
System
.
currentTimeMillis
();
DefaultOAuth2AccessToken
accessToken
=
null
;
ResponseEntity
response
=
null
;
try
{
System
.
out
.
println
(
"========1.1=======OAuth2AccessTokenRestTemplate======getToken========="
+
(
System
.
currentTimeMillis
()
-
start
));
UserDetails
user
=
User
.
builder
().
username
(
StringUtils
.
isBlank
(
clientId
)
?
this
.
oAuth2ClientProperties
.
getClientId
()
:
clientId
).
password
(
StringUtils
.
isBlank
(
clientSecret
)
?
this
.
oAuth2ClientProperties
.
getClientSecret
()
:
clientSecret
).
roles
(
new
String
[]{
"admin"
}).
build
();
response
=
this
.
tokenEndpoint
.
postAccessToken
(
new
UsernamePasswordAuthenticationToken
(
user
,
password
,
user
.
getAuthorities
()),
new
HashMap
<
String
,
String
>()
{
{
this
.
put
(
"username"
,
username
);
this
.
put
(
"password"
,
password
);
this
.
put
(
"grant_type"
,
grantType
);
this
.
put
(
"scope"
,
String
.
join
(
","
,
OAuth2AccessTokenRestTemplate
.
this
.
oAuth2ProtectedResourceDetails
.
getScope
()));
this
.
putAll
(
ext
);
}
});
System
.
out
.
println
(
"========1.2=======OAuth2AccessTokenRestTemplate======postAccessToken========="
+
(
System
.
currentTimeMillis
()
-
start
));
accessToken
=
(
DefaultOAuth2AccessToken
)
JSONObject
.
toJavaObject
((
JSON
)
JSONObject
.
toJSON
(
response
.
getBody
()),
DefaultOAuth2AccessToken
.
class
);
System
.
out
.
println
(
"========1.3=======OAuth2AccessTokenRestTemplate======toJavaObject========="
+
(
System
.
currentTimeMillis
()
-
start
));
}
catch
(
Exception
var12
)
{
throw
new
Exception
(
var12
.
getMessage
());
}
if
(!
Objects
.
isNull
(
accessToken
)
&&
!
StringUtils
.
isBlank
(
accessToken
.
getValue
()))
{
return
accessToken
;
}
else
{
throw
new
Exception
((
String
)((
Map
)
response
.
getBody
()).
get
(
"message"
));
}
}
private
OAuth2AccessToken
getTokenByHttp
(
String
clientId
,
String
clientSecret
,
String
username
,
String
password
,
String
grantType
,
Map
<
String
,
String
>
ext
)
throws
Exception
{
HttpHeaders
httpHeaders
=
new
HttpHeaders
();
httpHeaders
.
setContentType
(
MediaType
.
APPLICATION_FORM_URLENCODED
);
httpHeaders
.
setBasicAuth
(
StringUtils
.
isBlank
(
clientId
)
?
this
.
oAuth2ClientProperties
.
getClientId
()
:
clientId
,
StringUtils
.
isBlank
(
clientSecret
)
?
this
.
oAuth2ClientProperties
.
getClientSecret
()
:
clientSecret
);
MultiValueMap
<
String
,
String
>
map
=
new
LinkedMultiValueMap
();
if
(
StringUtils
.
isNotEmpty
(
username
))
{
map
.
put
(
"username"
,
Collections
.
singletonList
(
username
));
}
if
(
StringUtils
.
isNotEmpty
(
password
))
{
map
.
put
(
"password"
,
Collections
.
singletonList
(
password
));
}
map
.
put
(
"grant_type"
,
Collections
.
singletonList
(
grantType
));
map
.
put
(
"scope"
,
this
.
oAuth2ProtectedResourceDetails
.
getScope
());
if
(
null
!=
ext
&&
!
ext
.
isEmpty
())
{
ext
.
forEach
((
k
,
v
)
->
{
List
var10000
=
(
List
)
map
.
put
(
k
,
Collections
.
singletonList
(
v
));
});
}
HttpEntity
httpEntity
=
new
HttpEntity
(
map
,
httpHeaders
);
DefaultOAuth2AccessToken
accessToken
=
null
;
ResponseEntity
response
=
null
;
try
{
response
=
this
.
getRestTemplate
().
exchange
(
this
.
oAuth2ProtectedResourceDetails
.
getAccessTokenUri
(),
HttpMethod
.
POST
,
httpEntity
,
Object
.
class
,
new
Object
[
0
]);
accessToken
=
(
DefaultOAuth2AccessToken
)
JSONObject
.
toJavaObject
((
JSON
)
JSONObject
.
toJSON
(
response
.
getBody
()),
DefaultOAuth2AccessToken
.
class
);
}
catch
(
Exception
var13
)
{
throw
new
Exception
(
var13
.
getMessage
());
}
if
(!
Objects
.
isNull
(
accessToken
)
&&
!
StringUtils
.
isBlank
(
accessToken
.
getValue
()))
{
return
accessToken
;
}
else
{
throw
new
Exception
((
String
)((
Map
)
response
.
getBody
()).
get
(
"message"
));
}
}
}
signal-utc-service/src/main/java/net/wanji/utc/config/security/ResourceServerConfig.java
0 → 100644
View file @
c580c2ef
package
net
.
wanji
.
utc
.
config
.
security
;
import
net.wanji.common.framework.rest.HeaderMapRequestWrapper
;
import
net.wanji.common.utils.cookie.CookieUtil
;
import
net.wanji.common.utils.tool.StringUtils
;
import
net.wanji.common.utils.cache.IgniteClientCacheUtil
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.oauth2.common.OAuth2AccessToken
;
import
org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer
;
import
org.springframework.security.web.context.SecurityContextPersistenceFilter
;
import
org.springframework.security.web.util.matcher.RequestMatcher
;
import
org.springframework.web.filter.OncePerRequestFilter
;
import
javax.servlet.FilterChain
;
import
javax.servlet.ServletException
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.IOException
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.List
;
import
java.util.Objects
;
import
static
net
.
wanji
.
common
.
framework
.
Constants
.
Cache
.
LOGIN_CACHE
;
/**
* @Description: 资源服务器配置
* @Author
* @Date 2020/4/12 21:01
*/
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity
(
prePostEnabled
=
true
)
@Slf4j
public
class
ResourceServerConfig
extends
IdentityResourceServerConfig
{
private
static
String
profileActive
;
@Value
(
"${spring.profiles.active}"
)
public
void
setProfileActive
(
String
profileActive
)
{
ResourceServerConfig
.
profileActive
=
profileActive
;
}
@Override
public
void
configure
(
HttpSecurity
http
)
throws
Exception
{
// 放开全部
http
.
authorizeRequests
()
.
antMatchers
(
whiteList
.
toArray
(
new
String
[
whiteList
.
size
()])).
permitAll
()
.
requestMatchers
(
new
IpRequestMatcher
()).
permitAll
()
.
anyRequest
().
authenticated
()
.
and
().
cors
()
.
and
().
csrf
().
disable
()
.
addFilterBefore
(
new
OncePerRequestFilter
()
{
@Override
protected
void
doFilterInternal
(
HttpServletRequest
request
,
HttpServletResponse
response
,
FilterChain
filterChain
)
throws
ServletException
,
IOException
{
String
breakerToken
=
" "
;
// 判断header里有没有authorization,有则赋值给breakertoken,没有则根据tokenid
if
(
StringUtils
.
isNotBlank
(
request
.
getHeader
(
HttpHeaders
.
AUTHORIZATION
)))
{
breakerToken
=
request
.
getHeader
(
HttpHeaders
.
AUTHORIZATION
);
}
else
{
String
tokenId
=
""
;
// 移动端的tokenid在请求头里,pc端的在cookie里
String
mobileTokenId
=
request
.
getHeader
(
"tokenId"
);
if
(
StringUtils
.
isNotBlank
(
mobileTokenId
))
{
tokenId
=
mobileTokenId
;
}
else
{
tokenId
=
CookieUtil
.
getUid
(
request
,
"tokenId"
);
}
if
(
StringUtils
.
isNotBlank
(
tokenId
))
{
try
{
OAuth2AccessToken
oAuth2AccessToken
=
(
OAuth2AccessToken
)
IgniteClientCacheUtil
.
getValue
(
LOGIN_CACHE
,
tokenId
);
breakerToken
=
oAuth2AccessToken
.
getTokenType
()
+
" "
+
oAuth2AccessToken
.
getValue
();
}
catch
(
Exception
e
)
{
log
.
error
(
""
,
e
);
}
}
}
HeaderMapRequestWrapper
requestWrapper
=
new
HeaderMapRequestWrapper
(
request
);
if
(
StringUtils
.
isNotBlank
(
breakerToken
))
{
//将cookie中的token放到header,供oauth鉴权使用
requestWrapper
.
addHeader
(
HttpHeaders
.
AUTHORIZATION
,
breakerToken
);
}
filterChain
.
doFilter
(
requestWrapper
,
response
);
}
},
SecurityContextPersistenceFilter
.
class
);
}
//内部类,IP白名单匹配器
private
static
class
IpRequestMatcher
implements
RequestMatcher
{
//IPV4 和IPV6本地地址
private
static
final
List
<
String
>
ALLOWED_IPS
=
Arrays
.
asList
(
"127.0.0.1"
,
"173.17.0.1"
,
"0:0:0:0:0:0:0:1"
);
@Override
public
boolean
matches
(
HttpServletRequest
request
)
{
String
remoteAddr
=
request
.
getRemoteAddr
();
return
ALLOWED_IPS
.
contains
(
remoteAddr
);
}
@Override
public
MatchResult
matcher
(
HttpServletRequest
request
)
{
return
RequestMatcher
.
super
.
matcher
(
request
);
}
}
//访问白名单
private
static
final
List
<
String
>
whiteList
=
new
ArrayList
<
String
>()
{{
//swagger
add
(
"/webjars/**"
);
add
(
"/resources/**"
);
add
(
"/swagger-ui.html"
);
add
(
"/swagger-resources/**"
);
add
(
"/v2/api-docs"
);
add
(
"/getSwaggerToken"
);
add
(
"/"
);
add
(
"/**/*.html"
);
add
(
"/**/*.htm"
);
add
(
"/**/*.woff"
);
add
(
"/**/*.woff2"
);
add
(
"/**/*.ttf"
);
add
(
"/**/*.svg"
);
add
(
"/**/*.css"
);
add
(
"/**/*.png"
);
add
(
"/**/*.jpg"
);
add
(
"/**/*.gif"
);
add
(
"/**/*.ico"
);
add
(
"/**/*.json"
);
add
(
"/**/*.js"
);
add
(
"/**/*.txt"
);
add
(
"/utc/signalStatus/**"
);
//add("/cross/*");
// add("/**") ;
// add("/**");
if
(
Objects
.
equals
(
"test"
,
profileActive
))
{
//测试环境放开接口
add
(
"/**"
);
}
}};
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
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 comment