Skip to content
项目
群组
代码片段
帮助
正在加载...
帮助
为 GitLab 提交贡献
登录/注册
切换导航
A
Afrishop refactored project
项目
项目
详情
活动
周期分析
仓库
仓库
文件
提交
分支
标签
贡献者
分枝图
比较
统计图
议题
0
议题
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
CI / CD
CI / CD
流水线
作业
计划
统计图
Wiki
Wiki
代码片段
代码片段
成员
成员
折叠边栏
关闭边栏
活动
分枝图
统计图
创建新议题
作业
提交
议题看板
打开侧边栏
Whispa
Afrishop refactored project
Commits
6d32c460
提交
6d32c460
authored
9月 02, 2020
作者:
Whispa
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
third commit
上级
cf3c9bd4
显示空白字符变更
内嵌
并排
正在显示
23 个修改的文件
包含
906 行增加
和
16 行删除
+906
-16
pom.xml
pom.xml
+16
-0
SecurityConfiguration.java
...com/example/afrishop_v3/config/SecurityConfiguration.java
+0
-16
AuthController.java
...a/com/example/afrishop_v3/controllers/AuthController.java
+102
-0
FeedbackController.java
...m/example/afrishop_v3/controllers/FeedbackController.java
+30
-0
SearchController.java
...com/example/afrishop_v3/controllers/SearchController.java
+2
-0
TbCfFeedback.java
...ain/java/com/example/afrishop_v3/models/TbCfFeedback.java
+126
-0
TbCfFeedbackRecord.java
...va/com/example/afrishop_v3/models/TbCfFeedbackRecord.java
+109
-0
TbCfUserInfo.java
...ain/java/com/example/afrishop_v3/models/TbCfUserInfo.java
+8
-0
LoginRequest.java
...com/example/afrishop_v3/payload/request/LoginRequest.java
+24
-0
JwtResponse.java
...com/example/afrishop_v3/payload/response/JwtResponse.java
+64
-0
MessageResponse.java
...example/afrishop_v3/payload/response/MessageResponse.java
+17
-0
TbCfFeedbackRecordRepository.java
.../afrishop_v3/repository/TbCfFeedbackRecordRepository.java
+7
-0
TbCfFeedbackRepository.java
...xample/afrishop_v3/repository/TbCfFeedbackRepository.java
+7
-0
UserRepository.java
...va/com/example/afrishop_v3/repository/UserRepository.java
+11
-0
WebSecurityConfig.java
...a/com/example/afrishop_v3/security/WebSecurityConfig.java
+67
-0
AuthEntryPointJwt.java
...m/example/afrishop_v3/security/jwt/AuthEntryPointJwt.java
+27
-0
AuthTokenFilter.java
...com/example/afrishop_v3/security/jwt/AuthTokenFilter.java
+62
-0
JwtUtils.java
...n/java/com/example/afrishop_v3/security/jwt/JwtUtils.java
+58
-0
AuthenticationUser.java
...ple/afrishop_v3/security/services/AuthenticationUser.java
+26
-0
IAuthenticationFacade.java
.../afrishop_v3/security/services/IAuthenticationFacade.java
+7
-0
UserDetailsImpl.java
...xample/afrishop_v3/security/services/UserDetailsImpl.java
+103
-0
UserDetailsServiceImpl.java
...afrishop_v3/security/services/UserDetailsServiceImpl.java
+29
-0
application.properties
src/main/resources/application.properties
+4
-0
没有找到文件。
pom.xml
浏览文件 @
6d32c460
...
...
@@ -27,6 +27,22 @@
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-data-jpa
</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
<dependency>
<groupId>
org.springframework.security.oauth
</groupId>
<artifactId>
spring-security-oauth2
</artifactId>
<version>
2.1.0.RELEASE
</version>
</dependency>
<dependency>
<groupId>
org.springframework.security
</groupId>
<artifactId>
spring-security-test
</artifactId>
<scope>
test
</scope>
</dependency>
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt
</artifactId>
<version>
0.9.1
</version>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-oauth2-client
</artifactId>
...
...
src/main/java/com/example/afrishop_v3/config/SecurityConfiguration.java
deleted
100644 → 0
浏览文件 @
cf3c9bd4
package
com
.
example
.
afrishop_v3
.
config
;
import
org.springframework.context.annotation.Configuration
;
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.configuration.WebSecurityConfigurerAdapter
;
@Configuration
@EnableWebSecurity
public
class
SecurityConfiguration
extends
WebSecurityConfigurerAdapter
{
@Override
protected
void
configure
(
HttpSecurity
http
)
throws
Exception
{
http
.
authorizeRequests
().
antMatchers
(
"/"
).
permitAll
();
http
.
csrf
().
disable
().
authorizeRequests
().
anyRequest
().
permitAll
();
}
}
src/main/java/com/example/afrishop_v3/controllers/AuthController.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
controllers
;
import
com.example.afrishop_v3.base.Result
;
import
com.example.afrishop_v3.enums.ResultCodeEnum
;
import
com.example.afrishop_v3.models.TbCfUserInfo
;
import
com.example.afrishop_v3.payload.request.LoginRequest
;
import
com.example.afrishop_v3.payload.response.JwtResponse
;
import
com.example.afrishop_v3.payload.response.MessageResponse
;
import
com.example.afrishop_v3.repository.UserRepository
;
import
com.example.afrishop_v3.security.jwt.JwtUtils
;
import
com.example.afrishop_v3.security.services.UserDetailsImpl
;
import
com.example.afrishop_v3.util.IdUtil
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.security.authentication.AuthenticationManager
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.security.core.GrantedAuthority
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
;
import
org.springframework.security.crypto.password.PasswordEncoder
;
import
org.springframework.web.bind.annotation.*
;
import
java.util.Collection
;
import
java.util.List
;
import
java.util.Optional
;
import
java.util.stream.Collectors
;
@CrossOrigin
(
origins
=
"*"
,
maxAge
=
3600
)
@RestController
@RequestMapping
(
"/api/auth"
)
public
class
AuthController
{
private
final
AuthenticationManager
authenticationManager
;
private
final
UserRepository
userRepository
;
private
final
PasswordEncoder
encoder
;
private
final
JwtUtils
jwtUtils
;
public
AuthController
(
AuthenticationManager
authenticationManager
,
UserRepository
userRepository
,
PasswordEncoder
encoder
,
JwtUtils
jwtUtils
)
{
this
.
authenticationManager
=
authenticationManager
;
this
.
userRepository
=
userRepository
;
this
.
encoder
=
encoder
;
this
.
jwtUtils
=
jwtUtils
;
}
@PostMapping
(
"/signin"
)
public
ResponseEntity
<
Result
>
authenticateUser
(
@RequestBody
LoginRequest
loginRequest
)
{
Optional
<
TbCfUserInfo
>
byAccount
=
userRepository
.
findByAccount
(
loginRequest
.
getAccount
());
if
(
!
byAccount
.
isPresent
()
){
return
ResponseEntity
.
ok
(
new
Result
<>(
ResultCodeEnum
.
VALIDATE_ERROR
,
"User not found"
));
}
Authentication
authentication
=
authenticationManager
.
authenticate
(
new
UsernamePasswordAuthenticationToken
(
loginRequest
.
getAccount
(),
loginRequest
.
getPassword
()));
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
String
jwt
=
jwtUtils
.
generateJwtToken
(
authentication
);
UserDetailsImpl
userDetails
=
(
UserDetailsImpl
)
authentication
.
getPrincipal
();
List
<
String
>
roles
=
userDetails
.
getAuthorities
().
stream
()
.
map
(
GrantedAuthority:
:
getAuthority
)
.
collect
(
Collectors
.
toList
());
return
ResponseEntity
.
ok
(
new
Result
<>(
new
JwtResponse
(
jwt
,
userDetails
.
getId
(),
userDetails
.
getUsername
(),
userDetails
.
getEmail
(),
roles
)));
}
@PostMapping
(
"/signup"
)
public
ResponseEntity
<?>
registerUser
(
@RequestBody
TbCfUserInfo
signUpRequest
)
{
Optional
<
TbCfUserInfo
>
byAccount
=
userRepository
.
findByAccount
(
signUpRequest
.
getAccount
());
if
(
byAccount
.
isPresent
()
)
{
return
ResponseEntity
.
badRequest
()
.
body
(
new
MessageResponse
(
"Error: Username is already taken!"
));
}
Optional
<
TbCfUserInfo
>
byEmail
=
userRepository
.
findFirstByEmail
(
signUpRequest
.
getEmail
());
if
(
byEmail
.
isPresent
()
)
{
return
ResponseEntity
.
badRequest
()
.
body
(
new
MessageResponse
(
"Error: Email is already in use!"
));
}
signUpRequest
.
setUserId
(
IdUtil
.
createIdbyUUID
());
signUpRequest
.
setPassword
(
encoder
.
encode
(
signUpRequest
.
getPassword
()));
TbCfUserInfo
userInfo
=
userRepository
.
save
(
signUpRequest
);
return
ResponseEntity
.
ok
(
new
Result
<>(
userInfo
,
"User createdSuccessfully"
));
}
}
src/main/java/com/example/afrishop_v3/controllers/FeedbackController.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
controllers
;
import
com.example.afrishop_v3.base.Result
;
import
com.example.afrishop_v3.models.TbCfFeedback
;
import
com.example.afrishop_v3.repository.TbCfFeedbackRepository
;
import
com.example.afrishop_v3.security.services.AuthenticationUser
;
import
com.example.afrishop_v3.util.IdUtil
;
import
org.springframework.web.bind.annotation.*
;
@RestController
@RequestMapping
(
"/feedback"
)
public
class
FeedbackController
{
private
final
TbCfFeedbackRepository
repository
;
public
FeedbackController
(
TbCfFeedbackRepository
repository
)
{
this
.
repository
=
repository
;
}
@PostMapping
public
Result
saveFeedbackList
(
@RequestBody
TbCfFeedback
feedback
)
{
feedback
.
setFeedbackId
(
IdUtil
.
createIdbyUUID
());
return
new
Result
<>(
repository
.
save
(
feedback
));
}
@GetMapping
public
Result
getFeedbackList
()
{
return
new
Result
<>(
repository
.
findAll
());
}
}
src/main/java/com/example/afrishop_v3/controllers/SearchController.java
浏览文件 @
6d32c460
...
...
@@ -5,12 +5,14 @@ import com.example.afrishop_v3.enums.ResultCodeEnum;
import
com.example.afrishop_v3.models.TbCfSearch
;
import
com.example.afrishop_v3.repository.TbCfSearchRepository
;
import
com.example.afrishop_v3.util.IdUtil
;
import
org.springframework.security.access.prepost.PreAuthorize
;
import
org.springframework.web.bind.annotation.*
;
import
java.util.List
;
@RestController
@RequestMapping
(
"/search"
)
@PreAuthorize
(
"hasRole('user')"
)
public
class
SearchController
{
private
final
TbCfSearchRepository
repository
;
...
...
src/main/java/com/example/afrishop_v3/models/TbCfFeedback.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
models
;
import
lombok.Getter
;
import
lombok.Setter
;
import
javax.persistence.Entity
;
import
javax.persistence.Id
;
import
java.util.Date
;
/**
* 反馈问题列表实体
* 表名 tb_cf_feedback
*
* @author lipengjun
* @date 2019-09-21 15:15:23
*/
@Entity
@Getter
@Setter
public
class
TbCfFeedback
{
/**
* 反馈问题id
*/
@Id
private
String
feedbackId
;
/**
* 问题
*/
private
String
question
;
/**
* 是否展示,1展示,0不展示
*/
private
Integer
enableFlag
;
/**
* 创建时间
*/
private
Date
createTime
;
/**
* 反馈问题类型,1为填写类型
*/
private
Integer
questionType
;
/**
* 排序,数字,倒序
*/
private
Integer
sort
;
/**
* 设置:反馈问题id
*/
public
void
setFeedbackId
(
String
feedbackId
)
{
this
.
feedbackId
=
feedbackId
;
}
/**
* 获取:反馈问题id
*/
public
String
getFeedbackId
()
{
return
feedbackId
;
}
/**
* 设置:问题
*/
public
void
setQuestion
(
String
question
)
{
this
.
question
=
question
;
}
/**
* 获取:问题
*/
public
String
getQuestion
()
{
return
question
;
}
/**
* 设置:是否展示,1展示,0不展示
*/
public
void
setEnableFlag
(
Integer
enableFlag
)
{
this
.
enableFlag
=
enableFlag
;
}
/**
* 获取:是否展示,1展示,0不展示
*/
public
Integer
getEnableFlag
()
{
return
enableFlag
;
}
/**
* 设置:创建时间
*/
public
void
setCreateTime
(
Date
createTime
)
{
this
.
createTime
=
createTime
;
}
/**
* 获取:创建时间
*/
public
Date
getCreateTime
()
{
return
createTime
;
}
/**
* 设置:反馈问题类型,1为填写类型
*/
public
void
setQuestionType
(
Integer
questionType
)
{
this
.
questionType
=
questionType
;
}
/**
* 获取:反馈问题类型,1为填写类型
*/
public
Integer
getQuestionType
()
{
return
questionType
;
}
/**
* 设置:排序,数字,倒序
*/
public
void
setSort
(
Integer
sort
)
{
this
.
sort
=
sort
;
}
/**
* 获取:排序,数字,倒序
*/
public
Integer
getSort
()
{
return
sort
;
}
}
src/main/java/com/example/afrishop_v3/models/TbCfFeedbackRecord.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
models
;
import
lombok.Getter
;
import
lombok.Setter
;
import
javax.persistence.Entity
;
import
javax.persistence.Id
;
import
java.util.Date
;
/**
* 用户反馈记录表实体
* 表名 tb_cf_feedback_record
*
* @author lipengjun
* @date 2019-09-21 15:15:23
*/
@Entity
@Getter
@Setter
public
class
TbCfFeedbackRecord
{
/**
* 反馈记录id
*/
@Id
private
String
recordId
;
/**
* 反馈用户id
*/
private
String
userId
;
/**
* 反馈问题id
*/
private
String
feedbackId
;
/**
* 反馈填写内容
*/
private
String
answer
;
/**
* 创建时间
*/
private
Date
createTime
;
/**
* 设置:反馈记录id
*/
public
void
setRecordId
(
String
recordId
)
{
this
.
recordId
=
recordId
;
}
/**
* 获取:反馈记录id
*/
public
String
getRecordId
()
{
return
recordId
;
}
/**
* 设置:反馈用户id
*/
public
void
setUserId
(
String
userId
)
{
this
.
userId
=
userId
;
}
/**
* 获取:反馈用户id
*/
public
String
getUserId
()
{
return
userId
;
}
/**
* 设置:反馈问题id
*/
public
void
setFeedbackId
(
String
feedbackId
)
{
this
.
feedbackId
=
feedbackId
;
}
/**
* 获取:反馈问题id
*/
public
String
getFeedbackId
()
{
return
feedbackId
;
}
/**
* 设置:反馈填写内容
*/
public
void
setAnswer
(
String
answer
)
{
this
.
answer
=
answer
;
}
/**
* 获取:反馈填写内容
*/
public
String
getAnswer
()
{
return
answer
;
}
/**
* 设置:创建时间
*/
public
void
setCreateTime
(
Date
createTime
)
{
this
.
createTime
=
createTime
;
}
/**
* 获取:创建时间
*/
public
Date
getCreateTime
()
{
return
createTime
;
}
}
src/main/java/com/example/afrishop_v3/models/TbCfUserInfo.java
浏览文件 @
6d32c460
...
...
@@ -6,6 +6,8 @@ import lombok.Setter;
import
javax.persistence.Entity
;
import
javax.persistence.Id
;
import
java.io.Serializable
;
import
java.util.ArrayList
;
import
java.util.Collection
;
import
java.util.Date
;
/**
...
...
@@ -428,4 +430,10 @@ public class TbCfUserInfo {
public
Integer
getIsSend
()
{
return
isSend
;
}
public
Collection
<
String
>
getRoles
()
{
ArrayList
<
String
>
objects
=
new
ArrayList
<>();
objects
.
add
(
"user"
);
return
objects
;
}
}
src/main/java/com/example/afrishop_v3/payload/request/LoginRequest.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
payload
.
request
;
public
class
LoginRequest
{
private
String
account
;
private
String
password
;
public
String
getAccount
()
{
return
account
;
}
public
void
setAccount
(
String
account
)
{
this
.
account
=
account
;
}
public
String
getPassword
()
{
return
password
;
}
public
void
setPassword
(
String
password
)
{
this
.
password
=
password
;
}
}
src/main/java/com/example/afrishop_v3/payload/response/JwtResponse.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
payload
.
response
;
import
java.util.List
;
public
class
JwtResponse
{
private
String
token
;
private
String
type
=
"Bearer"
;
private
String
id
;
private
String
username
;
private
String
email
;
private
List
<
String
>
roles
;
public
JwtResponse
(
String
accessToken
,
String
id
,
String
username
,
String
email
,
List
<
String
>
roles
)
{
this
.
token
=
accessToken
;
this
.
id
=
id
;
this
.
username
=
username
;
this
.
email
=
email
;
this
.
roles
=
roles
;
}
public
String
getAccessToken
()
{
return
token
;
}
public
void
setAccessToken
(
String
accessToken
)
{
this
.
token
=
accessToken
;
}
public
String
getTokenType
()
{
return
type
;
}
public
void
setTokenType
(
String
tokenType
)
{
this
.
type
=
tokenType
;
}
public
String
getId
()
{
return
id
;
}
public
void
setId
(
String
id
)
{
this
.
id
=
id
;
}
public
String
getEmail
()
{
return
email
;
}
public
void
setEmail
(
String
email
)
{
this
.
email
=
email
;
}
public
String
getUsername
()
{
return
username
;
}
public
void
setUsername
(
String
username
)
{
this
.
username
=
username
;
}
public
List
<
String
>
getRoles
()
{
return
roles
;
}
}
src/main/java/com/example/afrishop_v3/payload/response/MessageResponse.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
payload
.
response
;
public
class
MessageResponse
{
private
String
message
;
public
MessageResponse
(
String
message
)
{
this
.
message
=
message
;
}
public
String
getMessage
()
{
return
message
;
}
public
void
setMessage
(
String
message
)
{
this
.
message
=
message
;
}
}
src/main/java/com/example/afrishop_v3/repository/TbCfFeedbackRecordRepository.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
repository
;
import
com.example.afrishop_v3.models.TbCfFeedbackRecord
;
import
org.springframework.data.repository.PagingAndSortingRepository
;
public
interface
TbCfFeedbackRecordRepository
extends
PagingAndSortingRepository
<
TbCfFeedbackRecord
,
String
>
{
}
src/main/java/com/example/afrishop_v3/repository/TbCfFeedbackRepository.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
repository
;
import
com.example.afrishop_v3.models.TbCfFeedback
;
import
org.springframework.data.repository.PagingAndSortingRepository
;
public
interface
TbCfFeedbackRepository
extends
PagingAndSortingRepository
<
TbCfFeedback
,
String
>
{
}
src/main/java/com/example/afrishop_v3/repository/UserRepository.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
repository
;
import
com.example.afrishop_v3.models.TbCfUserInfo
;
import
org.springframework.data.repository.PagingAndSortingRepository
;
import
java.util.Optional
;
public
interface
UserRepository
extends
PagingAndSortingRepository
<
TbCfUserInfo
,
String
>
{
Optional
<
TbCfUserInfo
>
findByAccount
(
String
s
);
Optional
<
TbCfUserInfo
>
findFirstByEmail
(
String
s
);
}
src/main/java/com/example/afrishop_v3/security/WebSecurityConfig.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
security
;
import
com.example.afrishop_v3.security.jwt.AuthEntryPointJwt
;
import
com.example.afrishop_v3.security.jwt.AuthTokenFilter
;
import
com.example.afrishop_v3.security.services.UserDetailsServiceImpl
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.security.authentication.AuthenticationManager
;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
;
import
org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
;
import
org.springframework.security.config.http.SessionCreationPolicy
;
import
org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
;
import
org.springframework.security.crypto.password.PasswordEncoder
;
import
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
(
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled
=
true
)
public
class
WebSecurityConfig
extends
WebSecurityConfigurerAdapter
{
@Autowired
UserDetailsServiceImpl
userDetailsService
;
@Autowired
private
AuthEntryPointJwt
unauthorizedHandler
;
@Bean
public
AuthTokenFilter
authenticationJwtTokenFilter
()
{
return
new
AuthTokenFilter
();
}
@Override
public
void
configure
(
AuthenticationManagerBuilder
authenticationManagerBuilder
)
throws
Exception
{
authenticationManagerBuilder
.
userDetailsService
(
userDetailsService
).
passwordEncoder
(
passwordEncoder
());
}
@Bean
@Override
public
AuthenticationManager
authenticationManagerBean
()
throws
Exception
{
return
super
.
authenticationManagerBean
();
}
@Bean
public
PasswordEncoder
passwordEncoder
()
{
return
new
BCryptPasswordEncoder
();
}
@Override
protected
void
configure
(
HttpSecurity
http
)
throws
Exception
{
http
.
cors
().
and
().
csrf
().
disable
()
.
exceptionHandling
().
authenticationEntryPoint
(
unauthorizedHandler
).
and
()
.
sessionManagement
().
sessionCreationPolicy
(
SessionCreationPolicy
.
STATELESS
).
and
()
.
authorizeRequests
().
antMatchers
(
"/api/auth/**"
).
permitAll
()
.
antMatchers
(
"/api/test/**"
).
permitAll
()
.
anyRequest
().
authenticated
();
http
.
addFilterBefore
(
authenticationJwtTokenFilter
(),
UsernamePasswordAuthenticationFilter
.
class
);
}
}
src/main/java/com/example/afrishop_v3/security/jwt/AuthEntryPointJwt.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
security
.
jwt
;
import
java.io.IOException
;
import
javax.servlet.ServletException
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.security.core.AuthenticationException
;
import
org.springframework.security.web.AuthenticationEntryPoint
;
import
org.springframework.stereotype.Component
;
@Component
public
class
AuthEntryPointJwt
implements
AuthenticationEntryPoint
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
AuthEntryPointJwt
.
class
);
@Override
public
void
commence
(
HttpServletRequest
request
,
HttpServletResponse
response
,
AuthenticationException
authException
)
throws
IOException
,
ServletException
{
logger
.
error
(
"Unauthorized error: {}"
,
authException
.
getMessage
());
response
.
sendError
(
HttpServletResponse
.
SC_UNAUTHORIZED
,
"Error: Unauthorized"
);
}
}
src/main/java/com/example/afrishop_v3/security/jwt/AuthTokenFilter.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
security
.
jwt
;
import
java.io.IOException
;
import
javax.servlet.FilterChain
;
import
javax.servlet.ServletException
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
com.example.afrishop_v3.security.services.UserDetailsServiceImpl
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.web.authentication.WebAuthenticationDetailsSource
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.filter.OncePerRequestFilter
;
public
class
AuthTokenFilter
extends
OncePerRequestFilter
{
@Autowired
private
JwtUtils
jwtUtils
;
@Autowired
private
UserDetailsServiceImpl
userDetailsService
;
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
AuthTokenFilter
.
class
);
@Override
protected
void
doFilterInternal
(
HttpServletRequest
request
,
HttpServletResponse
response
,
FilterChain
filterChain
)
throws
ServletException
,
IOException
{
try
{
String
jwt
=
parseJwt
(
request
);
if
(
jwt
!=
null
&&
jwtUtils
.
validateJwtToken
(
jwt
))
{
String
username
=
jwtUtils
.
getUserNameFromJwtToken
(
jwt
);
UserDetails
userDetails
=
userDetailsService
.
loadUserByUsername
(
username
);
UsernamePasswordAuthenticationToken
authentication
=
new
UsernamePasswordAuthenticationToken
(
userDetails
,
null
,
userDetails
.
getAuthorities
());
authentication
.
setDetails
(
new
WebAuthenticationDetailsSource
().
buildDetails
(
request
));
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
}
}
catch
(
Exception
e
)
{
logger
.
error
(
"Cannot set user authentication: {}"
,
e
);
}
filterChain
.
doFilter
(
request
,
response
);
}
private
String
parseJwt
(
HttpServletRequest
request
)
{
String
headerAuth
=
request
.
getHeader
(
"Authorization"
);
if
(
StringUtils
.
hasText
(
headerAuth
)
&&
headerAuth
.
startsWith
(
"Bearer "
))
{
return
headerAuth
.
substring
(
7
,
headerAuth
.
length
());
}
return
null
;
}
}
src/main/java/com/example/afrishop_v3/security/jwt/JwtUtils.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
security
.
jwt
;
import
java.util.Date
;
import
com.example.afrishop_v3.security.services.UserDetailsImpl
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.stereotype.Component
;
import
io.jsonwebtoken.*
;
@Component
public
class
JwtUtils
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
JwtUtils
.
class
);
@Value
(
"${bezkoder.app.jwtSecret}"
)
private
String
jwtSecret
;
@Value
(
"${bezkoder.app.jwtExpirationMs}"
)
private
int
jwtExpirationMs
;
public
String
generateJwtToken
(
Authentication
authentication
)
{
UserDetailsImpl
userPrincipal
=
(
UserDetailsImpl
)
authentication
.
getPrincipal
();
return
Jwts
.
builder
()
.
setSubject
((
userPrincipal
.
getUsername
()))
.
setIssuedAt
(
new
Date
())
.
setExpiration
(
new
Date
((
new
Date
()).
getTime
()
+
jwtExpirationMs
))
.
signWith
(
SignatureAlgorithm
.
HS512
,
jwtSecret
)
.
compact
();
}
public
String
getUserNameFromJwtToken
(
String
token
)
{
return
Jwts
.
parser
().
setSigningKey
(
jwtSecret
).
parseClaimsJws
(
token
).
getBody
().
getSubject
();
}
public
boolean
validateJwtToken
(
String
authToken
)
{
try
{
Jwts
.
parser
().
setSigningKey
(
jwtSecret
).
parseClaimsJws
(
authToken
);
return
true
;
}
catch
(
SignatureException
e
)
{
logger
.
error
(
"Invalid JWT signature: {}"
,
e
.
getMessage
());
}
catch
(
MalformedJwtException
e
)
{
logger
.
error
(
"Invalid JWT token: {}"
,
e
.
getMessage
());
}
catch
(
ExpiredJwtException
e
)
{
logger
.
error
(
"JWT token is expired: {}"
,
e
.
getMessage
());
}
catch
(
UnsupportedJwtException
e
)
{
logger
.
error
(
"JWT token is unsupported: {}"
,
e
.
getMessage
());
}
catch
(
IllegalArgumentException
e
)
{
logger
.
error
(
"JWT claims string is empty: {}"
,
e
.
getMessage
());
}
return
false
;
}
}
src/main/java/com/example/afrishop_v3/security/services/AuthenticationUser.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
security
.
services
;
import
com.example.afrishop_v3.models.TbCfUserInfo
;
import
com.example.afrishop_v3.repository.UserRepository
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.stereotype.Component
;
@Component
public
class
AuthenticationUser
implements
IAuthenticationFacade
{
private
final
UserRepository
repository
;
public
AuthenticationUser
(
UserRepository
repository
)
{
this
.
repository
=
repository
;
}
@Override
public
Authentication
getAuthentication
()
{
return
SecurityContextHolder
.
getContext
().
getAuthentication
();
}
public
TbCfUserInfo
userInfo
(){
return
repository
.
findByAccount
(
getAuthentication
().
getName
()).
orElseGet
(
null
);
}
}
src/main/java/com/example/afrishop_v3/security/services/IAuthenticationFacade.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
security
.
services
;
import
org.springframework.security.core.Authentication
;
interface
IAuthenticationFacade
{
Authentication
getAuthentication
();
}
src/main/java/com/example/afrishop_v3/security/services/UserDetailsImpl.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
security
.
services
;
import
java.util.Collection
;
import
java.util.List
;
import
java.util.Objects
;
import
java.util.stream.Collectors
;
import
com.example.afrishop_v3.models.TbCfUserInfo
;
import
org.springframework.security.core.GrantedAuthority
;
import
org.springframework.security.core.authority.SimpleGrantedAuthority
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
com.fasterxml.jackson.annotation.JsonIgnore
;
public
class
UserDetailsImpl
implements
UserDetails
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
id
;
private
String
username
;
private
String
email
;
@JsonIgnore
private
String
password
;
private
Collection
<?
extends
GrantedAuthority
>
authorities
;
public
UserDetailsImpl
(
String
id
,
String
username
,
String
email
,
String
password
,
Collection
<?
extends
GrantedAuthority
>
authorities
)
{
this
.
id
=
id
;
this
.
username
=
username
;
this
.
email
=
email
;
this
.
password
=
password
;
this
.
authorities
=
authorities
;
}
public
static
UserDetailsImpl
build
(
TbCfUserInfo
user
)
{
List
<
GrantedAuthority
>
authorities
=
user
.
getRoles
().
stream
()
.
map
(
SimpleGrantedAuthority:
:
new
)
.
collect
(
Collectors
.
toList
());
return
new
UserDetailsImpl
(
user
.
getUserId
(),
user
.
getAccount
(),
user
.
getEmail
(),
user
.
getPassword
(),
authorities
);
}
@Override
public
Collection
<?
extends
GrantedAuthority
>
getAuthorities
()
{
return
authorities
;
}
public
String
getId
()
{
return
id
;
}
public
String
getEmail
()
{
return
email
;
}
@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
;
}
@Override
public
boolean
equals
(
Object
o
)
{
if
(
this
==
o
)
return
true
;
if
(
o
==
null
||
getClass
()
!=
o
.
getClass
())
return
false
;
UserDetailsImpl
user
=
(
UserDetailsImpl
)
o
;
return
Objects
.
equals
(
id
,
user
.
id
);
}
}
src/main/java/com/example/afrishop_v3/security/services/UserDetailsServiceImpl.java
0 → 100644
浏览文件 @
6d32c460
package
com
.
example
.
afrishop_v3
.
security
.
services
;
import
com.example.afrishop_v3.models.TbCfUserInfo
;
import
com.example.afrishop_v3.repository.UserRepository
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.core.userdetails.UserDetailsService
;
import
org.springframework.security.core.userdetails.UsernameNotFoundException
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
@Service
public
class
UserDetailsServiceImpl
implements
UserDetailsService
{
private
final
UserRepository
userRepository
;
public
UserDetailsServiceImpl
(
UserRepository
userRepository
)
{
this
.
userRepository
=
userRepository
;
}
@Override
@Transactional
public
UserDetails
loadUserByUsername
(
String
username
)
throws
UsernameNotFoundException
{
TbCfUserInfo
user
=
userRepository
.
findByAccount
(
username
)
.
orElseThrow
(()
->
new
UsernameNotFoundException
(
"User Not Found with username: "
+
username
));
return
UserDetailsImpl
.
build
(
user
);
}
}
src/main/resources/application.properties
浏览文件 @
6d32c460
...
...
@@ -13,8 +13,12 @@ security.jwt.client-id=whispajwtclientid
security.jwt.client-secret
=
XY7kmzoNzl100
security.jwt.grant-type
=
password
security.jwt.scope-read
=
read
jwt.secret
=
javainuse
security.jwt.scope-write
=
write
security.jwt.resource-ids
=
testjwtresourceid
spring.servlet.multipart.max-file-size
=
456128KB
spring.servlet.multipart.max-request-size
=
456128KB
# App Properties
bezkoder.app.jwtSecret
=
bezKoderSecretKey
bezkoder.app.jwtExpirationMs
=
86400000
编写
预览
Markdown
格式
0%
重试
或
添加新文件
添加附件
取消
您添加了
0
人
到此讨论。请谨慎行事。
请先完成此评论的编辑!
取消
请
注册
或者
登录
后发表评论