调整结构

This commit is contained in:
zhou-hao
2017-12-01 20:22:10 +08:00
parent c17a67bb6c
commit 165c9ed8a7
10 changed files with 127 additions and 21 deletions

View File

@@ -59,10 +59,14 @@ public class AccessTokenInfo implements Serializable {
private String serverId;
public boolean isExpire() {
if (expiresIn == null) {
return true;
}
long time = updateTime==null?createTime:updateTime;
if (expiresIn <= 0) {
return false;
}
long time = updateTime == null ? createTime : updateTime;
return System.currentTimeMillis() - time > expiresIn * 1000;
}

View File

@@ -7,6 +7,7 @@ import org.hswebframework.web.authorization.oauth2.client.request.DefaultRespons
import org.hswebframework.web.authorization.oauth2.client.simple.*;
import org.hswebframework.web.authorization.oauth2.client.simple.provider.HswebResponseConvertSupport;
import org.hswebframework.web.authorization.oauth2.client.simple.provider.HswebResponseJudgeSupport;
import org.hswebframework.web.authorization.oauth2.client.simple.provider.github.GithubResponseConvert;
import org.hswebframework.web.authorization.oauth2.client.simple.request.builder.SimpleOAuth2RequestBuilderFactory;
import org.hswebframework.web.concurrent.lock.LockManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

View File

@@ -39,7 +39,7 @@ public class OAuth2RequestException extends RuntimeException {
}
public OAuth2RequestException(String message, ErrorType errorType, OAuth2Response response) {
super(message);
super(errorType+":"+message);
this.errorType = errorType;
this.response = response;
}

View File

@@ -49,7 +49,7 @@ public enum ErrorType {
UNSUPPORTED_RESPONSE_TYPE(4014), //不支持的响应类型
EXPIRED_CODE(4015), //AUTHORIZATION_CODE过期
EXPIRED_REFRESH_TOKEN(4020), //AUTHORIZATION_CODE过期
EXPIRED_REFRESH_TOKEN(4020), //REFRESH_TOKEN过期
CLIENT_DISABLED(4016),//客户端已被禁用

View File

@@ -21,11 +21,12 @@ package org.hswebframework.web.example.oauth2;
import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
import org.hswebframework.web.authorization.oauth2.client.OAuth2ServerConfig;
import org.hswebframework.web.authorization.oauth2.client.simple.OAuth2ServerConfigRepository;
import org.hswebframework.web.authorization.oauth2.client.simple.provider.github.GithubResponseConvert;
import org.hswebframework.web.authorization.oauth2.client.simple.provider.github.GithubResponseJudge;
import org.hswebframework.web.authorization.token.UserTokenManager;
import org.hswebframework.web.commons.entity.DataStatus;
import org.hswebframework.web.commons.entity.factory.EntityFactory;
import org.hswebframework.web.example.oauth2.github.GithubResponseConvert;
import org.hswebframework.web.example.oauth2.github.GithubResponseJudge;
import org.hswebframework.web.example.oauth2.github.GithubSSOAuthorizingListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
@@ -36,7 +37,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* TODO 完成注释
*
* @author zhouhao
*/
@@ -111,8 +111,7 @@ public class OAuth2ClientApplication implements CommandLineRunner {
OAuth2SSOAuthorizingListener listener = new OAuth2SSOAuthorizingListener(oAuth2RequestService, hsweb.getId(), userTokenManager);
GithubSSOAuthorizingListener githubSSOAuthorizingListener =
new GithubSSOAuthorizingListener(oAuth2RequestService, github.getId(), userTokenManager);
GithubSSOAuthorizingListener githubSSOAuthorizingListener = new GithubSSOAuthorizingListener(oAuth2RequestService, github.getId(), userTokenManager);
oAuth2RequestService.registerListener(hsweb.getId(), listener);
oAuth2RequestService.registerListener(github.getId(), githubSSOAuthorizingListener);

View File

@@ -0,0 +1,68 @@
package org.hswebframework.web.example.oauth2.github;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.WebUtil;
import org.hswebframework.web.authorization.oauth2.client.AccessTokenInfo;
import org.hswebframework.web.authorization.oauth2.client.request.definition.ResponseConvertForProviderDefinition;
import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
import java.util.List;
import java.util.Map;
@Slf4j
public class GithubResponseConvert implements ResponseConvertForProviderDefinition {
@Override
public String getProvider() {
return "github";
}
@Override
public <T> T convert(OAuth2Response response, Class<T> type) {
String result = response.asString();
if (result.startsWith("{")) {
return JSON.parseObject(result, type);
}
if (result.startsWith("[")) {
throw new UnsupportedOperationException("response is json array,you should call convertList method !");
}
Map<String, String> responseMap = WebUtil.queryStringToMap(result, "utf-8");
if (type == Map.class) {
return ((T) responseMap);
}
if (AccessTokenInfo.class.isAssignableFrom(type)) {
AccessTokenInfo info;
if(type!=AccessTokenInfo.class) {
try {
info = ((AccessTokenInfo) type.newInstance());
} catch (Exception e) {
log.warn("can not new instance {} use default AccessTokenInfo", type, e);
info = new AccessTokenInfo();
}
}else{
info = new AccessTokenInfo();
}
info.setAccessToken(responseMap.get("access_token"));
info.setScope(responseMap.get("scope"));
info.setTokenType(responseMap.get("token_type"));
info.setExpiresIn(-1);
return ((T) info);
}
return null;
}
@Override
public <T> List<T> convertList(OAuth2Response response, Class<T> type) {
String result = response.asString();
if (result.startsWith("{")) {
throw new UnsupportedOperationException("response is json array,you should call convertList method !");
}
if (result.startsWith("[")) {
return JSON.parseArray(result, type);
}
throw new UnsupportedOperationException("response format is not support yet,you can call response.as(ResponseConvert) method!");
}
}

View File

@@ -0,0 +1,38 @@
package org.hswebframework.web.example.oauth2.github;
import com.alibaba.fastjson.JSON;
import org.hswebframework.web.WebUtil;
import org.hswebframework.web.authorization.oauth2.client.exception.OAuth2RequestException;
import org.hswebframework.web.authorization.oauth2.client.request.definition.ResponseJudgeForProviderDefinition;
import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
import org.hswebframework.web.oauth2.core.ErrorType;
import java.util.Map;
public class GithubResponseJudge implements ResponseJudgeForProviderDefinition {
@Override
public String getProvider() {
return "github";
}
@Override
@SuppressWarnings("all")
public ErrorType judge(OAuth2Response response) {
String res= response.asString();
Map<String,Object> responseMap ;
if(res.startsWith("{")){
responseMap= JSON.parseObject(res);
}else{
responseMap= (Map) WebUtil.queryStringToMap(res,"utf-8");
}
if(response.status()==401){
throw new OAuth2RequestException(String.valueOf(responseMap.get("message")),ErrorType.UNAUTHORIZED_CLIENT,response);
}
if(responseMap.get("error")!=null){
throw new OAuth2RequestException(String.valueOf(responseMap.get("error_description")),ErrorType.EXPIRED_CODE,response);
}
return null;
}
}

View File

@@ -1,23 +1,20 @@
package org.hswebframework.web.example.oauth2;
package org.hswebframework.web.example.oauth2.github;
import org.hswebframework.web.WebUtil;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.basic.web.SessionIdUserTokenGenerator;
import org.hswebframework.web.authorization.basic.web.UserTokenGenerator;
import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
import org.hswebframework.web.authorization.oauth2.client.listener.OAuth2CodeAuthBeforeEvent;
import org.hswebframework.web.authorization.oauth2.client.listener.OAuth2Listener;
import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Session;
import org.hswebframework.web.authorization.simple.SimpleAuthentication;
import org.hswebframework.web.authorization.simple.SimplePermission;
import org.hswebframework.web.authorization.simple.SimpleRole;
import org.hswebframework.web.authorization.simple.SimpleUser;
import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilder;
import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
import org.hswebframework.web.authorization.token.UserTokenManager;
import org.hswebframework.web.example.oauth2.MemoryAuthenticationManager;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;

View File

@@ -90,7 +90,7 @@ public class OAuth2ClientController {
view.addStaticAttribute(OAuth2Constants.response_type, "code");
view.addStaticAttribute(OAuth2Constants.state, requestState(session).getResult());
view.addStaticAttribute(OAuth2Constants.client_id, entity.getClientId());
view.addStaticAttribute(OAuth2Constants.redirect_uri, URLEncoder.encode(callback, "UTF-8"));
view.addStaticAttribute(OAuth2Constants.redirect_uri, callback);
return view;
}
@@ -104,7 +104,6 @@ public class OAuth2ClientController {
HttpSession session) throws UnsupportedEncodingException {
try {
String cachedState = (String) session.getAttribute(STATE_SESSION_KEY);
// TODO: 2017/11/29 未验证state
// if (!state.equals(cachedState)) throw new BusinessException("state error");
oAuth2RequestService.doEvent(serverId, new OAuth2CodeAuthBeforeEvent(code, state, request::getParameter));
return new RedirectView(URLDecoder.decode(redirect, "UTF-8"));

View File

@@ -39,7 +39,7 @@ import java.util.List;
*/
@Service("oAuth2ServerConfigService")
@CacheConfig(cacheNames = "oauth2-server-config")
public class SimpleOAuth2ServerConfigService extends EnableCacheGenericEntityService<OAuth2ServerConfigEntity, String>
public class SimpleOAuth2ServerConfigService extends GenericEntityService<OAuth2ServerConfigEntity, String>
implements OAuth2ServerConfigService, OAuth2ServerConfigRepository {
@Autowired
private OAuth2ServerConfigDao oAuth2ServerConfigDao;
@@ -55,7 +55,7 @@ public class SimpleOAuth2ServerConfigService extends EnableCacheGenericEntitySer
}
@Override
@Cacheable(key = "'id:'+#id")
@Cacheable(key = "'conf-id:'+#id")
public OAuth2ServerConfig findById(String id) {
OAuth2ServerConfigEntity entity = selectByPk(id);
if (null == entity) {
@@ -65,13 +65,13 @@ public class SimpleOAuth2ServerConfigService extends EnableCacheGenericEntitySer
}
@Override
@CacheEvict(key = "'id:'+#id")
@CacheEvict(key = "'conf-id:'+#id")
public int updateByPk(String id, OAuth2ServerConfigEntity entity) {
return super.updateByPk(id, entity);
}
@Override
@CacheEvict(key = "'id:'+#id")
@CacheEvict(key = "'conf-id:'+#id")
public int deleteByPk(String id) {
return super.deleteByPk(id);
}
@@ -83,13 +83,13 @@ public class SimpleOAuth2ServerConfigService extends EnableCacheGenericEntitySer
}
@Override
@CacheEvict(key = "'id:'+#result")
@CacheEvict(key = "'conf-id:'+#result")
public String saveOrUpdate(OAuth2ServerConfigEntity entity) {
return super.saveOrUpdate(entity);
}
@Override
@CacheEvict(key = "'id:'+#result.id")
@CacheEvict(key = "'conf-id:'+#result.id")
public OAuth2ServerConfig save(OAuth2ServerConfig config) {
OAuth2ServerConfigEntity entity = entityFactory.newInstance(OAuth2ServerConfigEntity.class, config);
saveOrUpdate(entity);