Commit 8b82e539 authored by Quxl's avatar Quxl

c

parent c95b8117
package com.egolm.sso.api;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
......@@ -22,55 +23,114 @@ import org.apache.oltu.oauth2.common.message.types.GrantType;
public interface OAuthApi {
OAuthConfig getOAuthConfig();
final String OAUTH_TOKEN_SESSION = "OAUTH2_TOKEN_SESSION_KEY";
default void sendOAuthLoginRedirect(HttpServletResponse response) throws IOException, OAuthSystemException {
OAuthConfig config = this.getOAuthConfig();
AuthenticationRequestBuilder builder = OAuthClientRequest.authorizationLocation(config.getAuthorizeUrl());
builder.setResponseType(OAuth.OAUTH_CODE);
builder.setClientId(config.getClientId());
builder.setRedirectURI(config.getRediretUrl());
builder.setScope(config.getClientScope());
OAuthClientRequest oauthResponse = builder.buildQueryMessage();
response.sendRedirect(oauthResponse.getLocationUri());
default void sendOAuthLoginRedirect(HttpServletResponse response) {
try {
OAuthConfig config = this.getOAuthConfig();
AuthenticationRequestBuilder builder = OAuthClientRequest.authorizationLocation(config.getAuthorizeUrl());
builder.setResponseType(OAuth.OAUTH_CODE);
builder.setClientId(config.getClientId());
builder.setRedirectURI(config.getRediretUrl());
builder.setScope(config.getClientScope());
OAuthClientRequest oauthResponse = builder.buildQueryMessage();
response.sendRedirect(oauthResponse.getLocationUri());
} catch (Exception e) {
throw new OAuthApiException(e.getMessage(), e);
}
}
default boolean isLogin(HttpServletRequest request) {
HttpSession session = request.getSession();
OAuthToken token = (OAuthToken)session.getAttribute(OAUTH_TOKEN_SESSION);
return token != null;
}
default OAuthToken getOAuthToken(HttpServletRequest request) throws OAuthProblemException, OAuthSystemException {
OAuthConfig config = this.getOAuthConfig();
OAuthAuthzResponse oauthAuthzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oauthAuthzResponse.getCode();
TokenRequestBuilder builder = OAuthClientRequest.tokenLocation(config.getAccessTokenUrl());
builder.setGrantType(GrantType.AUTHORIZATION_CODE);
builder.setClientId(config.getClientId());
builder.setClientSecret(config.getClientSecret());
builder.setRedirectURI(config.getRediretUrl());
builder.setCode(code);
OAuthClientRequest oauthClientRequest = builder.buildQueryMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(oauthClientRequest, OAuth.HttpMethod.POST);
String accessToken = oAuthResponse.getAccessToken();
String refreshToken = oAuthResponse.getRefreshToken();
Long expiresIn = oAuthResponse.getExpiresIn();
String idToken = oAuthResponse.getParam("id_token");
String tokenType = oAuthResponse.getTokenType();
OAuthToken token = new OAuthToken(accessToken, refreshToken, idToken, tokenType, expiresIn);
return token;
try {
HttpSession session = request.getSession();
OAuthToken token = (OAuthToken)session.getAttribute(OAUTH_TOKEN_SESSION);
if(token == null) {
OAuthConfig config = this.getOAuthConfig();
OAuthAuthzResponse oauthAuthzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oauthAuthzResponse.getCode();
TokenRequestBuilder builder = OAuthClientRequest.tokenLocation(config.getAccessTokenUrl());
builder.setGrantType(GrantType.AUTHORIZATION_CODE);
builder.setClientId(config.getClientId());
builder.setClientSecret(config.getClientSecret());
builder.setRedirectURI(config.getRediretUrl());
builder.setCode(code);
OAuthClientRequest oauthClientRequest = builder.buildQueryMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(oauthClientRequest, OAuth.HttpMethod.POST);
String accessToken = oAuthResponse.getAccessToken();
String refreshToken = oAuthResponse.getRefreshToken();
Long expiresIn = oAuthResponse.getExpiresIn();
String idToken = oAuthResponse.getParam("id_token");
String tokenType = oAuthResponse.getTokenType();
token = new OAuthToken(accessToken, refreshToken, idToken, tokenType, expiresIn);
session.setAttribute(OAUTH_TOKEN_SESSION, token);
}
return token;
} catch (Exception e) {
throw new OAuthApiException(e.getMessage(), e);
}
}
default OAuthToken refreshOAuthToken(HttpServletRequest request) {
try {
HttpSession session = request.getSession();
OAuthToken token = (OAuthToken)session.getAttribute(OAUTH_TOKEN_SESSION);
OAuthConfig config = this.getOAuthConfig();
TokenRequestBuilder builder = OAuthClientRequest.tokenLocation(config.getAccessTokenUrl());
builder.setGrantType(GrantType.REFRESH_TOKEN);
builder.setRefreshToken(token.getRefreshToken());
builder.setClientId(config.getClientId());
builder.setClientSecret(config.getClientSecret());
OAuthClientRequest oauthClientRequest = builder.buildQueryMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(oauthClientRequest, OAuth.HttpMethod.POST);
String accessToken = oAuthResponse.getAccessToken();
String refreshToken = oAuthResponse.getRefreshToken();
Long expiresIn = oAuthResponse.getExpiresIn();
String idToken = oAuthResponse.getParam("id_token");
String tokenType = oAuthResponse.getTokenType();
OAuthToken newToken = new OAuthToken(accessToken, refreshToken, idToken, tokenType, expiresIn);
session.setAttribute(OAUTH_TOKEN_SESSION, newToken);
return newToken;
} catch (Exception e) {
throw new OAuthApiException(e.getMessage(), e);
}
}
default String getResource(String method, String url, OAuthToken token) throws OAuthSystemException, OAuthProblemException {
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
String accessToken = token.getAccessToken();
OAuthClientRequest request = new OAuthBearerClientRequest(url).setAccessToken(accessToken).buildQueryMessage();
OAuthResourceResponse resourceResponse = oAuthClient.resource(request, method, OAuthResourceResponse.class);
String resBody = resourceResponse.getBody();
return resBody;
default String doRequest(String method, String url, HttpServletRequest req) {
try {
HttpSession session = req.getSession();
OAuthToken token = (OAuthToken)session.getAttribute(OAUTH_TOKEN_SESSION);
Map<String, String[]> parameters = req.getParameterMap();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
String accessToken = token.getAccessToken();
OAuthClientRequest request = new OAuthBearerClientRequest(url).setAccessToken(accessToken).buildQueryMessage();
String body = StringUtil.toQueryString(parameters);
request.setBody(body);
OAuthResourceResponse resourceResponse = oAuthClient.resource(request, method, OAuthResourceResponse.class);
String resBody = resourceResponse.getBody();
return resBody;
} catch (OAuthProblemException e) {
this.refreshOAuthToken(req);
return doRequest(method, url, req);
} catch (Exception e) {
throw new OAuthApiException(e.getMessage(), e);
}
}
default String doGetResource(String url, OAuthToken token) throws OAuthSystemException, OAuthProblemException {
return this.getResource("GET", url, token);
default String doGetResource(String url, HttpServletRequest req) {
return this.doRequest("GET", url, req);
}
default String doPostResource(String url, OAuthToken token) throws OAuthSystemException, OAuthProblemException {
return this.getResource("POST", url, token);
default String doPostResource(String url, HttpServletRequest req) {
return this.doRequest("POST", url, req);
}
}
package com.egolm.sso.api;
public class OAuthApiException extends RuntimeException {
private static final long serialVersionUID = 4300677142149830999L;
public OAuthApiException(String message) {
super(message);
}
public OAuthApiException(String message, Throwable e) {
super(message, e);
}
}
package com.egolm.sso.api;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class StringUtil {
public static String toQueryString(Map<?, ?> parameters) throws UnsupportedEncodingException {
return toQueryString(parameters, null);
}
public static String toQueryString(Map<?, ?> parameters, String encode) throws UnsupportedEncodingException {
List<String> params = new ArrayList<String>();
if (parameters != null) {
for (Object key : parameters.keySet()) {
Object val = parameters.get(key);
String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? ""
: URLEncoder.encode(String.valueOf(sVal), encode == null ? "utf-8" : encode)));
}
} else {
params.add("sKey=");
}
}
}
return join("&", "", "", "", params);
}
public static String join(String sign, String before, String after, String def, List<String> strs) {
if(strs == null || strs.size() == 0) {
return def;
} else {
StringBuffer sb = new StringBuffer();
Integer size = strs.size();
for(int i = 0; i < size; i++) {
String str = String.valueOf(strs.get(i));
sb.append((i == 0 && before != null) ? before : "").append(str == null ? "" : str).append(i < size - 1 ? (sign == null ? "" : sign) : "").append((i == size - 1 && after != null) ? after : "");
}
return String.valueOf(sb);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment