Skip to content

Commit

Permalink
oauth2修改一些bug
Browse files Browse the repository at this point in the history
  • Loading branch information
yx726843014 committed Oct 5, 2018
1 parent f23019a commit 04a2f15
Show file tree
Hide file tree
Showing 11 changed files with 173 additions and 24 deletions.
14 changes: 7 additions & 7 deletions fly-core-base/src/main/resources/application-basedev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
spring:
redis:
port: 6379
host: 39.108.189.121
host: localhost
password:
timeout: 2000
jedis:
Expand Down Expand Up @@ -40,19 +40,19 @@
type: com.alibaba.druid.pool.DruidDataSource
oauth:
driver-class-name: com.mysql.jdbc.Driver
password: root
password: 123
username: root
url: jdbc:mysql://39.108.189.121:3306/fly_oauth?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
url: jdbc:mysql://localhost:3306/fly_oauth?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
order:
driver-class-name: com.mysql.jdbc.Driver
password: root
password: 123
username: root
url: jdbc:mysql://39.108.189.121:3306/fly_order?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
url: jdbc:mysql://localhost:3306/fly_order?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
goods:
driver-class-name: com.mysql.jdbc.Driver
password: root
password: 123
username: root
url: jdbc:mysql://39.108.189.121:3306/fly_goods?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
url: jdbc:mysql://localhost:3306/fly_goods?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
initialSize: 1
Expand Down
112 changes: 112 additions & 0 deletions fly-core-base/src/main/resources/application-basepro.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#配置redis:
spring:
redis:
port: 6379
host: 39.108.189.121
password:
timeout: 2000
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
rabbitmq:
addresses: 39.108.189.121
port: 5672
username: guest
password: guest
#开启发送确认
publisher-confirms: true
#开启发送失败退回
publisher-returns: true
#开启ack
listener:
direct:
acknowledge-mode: manual
retry:
enabled: true
max-attempts: 3
simple:
acknowledge-mode: manual
retry:
enabled: true
max-attempts: 3
datasource:
type: com.alibaba.druid.pool.DruidDataSource
oauth:
driver-class-name: com.mysql.jdbc.Driver
password: root
username: root
url: jdbc:mysql://39.108.189.121:3306/fly_oauth?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
order:
driver-class-name: com.mysql.jdbc.Driver
password: root
username: root
url: jdbc:mysql://39.108.189.121:3306/fly_order?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
goods:
driver-class-name: com.mysql.jdbc.Driver
password: root
username: root
url: jdbc:mysql://39.108.189.121:3306/fly_goods?useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
initialSize: 1
minIdle: 3
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
initialize: false


