Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
G
guns-vip
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
chenjunxiong
guns-vip
Commits
60e05b30
Commit
60e05b30
authored
Aug 23, 2017
by
stylefeng
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
guns-rest增加auth验证接口
parent
d7d33e13
Hide whitespace changes
Inline
Side-by-side
Showing
21 changed files
with
991 additions
and
1 deletions
+991
-1
guns-rest/pom.xml
+9
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/GunsRestApplication.java
+1
-1
guns-rest/src/main/java/com/stylefeng/guns/rest/auth/JwtTokenUtil.java
+137
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/config/FastjsonConfig.java
+50
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/config/MybatisPlusConfig.java
+48
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/config/properties/DruidProperties.java
+221
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/config/properties/JwtProperties.java
+61
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/controller/AuthenticationRestController.java
+42
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/persistence/dao/UserMapper.java
+17
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/persistence/dao/mapping/UserMapper.xml
+11
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/persistence/model/User.java
+52
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/service/IReqValidator.java
+22
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/service/impl/DbValidator.java
+34
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/service/impl/SimpleValidator.java
+33
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/transfer/JwtAuthenticationRequest.java
+39
-0
guns-rest/src/main/java/com/stylefeng/guns/rest/transfer/JwtAuthenticationResponse.java
+21
-0
guns-rest/src/main/resources/application.properties
+0
-0
guns-rest/src/main/resources/application.yml
+33
-0
guns-rest/src/test/java/com/stylefeng/guns/generator/EntityGenerator.java
+92
-0
guns-rest/src/test/java/com/stylefeng/guns/jwt/DecryptTest.java
+23
-0
guns-rest/src/test/java/com/stylefeng/guns/jwt/JWTTest.java
+45
-0
No files found.
guns-rest/pom.xml
View file @
60e05b30
...
@@ -25,10 +25,19 @@
...
@@ -25,10 +25,19 @@
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-mobile
</artifactId>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-test
</artifactId>
<artifactId>
spring-boot-starter-test
</artifactId>
<scope>
test
</scope>
<scope>
test
</scope>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>
org.apache.velocity
</groupId>
<artifactId>
velocity
</artifactId>
<scope>
test
</scope>
</dependency>
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt
</artifactId>
<artifactId>
jjwt
</artifactId>
</dependency>
</dependency>
...
...
guns-rest/src/main/java/com/stylefeng/guns/GunsRestApplication.java
→
guns-rest/src/main/java/com/stylefeng/guns/
rest/
GunsRestApplication.java
View file @
60e05b30
package
com
.
stylefeng
.
guns
;
package
com
.
stylefeng
.
guns
.
rest
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
...
...
guns-rest/src/main/java/com/stylefeng/guns/rest/auth/JwtTokenUtil.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
auth
;
import
com.stylefeng.guns.rest.config.properties.JwtProperties
;
import
io.jsonwebtoken.Claims
;
import
io.jsonwebtoken.Jwts
;
import
io.jsonwebtoken.SignatureAlgorithm
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.mobile.device.Device
;
import
org.springframework.stereotype.Component
;
import
java.io.Serializable
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.Map
;
import
java.util.function.Function
;
@Component
public
class
JwtTokenUtil
implements
Serializable
{
@Autowired
private
JwtProperties
jwtProperties
;
private
static
final
long
serialVersionUID
=
-
3301605591108950415L
;
static
final
String
CLAIM_KEY_USERNAME
=
"sub"
;
static
final
String
CLAIM_KEY_AUDIENCE
=
"aud"
;
static
final
String
CLAIM_KEY_CREATED
=
"iat"
;
static
final
String
AUDIENCE_UNKNOWN
=
"unknown"
;
static
final
String
AUDIENCE_WEB
=
"web"
;
static
final
String
AUDIENCE_MOBILE
=
"mobile"
;
static
final
String
AUDIENCE_TABLET
=
"tablet"
;
public
String
getUsernameFromToken
(
String
token
)
{
return
getClaimFromToken
(
token
,
Claims:
:
getSubject
);
}
public
Date
getIssuedAtDateFromToken
(
String
token
)
{
return
getClaimFromToken
(
token
,
Claims:
:
getIssuedAt
);
}
public
Date
getExpirationDateFromToken
(
String
token
)
{
return
getClaimFromToken
(
token
,
Claims:
:
getExpiration
);
}
public
String
getAudienceFromToken
(
String
token
)
{
return
getClaimFromToken
(
token
,
Claims:
:
getAudience
);
}
public
<
T
>
T
getClaimFromToken
(
String
token
,
Function
<
Claims
,
T
>
claimsResolver
)
{
final
Claims
claims
=
getAllClaimsFromToken
(
token
);
return
claimsResolver
.
apply
(
claims
);
}
private
Claims
getAllClaimsFromToken
(
String
token
)
{
return
Jwts
.
parser
()
.
setSigningKey
(
jwtProperties
.
getSecret
())
.
parseClaimsJws
(
token
)
.
getBody
();
}
private
Boolean
isTokenExpired
(
String
token
)
{
final
Date
expiration
=
getExpirationDateFromToken
(
token
);
return
expiration
.
before
(
new
Date
());
}
private
Boolean
isCreatedBeforeLastPasswordReset
(
Date
created
,
Date
lastPasswordReset
)
{
return
(
lastPasswordReset
!=
null
&&
created
.
before
(
lastPasswordReset
));
}
private
String
generateAudience
(
Device
device
)
{
String
audience
=
AUDIENCE_UNKNOWN
;
if
(
device
.
isNormal
())
{
audience
=
AUDIENCE_WEB
;
}
else
if
(
device
.
isTablet
())
{
audience
=
AUDIENCE_TABLET
;
}
else
if
(
device
.
isMobile
())
{
audience
=
AUDIENCE_MOBILE
;
}
return
audience
;
}
private
Boolean
ignoreTokenExpiration
(
String
token
)
{
String
audience
=
getAudienceFromToken
(
token
);
return
(
AUDIENCE_TABLET
.
equals
(
audience
)
||
AUDIENCE_MOBILE
.
equals
(
audience
));
}
public
String
generateToken
(
String
userName
,
Device
device
)
{
Map
<
String
,
Object
>
claims
=
new
HashMap
<>();
return
doGenerateToken
(
claims
,
userName
,
generateAudience
(
device
));
}
private
String
doGenerateToken
(
Map
<
String
,
Object
>
claims
,
String
subject
,
String
audience
)
{
final
Date
createdDate
=
new
Date
();
final
Date
expirationDate
=
new
Date
(
createdDate
.
getTime
()
+
jwtProperties
.
getExpiration
()
*
1000
);
System
.
out
.
println
(
"doGenerateToken "
+
createdDate
);
return
Jwts
.
builder
()
.
setClaims
(
claims
)
.
setSubject
(
subject
)
.
setAudience
(
audience
)
.
setIssuedAt
(
createdDate
)
.
setExpiration
(
expirationDate
)
.
signWith
(
SignatureAlgorithm
.
HS512
,
jwtProperties
.
getSecret
())
.
compact
();
}
public
Boolean
canTokenBeRefreshed
(
String
token
,
Date
lastPasswordReset
)
{
final
Date
created
=
getIssuedAtDateFromToken
(
token
);
return
!
isCreatedBeforeLastPasswordReset
(
created
,
lastPasswordReset
)
&&
(!
isTokenExpired
(
token
)
||
ignoreTokenExpiration
(
token
));
}
public
String
refreshToken
(
String
token
)
{
final
Claims
claims
=
getAllClaimsFromToken
(
token
);
claims
.
setIssuedAt
(
new
Date
());
return
doRefreshToken
(
claims
);
}
public
String
doRefreshToken
(
Claims
claims
)
{
return
Jwts
.
builder
()
.
setClaims
(
claims
)
.
signWith
(
SignatureAlgorithm
.
HS512
,
jwtProperties
.
getSecret
())
.
compact
();
}
public
Boolean
validateToken
(
String
token
,
String
userName
)
{
final
String
username
=
getUsernameFromToken
(
token
);
final
Date
created
=
getIssuedAtDateFromToken
(
token
);
//final Date expiration = getExpirationDateFromToken(token);
return
(
username
.
equals
(
userName
)
&&
!
isTokenExpired
(
token
));
}
}
\ No newline at end of file
guns-rest/src/main/java/com/stylefeng/guns/rest/config/FastjsonConfig.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
config
;
import
com.alibaba.fastjson.serializer.SerializerFeature
;
import
com.alibaba.fastjson.serializer.ValueFilter
;
import
com.alibaba.fastjson.support.config.FastJsonConfig
;
import
com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.http.MediaType
;
import
java.nio.charset.Charset
;
import
java.util.ArrayList
;
/**
* fastjson配置类
*
* @author fengshuonan
* @date 2017-05-23 22:56
*/
@Configuration
public
class
FastjsonConfig
{
@Bean
public
FastJsonHttpMessageConverter4
fastJsonHttpMessageConverter
()
{
FastJsonHttpMessageConverter4
converter
=
new
FastJsonHttpMessageConverter4
();
FastJsonConfig
fastJsonConfig
=
new
FastJsonConfig
();
fastJsonConfig
.
setSerializerFeatures
(
SerializerFeature
.
PrettyFormat
,
SerializerFeature
.
WriteMapNullValue
);
fastJsonConfig
.
setDateFormat
(
"yyyy-MM-dd HH:mm:ss"
);
ValueFilter
valueFilter
=
new
ValueFilter
()
{
public
Object
process
(
Object
o
,
String
s
,
Object
o1
)
{
if
(
null
==
o1
)
{
o1
=
""
;
}
return
o1
;
}
};
fastJsonConfig
.
setCharset
(
Charset
.
forName
(
"utf-8"
));
fastJsonConfig
.
setSerializeFilters
(
valueFilter
);
converter
.
setFastJsonConfig
(
fastJsonConfig
);
ArrayList
<
MediaType
>
mediaTypes
=
new
ArrayList
<>();
mediaTypes
.
add
(
MediaType
.
APPLICATION_JSON_UTF8
);
converter
.
setSupportedMediaTypes
(
mediaTypes
);
return
converter
;
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/config/MybatisPlusConfig.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
config
;
import
com.alibaba.druid.pool.DruidDataSource
;
import
com.baomidou.mybatisplus.plugins.PaginationInterceptor
;
import
com.stylefeng.guns.rest.config.properties.DruidProperties
;
import
org.mybatis.spring.annotation.MapperScan
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
/**
* MybatisPlus配置
*
* @author stylefeng
* @Date 2017年8月23日12:51:41
*/
@Configuration
@MapperScan
(
basePackages
=
{
"com.stylefeng.guns.rest.*.dao"
,
"com.stylefeng.guns.rest.persistence.dao"
})
public
class
MybatisPlusConfig
{
@Autowired
DruidProperties
druidProperties
;
/**
* guns的数据源
*/
private
DruidDataSource
dataSourceGuns
()
{
DruidDataSource
dataSource
=
new
DruidDataSource
();
druidProperties
.
config
(
dataSource
);
return
dataSource
;
}
/**
* 单数据源连接池配置
*/
@Bean
public
DruidDataSource
singleDatasource
()
{
return
dataSourceGuns
();
}
/**
* mybatis-plus分页插件
*/
@Bean
public
PaginationInterceptor
paginationInterceptor
()
{
return
new
PaginationInterceptor
();
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/config/properties/DruidProperties.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
config
.
properties
;
import
com.alibaba.druid.pool.DruidDataSource
;
import
org.springframework.boot.context.properties.ConfigurationProperties
;
import
org.springframework.stereotype.Component
;
import
java.sql.SQLException
;
/**
* <p>数据库数据源配置</p>
* <p>说明:这个类中包含了许多默认配置,若这些配置符合您的情况,您可以不用管,若不符合,建议不要修改本类,建议直接在"application.yml"中配置即可</p>
* @author fengshuonan
* @date 2017-05-21 11:18
*/
@Component
@ConfigurationProperties
(
prefix
=
"spring.datasource"
)
public
class
DruidProperties
{
private
String
url
=
"jdbc:mysql://127.0.0.1:3306/guns?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull"
;
private
String
username
=
"root"
;
private
String
password
=
"root"
;
private
String
driverClassName
=
"com.mysql.jdbc.Driver"
;
private
Integer
initialSize
=
2
;
private
Integer
minIdle
=
1
;
private
Integer
maxActive
=
20
;
private
Integer
maxWait
=
60000
;
private
Integer
timeBetweenEvictionRunsMillis
=
60000
;
private
Integer
minEvictableIdleTimeMillis
=
300000
;
private
String
validationQuery
=
"SELECT 'x'"
;
private
Boolean
testWhileIdle
=
true
;
private
Boolean
testOnBorrow
=
false
;
private
Boolean
testOnReturn
=
false
;
private
Boolean
poolPreparedStatements
=
true
;
private
Integer
maxPoolPreparedStatementPerConnectionSize
=
20
;
private
String
filters
=
"stat"
;
public
void
config
(
DruidDataSource
dataSource
)
{
dataSource
.
setUrl
(
url
);
dataSource
.
setUsername
(
username
);
dataSource
.
setPassword
(
password
);
dataSource
.
setDriverClassName
(
driverClassName
);
dataSource
.
setInitialSize
(
initialSize
);
//定义初始连接数
dataSource
.
setMinIdle
(
minIdle
);
//最小空闲
dataSource
.
setMaxActive
(
maxActive
);
//定义最大连接数
dataSource
.
setMaxWait
(
maxWait
);
//最长等待时间
// 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
dataSource
.
setTimeBetweenEvictionRunsMillis
(
timeBetweenEvictionRunsMillis
);
// 配置一个连接在池中最小生存的时间,单位是毫秒
dataSource
.
setMinEvictableIdleTimeMillis
(
minEvictableIdleTimeMillis
);
dataSource
.
setValidationQuery
(
validationQuery
);
dataSource
.
setTestWhileIdle
(
testWhileIdle
);
dataSource
.
setTestOnBorrow
(
testOnBorrow
);
dataSource
.
setTestOnReturn
(
testOnReturn
);
// 打开PSCache,并且指定每个连接上PSCache的大小
dataSource
.
setPoolPreparedStatements
(
poolPreparedStatements
);
dataSource
.
setMaxPoolPreparedStatementPerConnectionSize
(
maxPoolPreparedStatementPerConnectionSize
);
try
{
dataSource
.
setFilters
(
filters
);
}
catch
(
SQLException
e
)
{
e
.
printStackTrace
();
}
}
public
String
getUrl
()
{
return
url
;
}
public
void
setUrl
(
String
url
)
{
this
.
url
=
url
;
}
public
String
getUsername
()
{
return
username
;
}
public
void
setUsername
(
String
username
)
{
this
.
username
=
username
;
}
public
String
getPassword
()
{
return
password
;
}
public
void
setPassword
(
String
password
)
{
this
.
password
=
password
;
}
public
String
getDriverClassName
()
{
return
driverClassName
;
}
public
void
setDriverClassName
(
String
driverClassName
)
{
this
.
driverClassName
=
driverClassName
;
}
public
Integer
getInitialSize
()
{
return
initialSize
;
}
public
void
setInitialSize
(
Integer
initialSize
)
{
this
.
initialSize
=
initialSize
;
}
public
Integer
getMinIdle
()
{
return
minIdle
;
}
public
void
setMinIdle
(
Integer
minIdle
)
{
this
.
minIdle
=
minIdle
;
}
public
Integer
getMaxActive
()
{
return
maxActive
;
}
public
void
setMaxActive
(
Integer
maxActive
)
{
this
.
maxActive
=
maxActive
;
}
public
Integer
getMaxWait
()
{
return
maxWait
;
}
public
void
setMaxWait
(
Integer
maxWait
)
{
this
.
maxWait
=
maxWait
;
}
public
Integer
getTimeBetweenEvictionRunsMillis
()
{
return
timeBetweenEvictionRunsMillis
;
}
public
void
setTimeBetweenEvictionRunsMillis
(
Integer
timeBetweenEvictionRunsMillis
)
{
this
.
timeBetweenEvictionRunsMillis
=
timeBetweenEvictionRunsMillis
;
}
public
Integer
getMinEvictableIdleTimeMillis
()
{
return
minEvictableIdleTimeMillis
;
}
public
void
setMinEvictableIdleTimeMillis
(
Integer
minEvictableIdleTimeMillis
)
{
this
.
minEvictableIdleTimeMillis
=
minEvictableIdleTimeMillis
;
}
public
String
getValidationQuery
()
{
return
validationQuery
;
}
public
void
setValidationQuery
(
String
validationQuery
)
{
this
.
validationQuery
=
validationQuery
;
}
public
Boolean
getTestWhileIdle
()
{
return
testWhileIdle
;
}
public
void
setTestWhileIdle
(
Boolean
testWhileIdle
)
{
this
.
testWhileIdle
=
testWhileIdle
;
}
public
Boolean
getTestOnBorrow
()
{
return
testOnBorrow
;
}
public
void
setTestOnBorrow
(
Boolean
testOnBorrow
)
{
this
.
testOnBorrow
=
testOnBorrow
;
}
public
Boolean
getTestOnReturn
()
{
return
testOnReturn
;
}
public
void
setTestOnReturn
(
Boolean
testOnReturn
)
{
this
.
testOnReturn
=
testOnReturn
;
}
public
Boolean
getPoolPreparedStatements
()
{
return
poolPreparedStatements
;
}
public
void
setPoolPreparedStatements
(
Boolean
poolPreparedStatements
)
{
this
.
poolPreparedStatements
=
poolPreparedStatements
;
}
public
Integer
getMaxPoolPreparedStatementPerConnectionSize
()
{
return
maxPoolPreparedStatementPerConnectionSize
;
}
public
void
setMaxPoolPreparedStatementPerConnectionSize
(
Integer
maxPoolPreparedStatementPerConnectionSize
)
{
this
.
maxPoolPreparedStatementPerConnectionSize
=
maxPoolPreparedStatementPerConnectionSize
;
}
public
String
getFilters
()
{
return
filters
;
}
public
void
setFilters
(
String
filters
)
{
this
.
filters
=
filters
;
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/config/properties/JwtProperties.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
config
.
properties
;
import
org.springframework.boot.context.properties.ConfigurationProperties
;
import
org.springframework.context.annotation.Configuration
;
/**
* jwt相关配置
*
* @author fengshuonan
* @date 2017-08-23 9:23
*/
@Configuration
@ConfigurationProperties
(
prefix
=
JwtProperties
.
JWT_PREFIX
)
public
class
JwtProperties
{
public
static
final
String
JWT_PREFIX
=
"jwt"
;
private
String
header
=
"Authorization"
;
private
String
secret
=
"defaultSecret"
;
private
Long
expiration
=
604800L
;
private
String
authPath
=
"auth"
;
public
static
String
getJwtPrefix
()
{
return
JWT_PREFIX
;
}
public
String
getHeader
()
{
return
header
;
}
public
void
setHeader
(
String
header
)
{
this
.
header
=
header
;
}
public
String
getSecret
()
{
return
secret
;
}
public
void
setSecret
(
String
secret
)
{
this
.
secret
=
secret
;
}
public
Long
getExpiration
()
{
return
expiration
;
}
public
void
setExpiration
(
Long
expiration
)
{
this
.
expiration
=
expiration
;
}
public
String
getAuthPath
()
{
return
authPath
;
}
public
void
setAuthPath
(
String
authPath
)
{
this
.
authPath
=
authPath
;
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/controller/AuthenticationRestController.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
controller
;
import
com.stylefeng.guns.rest.auth.JwtTokenUtil
;
import
com.stylefeng.guns.rest.config.properties.JwtProperties
;
import
com.stylefeng.guns.rest.service.IReqValidator
;
import
com.stylefeng.guns.rest.transfer.JwtAuthenticationResponse
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.mobile.device.Device
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestParam
;
import
org.springframework.web.bind.annotation.RestController
;
import
javax.annotation.Resource
;
import
javax.servlet.http.HttpServletRequest
;
import
java.util.Map
;
@RestController
public
class
AuthenticationRestController
{
@Autowired
private
JwtProperties
jwtProperties
;
@Autowired
private
JwtTokenUtil
jwtTokenUtil
;
@Resource
(
name
=
"simpleValidator"
)
private
IReqValidator
reqValidator
;
@RequestMapping
(
value
=
"${jwt.auth-path}"
)
public
ResponseEntity
<?>
createAuthenticationToken
(
@RequestParam
Map
<
String
,
Object
>
params
,
Device
device
,
HttpServletRequest
request
)
{
boolean
validate
=
reqValidator
.
validate
(
params
);
if
(
validate
)
{
final
String
token
=
jwtTokenUtil
.
generateToken
((
String
)
params
.
get
(
"userName"
),
device
);
return
ResponseEntity
.
ok
(
new
JwtAuthenticationResponse
(
token
));
}
else
{
return
ResponseEntity
.
status
(
400
).
body
(
"UserName or password is not right!"
);
}
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/persistence/dao/UserMapper.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
persistence
.
dao
;
import
com.stylefeng.guns.rest.persistence.model.User
;
import
com.baomidou.mybatisplus.mapper.BaseMapper
;
/**
* <p>
* Mapper 接口
* </p>
*
* @author stylefeng
* @since 2017-08-23
*/
public
interface
UserMapper
extends
BaseMapper
<
User
>
{
}
\ No newline at end of file
guns-rest/src/main/java/com/stylefeng/guns/rest/persistence/dao/mapping/UserMapper.xml
0 → 100644
View file @
60e05b30
<?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.stylefeng.guns.rest.persistence.dao.UserMapper"
>
<!-- 通用查询映射结果 -->
<resultMap
id=
"BaseResultMap"
type=
"com.stylefeng.guns.rest.persistence.model.User"
>
<id
column=
"id"
property=
"id"
/>
<result
column=
"userName"
property=
"userName"
/>
</resultMap>
</mapper>
guns-rest/src/main/java/com/stylefeng/guns/rest/persistence/model/User.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
persistence
.
model
;
import
java.io.Serializable
;
import
com.baomidou.mybatisplus.activerecord.Model
;
import
java.io.Serializable
;
/**
* <p>
*
* </p>
*
* @author stylefeng
* @since 2017-08-23
*/
public
class
User
extends
Model
<
User
>
{
private
static
final
long
serialVersionUID
=
1L
;
private
Long
id
;
private
String
userName
;
public
Long
getId
()
{
return
id
;
}
public
void
setId
(
Long
id
)
{
this
.
id
=
id
;
}
public
String
getUserName
()
{
return
userName
;
}
public
void
setUserName
(
String
userName
)
{
this
.
userName
=
userName
;
}
@Override
protected
Serializable
pkVal
()
{
return
this
.
id
;
}
@Override
public
String
toString
()
{
return
"User{"
+
"id="
+
id
+
", userName="
+
userName
+
"}"
;
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/service/IReqValidator.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
service
;
import
java.util.Map
;
/**
* <p>验证请求/auth接口时,请求参数的正确性</p>
*
* <p>如果想拓展验证方法只需实现这个接口,然后在AuthenticationRestController类中注意相应实现的本接口的类即可</p>
*
* @author fengshuonan
* @date 2017-08-23 11:48
*/
public
interface
IReqValidator
{
/**
* 通过请求参数验证
*
* @author fengshuonan
* @Date 2017/8/23 11:49
*/
boolean
validate
(
Map
<
String
,
Object
>
params
);
}
guns-rest/src/main/java/com/stylefeng/guns/rest/service/impl/DbValidator.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
service
.
impl
;
import
com.baomidou.mybatisplus.mapper.EntityWrapper
;
import
com.stylefeng.guns.rest.persistence.dao.UserMapper
;
import
com.stylefeng.guns.rest.persistence.model.User
;
import
com.stylefeng.guns.rest.service.IReqValidator
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.stereotype.Service
;
import
java.util.List
;
import
java.util.Map
;
/**
* 账号密码验证
*
* @author fengshuonan
* @date 2017-08-23 12:34
*/
@Service
public
class
DbValidator
implements
IReqValidator
{
@Autowired
UserMapper
userMapper
;
@Override
public
boolean
validate
(
Map
<
String
,
Object
>
params
)
{
List
<
User
>
users
=
userMapper
.
selectList
(
new
EntityWrapper
<
User
>().
eq
(
"userName"
,
params
.
get
(
"userName"
)));
if
(
users
!=
null
&&
users
.
size
()
>
0
){
return
true
;
}
else
{
return
false
;
}
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/service/impl/SimpleValidator.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
service
.
impl
;
import
com.stylefeng.guns.rest.service.IReqValidator
;
import
org.springframework.stereotype.Service
;
import
java.util.Map
;
/**
* 直接验证账号密码是不是admin
*
* @author fengshuonan
* @date 2017-08-23 12:34
*/
@Service
public
class
SimpleValidator
implements
IReqValidator
{
private
static
String
USER_NAME
=
"admin"
;
private
static
String
PASSWORD
=
"admin"
;
@Override
public
boolean
validate
(
Map
<
String
,
Object
>
params
)
{
String
userName
=
(
String
)
params
.
get
(
"userName"
);
String
password
=
(
String
)
params
.
get
(
"password"
);
if
(
USER_NAME
.
equals
(
userName
)
&&
PASSWORD
.
equals
(
password
)){
return
true
;
}
else
{
return
false
;
}
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/transfer/JwtAuthenticationRequest.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
transfer
;
import
java.io.Serializable
;
/**
* Created by stephan on 20.03.16.
*/
public
class
JwtAuthenticationRequest
implements
Serializable
{
private
static
final
long
serialVersionUID
=
-
8445943548965154778L
;
private
String
username
;
private
String
password
;
public
JwtAuthenticationRequest
()
{
super
();
}
public
JwtAuthenticationRequest
(
String
username
,
String
password
)
{
this
.
setUsername
(
username
);
this
.
setPassword
(
password
);
}
public
String
getUsername
()
{
return
this
.
username
;
}
public
void
setUsername
(
String
username
)
{
this
.
username
=
username
;
}
public
String
getPassword
()
{
return
this
.
password
;
}
public
void
setPassword
(
String
password
)
{
this
.
password
=
password
;
}
}
guns-rest/src/main/java/com/stylefeng/guns/rest/transfer/JwtAuthenticationResponse.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
rest
.
transfer
;
import
java.io.Serializable
;
/**
* Created by stephan on 20.03.16.
*/
public
class
JwtAuthenticationResponse
implements
Serializable
{
private
static
final
long
serialVersionUID
=
1250166508152483573L
;
private
final
String
token
;
public
JwtAuthenticationResponse
(
String
token
)
{
this
.
token
=
token
;
}
public
String
getToken
()
{
return
this
.
token
;
}
}
guns-rest/src/main/resources/application.properties
deleted
100644 → 0
View file @
d7d33e13
guns-rest/src/main/resources/application.yml
0 → 100644
View file @
60e05b30
jwt
:
header
:
Authorization
#http请求头部需要带的标识
secret
:
mySecret
#jwt秘钥
expiration
:
604800
#7天 单位:秒
auth-path
:
auth
#认证请求的路径
mybatis-plus
:
mapper-locations
:
classpath*:com/stylefeng/guns/rest/**/mapping/*.xml
typeAliasesPackage
:
com.stylefeng.guns.rest.persistence.model
global-config
:
id-type
:
0
#0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid)
db-column-underline
:
false
refresh-mapper
:
true
configuration
:
map-underscore-to-camel-case
:
false
cache-enabled
:
true
#配置的缓存的全局开关
lazyLoadingEnabled
:
true
#延时加载的开关
multipleResultSetsEnabled
:
true
#开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句,调试用
spring
:
datasource
:
url
:
jdbc:mysql://127.0.0.1:3306/rest?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
username
:
root
password
:
root
filters
:
log4j,wall,mergeStat
logging
:
level.root
:
info
level.com.stylefeng
:
debug
path
:
logs/
file
:
guns-rest.log
\ No newline at end of file
guns-rest/src/test/java/com/stylefeng/guns/generator/EntityGenerator.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
generator
;
import
com.baomidou.mybatisplus.generator.AutoGenerator
;
import
com.baomidou.mybatisplus.generator.InjectionConfig
;
import
com.baomidou.mybatisplus.generator.config.DataSourceConfig
;
import
com.baomidou.mybatisplus.generator.config.GlobalConfig
;
import
com.baomidou.mybatisplus.generator.config.PackageConfig
;
import
com.baomidou.mybatisplus.generator.config.StrategyConfig
;
import
com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert
;
import
com.baomidou.mybatisplus.generator.config.rules.DbColumnType
;
import
com.baomidou.mybatisplus.generator.config.rules.DbType
;
import
com.baomidou.mybatisplus.generator.config.rules.NamingStrategy
;
import
org.junit.Test
;
import
java.util.HashMap
;
import
java.util.Map
;
/**
* 实体生成
*
* @author fengshuonan
* @date 2017-08-23 12:15
*/
public
class
EntityGenerator
{
@Test
public
void
entityGenerator
()
{
AutoGenerator
mpg
=
new
AutoGenerator
();
// 全局配置
GlobalConfig
gc
=
new
GlobalConfig
();
gc
.
setOutputDir
(
"D:\\tmp\\guns\\guns-rest\\src\\main\\java"
);
//这里写你自己的java目录
gc
.
setFileOverride
(
true
);
//是否覆盖
gc
.
setActiveRecord
(
true
);
gc
.
setEnableCache
(
false
);
// XML 二级缓存
gc
.
setBaseResultMap
(
true
);
// XML ResultMap
gc
.
setBaseColumnList
(
false
);
// XML columList
gc
.
setAuthor
(
"stylefeng"
);
mpg
.
setGlobalConfig
(
gc
);
// 数据源配置
DataSourceConfig
dsc
=
new
DataSourceConfig
();
dsc
.
setDbType
(
DbType
.
MYSQL
);
dsc
.
setTypeConvert
(
new
MySqlTypeConvert
()
{
// 自定义数据库表字段类型转换【可选】
@Override
public
DbColumnType
processTypeConvert
(
String
fieldType
)
{
return
super
.
processTypeConvert
(
fieldType
);
}
});
dsc
.
setDriverName
(
"com.mysql.jdbc.Driver"
);
dsc
.
setUsername
(
"root"
);
dsc
.
setPassword
(
"root"
);
dsc
.
setUrl
(
"jdbc:mysql://127.0.0.1:3306/rest?characterEncoding=utf8"
);
mpg
.
setDataSource
(
dsc
);
// 策略配置
StrategyConfig
strategy
=
new
StrategyConfig
();
//strategy.setTablePrefix(new String[]{"_"});// 此处可以修改为您的表前缀
strategy
.
setNaming
(
NamingStrategy
.
underline_to_camel
);
// 表名生成策略
strategy
.
setInclude
(
new
String
[]{
"user"
});
mpg
.
setStrategy
(
strategy
);
// 包配置
PackageConfig
pc
=
new
PackageConfig
();
pc
.
setParent
(
null
);
pc
.
setEntity
(
"com.stylefeng.guns.rest.persistence.model"
);
pc
.
setMapper
(
"com.stylefeng.guns.rest.persistence.dao"
);
pc
.
setXml
(
"com.stylefeng.guns.rest.persistence.dao.mapping"
);
pc
.
setService
(
"TTT"
);
//本项目没用,生成之后删掉
pc
.
setServiceImpl
(
"TTT"
);
//本项目没用,生成之后删掉
pc
.
setController
(
"TTT"
);
//本项目没用,生成之后删掉
mpg
.
setPackageInfo
(
pc
);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
InjectionConfig
cfg
=
new
InjectionConfig
()
{
@Override
public
void
initMap
()
{
Map
<
String
,
Object
>
map
=
new
HashMap
<>();
map
.
put
(
"abc"
,
this
.
getConfig
().
getGlobalConfig
().
getAuthor
()
+
"-mp"
);
this
.
setMap
(
map
);
}
};
mpg
.
setCfg
(
cfg
);
// 执行生成
mpg
.
execute
();
// 打印注入设置
System
.
err
.
println
(
mpg
.
getCfg
().
getMap
().
get
(
"abc"
));
}
}
guns-rest/src/test/java/com/stylefeng/guns/jwt/DecryptTest.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
jwt
;
import
io.jsonwebtoken.Jwts
;
/**
* jwt测试
*
* @author fengshuonan
* @date 2017-08-21 16:34
*/
public
class
DecryptTest
{
public
static
void
main
(
String
[]
args
)
{
String
key
=
"mySecret"
;
String
compactJws
=
"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZCI6IndlYiIsImV4cCI6MTUwNDA3NDg1OCwiaWF0IjoxNTAzNDcwMDU4fQ.S6eOFPkDl77sg9mwhgkQZ37504OaYFTZs4pMb2FuG-UKbimTsiOAU_gQhqfOfBOIho8Ab4C1fnIN-4z-Ie8V8g"
;
System
.
out
.
println
(
"body = "
+
Jwts
.
parser
().
setSigningKey
(
key
).
parseClaimsJws
(
compactJws
).
getBody
());
System
.
out
.
println
(
"header = "
+
Jwts
.
parser
().
setSigningKey
(
key
).
parseClaimsJws
(
compactJws
).
getHeader
());
System
.
out
.
println
(
"signature = "
+
Jwts
.
parser
().
setSigningKey
(
key
).
parseClaimsJws
(
compactJws
).
getSignature
());
}
}
guns-rest/src/test/java/com/stylefeng/guns/jwt/JWTTest.java
0 → 100644
View file @
60e05b30
package
com
.
stylefeng
.
guns
.
jwt
;
import
com.stylefeng.guns.core.util.IdGenerator
;
import
io.jsonwebtoken.*
;
import
io.jsonwebtoken.impl.DefaultClaims
;
import
io.jsonwebtoken.impl.crypto.MacProvider
;
import
java.security.Key
;
/**
* jwt测试
*
* @author fengshuonan
* @date 2017-08-21 16:34
*/
public
class
JWTTest
{
public
static
void
main
(
String
[]
args
)
{
Key
key
=
MacProvider
.
generateKey
();
String
compactJws
=
Jwts
.
builder
()
.
setSubject
(
"Joe"
)
.
setClaims
(
new
DefaultClaims
().
setId
(
IdGenerator
.
getId
()))
.
signWith
(
SignatureAlgorithm
.
HS512
,
key
)
.
compact
();
System
.
out
.
println
(
compactJws
);
assert
Jwts
.
parser
().
setSigningKey
(
key
).
parseClaimsJws
(
compactJws
).
getBody
().
getSubject
().
equals
(
"Joe"
);
try
{
Claims
body
=
Jwts
.
parser
().
setSigningKey
(
key
).
parseClaimsJws
(
compactJws
).
getBody
();
System
.
out
.
println
(
body
);
System
.
out
.
println
(
body
.
getExpiration
());
System
.
out
.
println
(
"trust"
);
}
catch
(
SignatureException
e
)
{
System
.
out
.
println
(
"not trust"
);
}
catch
(
ExpiredJwtException
e
)
{
System
.
out
.
println
(
"ExpiredJwtException"
);
}
}
}
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