mybatis-plus:
# 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
# 如果是放在resource目录 classpath:/mapper/*Mapper.xml
mapper-locations: classpath*:/mapper/*.xml,/mapper/*/*.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.fly.**.domain
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 1
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
#refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
# Sequence序列接口实现类配置
#key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator
#逻辑删除配置(下面3个配置)
logic-delete-value: 1
logic-not-delete-value: 0
#sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#自定义填充策略接口实现
#meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler
configuration:
#配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
map-underscore-to-camel-case: true
cache-enabled: false
#配置JdbcTypeForNull, oracle数据库必须配置
jdbc-type-for-null: 'null'
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4 changes: 2 additions & 2 deletions fly-service-api/src/main/java/com/fly/ApiApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public static void main(String[] args) {

@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/order/**").permitAll()
.anyRequest().authenticated();
http.csrf().disable().authorizeRequests().anyRequest().permitAll();
// .anyRequest().authenticated();
}

@Override
Expand Down
12 changes: 10 additions & 2 deletions fly-service-api/src/main/java/com/fly/web/GoodsController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,20 @@
import com.fly.service.GoodsService;
import com.fly.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* @author 游雄
Expand All @@ -36,8 +41,11 @@ public Object addGoods(Principal principal){
}

@GetMapping(value = "/buy/{goodsId}")
public Object buyGoods(Principal principal, @PathVariable("goodsId") Integer goodsId){
if(principal == null){
public Object buyGoods(OAuth2Authentication principal, @PathVariable("goodsId") Integer goodsId){
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) principal.getUserAuthentication();
Map<Object,Object> details = (Map<Object, Object>) usernamePasswordAuthenticationToken.getDetails();
Object userAuthentication = details.get("userAuthentication");
if(userAuthentication == null){
return Result.buildFailure("未登录");
}
boolean flag = goodsService.buyGoods(goodsId,principal);
Expand Down
2 changes: 1 addition & 1 deletion fly-service-api/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
spring:
profiles:
active: pro,basedev
active: dev,basedev
application:
name: api-service
jackson:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
Expand All @@ -27,6 +29,9 @@
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;

import java.util.Arrays;

/**
* @author 游雄
Expand Down Expand Up @@ -61,7 +66,14 @@ public AuthorizationServerTokenServices myTokenServices(){
myTokenServices.setClientDetailsService(clientService);
myTokenServices.setAuthenticationManager(authenticationManager);
myTokenServices.setAccessTokenEnhancer(jwtAccessTokenConverter());
//支持刷新token
myTokenServices.setSupportRefreshToken(true);
//此处需要设置false不然刷新Token令牌 刷新后是不会被删除的
myTokenServices.setReuseRefreshToken(false);
//refresh_token需要配置
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper(accountService));
myTokenServices.setAuthenticationManager(new ProviderManager(Arrays.asList(provider)));
return myTokenServices;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,6 @@ public void configure(HttpSecurity http) throws Exception {
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.authenticationEntryPoint(new MyAuthExceptionEntryPoint()).accessDeniedHandler(new MyAccessDeniedHandler());
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
OAuth2Exception oAuth2Exception;
if (e.getMessage() != null && e.getMessage().equals(BAD_MSG)) {
oAuth2Exception = new InvalidGrantException("用户名或密码错误", e);
}else if (e instanceof InternalAuthenticationServiceException) {
} else if (e instanceof InternalAuthenticationServiceException) {
oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
} else{
} else if (e instanceof InvalidGrantException) {
oAuth2Exception = new InvalidGrantException("Token验证失效",e);
} else {
oAuth2Exception = new UnsupportedResponseTypeException("服务内部错误", e);
}
return super.translate(oAuth2Exception);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
*/
@DynamicDataSource(type = DatabaseType.oauth)
@Data
public class MyTokenServices implements AuthorizationServerTokenServices, ResourceServerTokenServices, ConsumerTokenServices, InitializingBean {
public class MyTokenServices extends DefaultTokenServices implements AuthorizationServerTokenServices, ResourceServerTokenServices, ConsumerTokenServices, InitializingBean {
private int refreshTokenValiditySeconds = 2592000;
private int accessTokenValiditySeconds = 43200;
private boolean supportRefreshToken = false;
Expand All @@ -51,10 +51,11 @@ public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication)
OAuth2AccessToken existingAccessToken = this.tokenStore.getAccessToken(authentication);
OAuth2RefreshToken refreshToken = null;
if (existingAccessToken != null) {
if (!existingAccessToken.isExpired()) {
//重复登录挤掉前面登录的
/*if (!existingAccessToken.isExpired()) {
this.tokenStore.storeAccessToken(existingAccessToken, authentication);
return existingAccessToken;
}
}*/

if (existingAccessToken.getRefreshToken() != null) {
refreshToken = existingAccessToken.getRefreshToken();
Expand Down
20 changes: 17 additions & 3 deletions fly-service-oauth/src/main/java/com/fly/web/AccountController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
import com.fly.service.AccountService;
import com.fly.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Map;

/**
* @author 游雄
Expand All @@ -23,9 +27,19 @@ public class AccountController {
@Autowired
private AccountService accountService;

@RequestMapping(value = "user",produces = "application/json")
public Object user(Principal principal){
//Account account = accountService.findByUsername("admin");
@RequestMapping(value = "user", produces = "application/json")
public Object user(OAuth2Authentication principal) {
OAuth2Request oAuth2Request = principal.getOAuth2Request();
String grantType = oAuth2Request.getGrantType();
if (grantType.equals("password")) {
Account account = accountService.findByUsername(principal.getName());
if(account != null){
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) principal.getUserAuthentication();
Map<Object, Object> details = (Map<Object, Object>) usernamePasswordAuthenticationToken.getDetails();
details.put("account",account);
// principal.setDetails(details);
}
}
return principal;
}

Expand Down
6 changes: 2 additions & 4 deletions fly-service-oauth/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
spring:
profiles:
active: basedev,pro
active: basedev,dev
application:
name: oauth
output:
ansi:
enabled: always
server:
port: 8200
management:
security:
enabled: false



0 comments on commit 04a2f15

Please sign in to comment.