OAuth is used to provide access to authenticated project resourse to the authenticated client.All the client request is intercepted by the OAuth , validates the input request & its authentications , then forwards to the restricted resourse if successful.
Web.xml
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Bean.xml
<beans:bean name="springSecurityFilterChain" class="com.mhhe.openapi.oauthprovider.util.OAuthController"/>
package com.mhhe.openapi.oauthprovider.util;
import static com.mhhe.openapi.exception.OpenAPIErrorMessage.OPENAPI_ERROR_MESSAGE;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.SignatureException;
import java.util.Hashtable;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthException;
import net.oauth.OAuthMessage;
import net.oauth.OAuthProblemException;
import net.oauth.SimpleOAuthValidator;
import net.oauth.signature.OAuthSignatureMethod;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.gson.Gson;
import com.mhe.connect.business.common.Logger;
import com.mhe.connect.openapi.business.oauth.vo.OAuthNonceDomainVO;
import com.mhhe.connect.openapi.business.ServiceFactory;
import com.mhhe.connect.openapi.exception.ConnectApplicationException;
import com.mhhe.connect.openapi.exception.ConnectSystemException;
import com.mhhe.openapi.common.OpenAPIConfiguration;
import com.mhhe.openapi.domain.OAuthConsumerDetails;
import com.mhhe.openapi.domain.OAuthDomain;
import com.mhhe.openapi.util.OAuthConsumerDetailsService;
public class OAuthController implements Filter {
private static final Logger _logger = Logger.getInstance(OAuthController.class);
private FilterConfig filterConfig;
@Autowired
private OAuthConsumerDetailsService consumerDetailsService;
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
if (consumerDetailsService == null) {
consumerDetailsService = new OAuthConsumerDetailsService();
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (_logger.isDebugEnabled()) {
_logger.debug("Executing OAuthController... dofilter..start-->");
}
Gson gson = new Gson();
/* For Json generation */
OutputStream out = response.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(out);
OAuthDomain oAuthDomainObj = null;
Boolean isValidPath = true;
HttpServletResponse res = (HttpServletResponse)response;
/**
* 1. CHeck if oauth enabled for applicatiion
* 2. Check if Consumer Key is valid
* 3. Check if oauth check is requried for this consumer
* 4. Check if the timestamp in the header exceeds the window size differences
* 5. Check if nonce is being repeated.
* 6. Check if signature matches.
* 7. Update the oapi_oauth_nonce accordingly.
*/
try {
/* Request tracker */
insertRequestInfo ((HttpServletRequest)request);
/* Check for system wise control , if the oauth is ON or OFF */
if(!isAuthCheckEnabled()){
chain.doFilter(request, response); /* If Oauth validation is not enabled */
} else{
// get the request URI
String forwardUrl = getRequestURL ((HttpServletRequest)request);
String method = ((HttpServletRequest)request).getMethod().toString();
if (forwardUrl.contains(OAuthConstant.bypass_oauth_for_admin_pages) || forwardUrl.contains(OAuthConstant.bypass_oauth_for_logback_servlet)) {
chain.doFilter(request, response); /*Code to bypass admin jsp access without validation*/
} else if (forwardUrl.contains(OAuthConstant.bypass_oauth_for_secret_key_create)) {
createSecretKey((HttpServletRequest)request); /*Code to bypass admin jsp access without validation*/
chain.doFilter(request, response);
} else {
/*
* 1. Form the POJO from header.
*/
OAuthDomain oAuthDomain = getOAuthDomain((HttpServletRequest)request);
//fetch the details for this consumer
OpenAPIConfiguration openAPIConfiguration = new OpenAPIConfiguration();
OAuthConsumerDetails domain = openAPIConfiguration.loadConsumerByConsumerKey(oAuthDomain.getOauthConsumerKey());
//check whether consumer key is valid
if (isConsumerValid(domain)) {
//check whether oauth is required for this consumer
if (isOAuthReqd(domain)) {
// check whether mandatory fields have been filled up
validateResponse(oAuthDomain);
//check if timestamp difference matches the window size
/*if (isWindowSizeMatched(oAuthDomain,domain)) { */
//load all nonces for this consumer key
List<OAuthNonceDomainVO> nonces = consumerDetailsService.loadAllNoncesForConsumer(oAuthDomain.getOauthConsumerKey());
//check if nonce is repeated
if (!isNonceRepeated(oAuthDomain, nonces)) {
//check if signature matches
if (isSignatureMatched(oAuthDomain, domain,forwardUrl,method)) {
//update the DB
consumerDetailsService.updateNonce(oAuthDomain, domain.getWindowSize());
//process the request
chain.doFilter(request, response);
} else {
isValidPath = false;
throw new OAuthException("OAPI-OAUTH-002");
}
} else {
isValidPath = false;
throw new OAuthException("OAPI-OAUTH-004");
}
/*} else {
isValidPath = false;
throw new OAuthException("OAPI-OAUTH-003");
}*/
} else {
//process the request
chain.doFilter(request, response);
}
} else {
isValidPath = false;
throw new OAuthException("OAPI-OAUTH-001");
}
}
}
} catch (ConnectApplicationException e) {
_logger.error("exception in dofilter method of OAuthController class : "+e.getMessage(),e );
res.setStatus(401);
oAuthDomainObj = new OAuthDomain();
oAuthDomainObj.setErrorMessage(e.getMessage());
} catch (ConnectSystemException e) {
_logger.error("exception in dofilter method of OAuthController class : "+e.getMessage(),e );
res.setStatus(401);
oAuthDomainObj = new OAuthDomain();
oAuthDomainObj.setErrorMessage(e.getMessage());
} catch (OAuthException ex) {
res.setStatus(401);
oAuthDomainObj = new OAuthDomain();
oAuthDomainObj.setErrorMessage(ex.getMessage());
} finally {
try {
if (oAuthDomainObj != null) {
gson.toJson(oAuthDomainObj, osw);
osw.flush();
out.close();
}
} catch(Exception e) {
_logger.error("exception in finally block of dofilter method of OAuthController class ",e );
gson.toJson(oAuthDomainObj, osw);
osw.flush();
}
}
if (_logger.isDebugEnabled()) {
_logger.debug("Executing OAuthController... dofilter..end-->");
}
}
/**
* This method checks whether the incomingRequest came within the windowSize interval, ie
* timeRequestCame - windowSize <= currentTime <= timeRequestCame + windowSize
* @param oAuthDomain
* @param domain
* @return
*/
@Deprecated
private boolean isWindowSizeMatched(OAuthDomain oAuthDomain,
OAuthConsumerDetails domain) {
// check whether the current timestamp is +- windowSize than the timestamp obtained from header
if (_logger.isDebugEnabled()) {
_logger.debug("isWindowSizeMatched... ");
}
if (domain.getWindowSize() == 0) {
return true; //this could be default value
} else {
long timeRequestCame = Long.valueOf(oAuthDomain.getOauthTimestamp());
long currentTime = currentTimeSecs (System.currentTimeMillis());
if (_logger.isDebugEnabled()) {
_logger.debug("isWindowSizeMatched... timeRequestCame="+timeRequestCame+" currentTime="+currentTime+" windowSize="+domain.getWindowSize());
}
if ((currentTime <= timeRequestCame + domain.getWindowSize()) &&
(currentTime >= timeRequestCame - domain.getWindowSize())
) {
return true;
}
}
return false;
}
/**
* This method is used to convert currentTimeMillis to currentTimeSecs
* @param currentTimeMillis --- System.currentTimeMilis
* @return currentTimeSecs
*/
@Deprecated
private long currentTimeSecs( long currentTimeMillis ) {
long currentTimesec = (currentTimeMillis/1000);
return currentTimesec;
}
/**
* This is the method to be used for signature verifciation
* @param oAuthDomain
* @param domain
* @param uri
* @param method
* @return
* @throws OAuthException
*/
public boolean isSignatureMatched(OAuthDomain oAuthDomain, OAuthConsumerDetails domain
,String uri, String method)
throws OAuthException {
OAuthMessage authMessage = null;
OAuthAccessor accessor = null;
boolean isvalid = false ;
Hashtable<String, String> params = new Hashtable<String, String> ();
params.put("oauth_consumer_key",oAuthDomain.getOauthConsumerKey());
params.put("oauth_signature_method", oAuthDomain.getOauthSignatureMethod());
params.put("oauth_timestamp", oAuthDomain.getOauthTimestamp());
params.put("oauth_nonce", oAuthDomain.getOauthNonce());
params.put("oauth_version", oAuthDomain.getOauthVersion());
params.put("oauth_signature", oAuthDomain.getOauthSignature());
if (_logger.isDebugEnabled()) {
_logger.debug("Inside isSignatureMatched() -- nonce="+oAuthDomain.getOauthNonce()+" key="+oAuthDomain.getOauthConsumerKey()+" method="+oAuthDomain.getOauthSignatureMethod()+" timestamp="+oAuthDomain.getOauthTimestamp()+" version="+oAuthDomain.getOauthVersion());
_logger.debug("URI="+uri+" method="+method);
}
try {
authMessage = new OAuthMessage(method, uri, params.entrySet());
OAuthConsumer consumer = new OAuthConsumer(null,oAuthDomain.getOauthConsumerKey(),domain.getSecret(), null);
accessor = new OAuthAccessor(consumer);
accessor.accessToken = "";
/* Simple OAuth Validation */
SimpleOAuthValidator oauthValidator = new SimpleOAuthValidator (
domain.getWindowSize() * 1000L , Double.valueOf(oAuthDomain.getOauthVersion()));
/* Validate Oauth */
oauthValidator.validateMessage(authMessage, accessor);
authMessage.sign(accessor);
if (_logger.isDebugEnabled()) {
_logger.debug("Inside isSignatureMatched() -- signatureBaseString="+OAuthSignatureMethod.getBaseString(authMessage));
}
if (oAuthDomain.getOauthSignature().equals(authMessage.getSignature())) {
isvalid = true;
} else {
isvalid = false;
}
} catch (OAuthProblemException e) {
try {
if( "signature_invalid".equalsIgnoreCase(e.getMessage())) {
authMessage.sign(accessor);
if (_logger.isDebugEnabled()) {
_logger.debug("Inside isSignatureMatched() -- signatureBaseString="+OAuthSignatureMethod.getBaseString(authMessage));
}
if (oAuthDomain.getOauthSignature().equals(authMessage.getSignature())) {
isvalid = true;
} else {
isvalid = false;
}
} else if("timestamp_refused".equalsIgnoreCase(e.getMessage())) {
throw new OAuthException("OAPI-OAUTH-003");
}
} catch (IOException e1) {
e1.printStackTrace();
throw new OAuthException("OAPI-OAUTH-002");
} catch (URISyntaxException e2) {
e2.printStackTrace();
throw new OAuthException("OAPI-OAUTH-002");
}
} catch (IOException e) {
e.printStackTrace();
throw new OAuthException("OAPI-OAUTH-002");
} catch (URISyntaxException e) {
e.printStackTrace();
throw new OAuthException("OAPI-OAUTH-002");
}
return isvalid;
}
/**
* This is the method that checks whether the incoming signature matches the computed one.
* @param oAuthDomain
* @param domain
* @return
* @throws OAuthException
*/
@Deprecated
private boolean isSignatureMatched(OAuthDomain oAuthDomain, OAuthConsumerDetails domain)
throws OAuthException {
if (_logger.isDebugEnabled()) {
_logger.debug("Inside isSignatureMatched start-->");
}
StringBuffer baseString = new StringBuffer();
String oauthSignature = OAuthConstant.BLANK_STRING;
boolean authValidflag = false;
StringBuilder subBaseString = new StringBuilder();
if (_logger.isDebugEnabled()) {
_logger.debug("Inside isSignatureMatched() -- nonce="+oAuthDomain.getOauthNonce()+" key="+oAuthDomain.getOauthConsumerKey()+" method="+oAuthDomain.getOauthSignatureMethod()+" timestamp="+oAuthDomain.getOauthTimestamp());
}
subBaseString.append(OAuthConstant.oauth_consumer_key_url).append(oAuthDomain.getOauthConsumerKey())
.append(OAuthConstant.oauth_nonce_url).append(oAuthDomain.getOauthNonce()).append(OAuthConstant.oauth_signature_method_url)
.append(oAuthDomain.getOauthSignatureMethod()).append(OAuthConstant.oauth_timestamp_url).append(oAuthDomain.getOauthTimestamp())
.append(OAuthConstant.oauth_token_url).append(domain.getSecret())
.append(OAuthConstant.oauth_version_url).append(OAuthConstant.oauth_version_1);
if (_logger.isDebugEnabled()) {
_logger.debug("Inside isSignatureMatched() -- subBaseString--> ="+subBaseString);
}
try {
baseString.append(OAuthConstant.baseString_get);
//baseString.append(URLEncoder.encode(OAuthConstant.baseRequest, OAuthConstant.encode_format));
baseString.append(URLEncoder.encode(subBaseString.toString(), OAuthConstant.encode_format));
try {
oauthSignature = calculateRFC2104HMAC(baseString.toString(), domain.getSecret(),oAuthDomain.getOauthSignatureMethod());
oauthSignature = URLEncoder.encode(oauthSignature, OAuthConstant.encode_format);
if (_logger.isDebugEnabled()) {
_logger.debug("Inside isSignatureMatched() -- oauthSignature--> ="+oauthSignature);
}
} catch (SignatureException e) {
_logger.error(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4003"), e);
throw new ConnectApplicationException(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4003"),e);
}
} catch (UnsupportedEncodingException e) {
_logger.error(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4004"), e);
throw new ConnectApplicationException(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4004"),e);
}
if(oauthSignature.equals(oAuthDomain.getOauthSignature())){
authValidflag = true;
} else {
authValidflag = false;
}
if (_logger.isDebugEnabled()) {
_logger.debug("Inside isSignatureMatched() -- end--> with isvalidated ="+authValidflag);
}
return authValidflag;
}
/**
* This method checks whether the nonce is repeated or not
* @return boolean
*/
private boolean isNonceRepeated(OAuthDomain oAuthDomain,
List<OAuthNonceDomainVO> nonces) {
if (_logger.isDebugEnabled()) {
_logger.debug("isNonceRepeated... incomingNonce="+oAuthDomain.getOauthNonce());
}
for (OAuthNonceDomainVO oAuthNonceDomain : nonces) {
if (_logger.isDebugEnabled()) {
_logger.debug("isNonceRepeated... in the loop nonce value="+oAuthNonceDomain.getNonce());
}
if (oAuthNonceDomain.getNonce().equals(oAuthDomain.getOauthNonce())) {
return true;
}
}
return false;
}
/**
* This method return whether the consumer needs any oauth or not
* @return boolean
*/
private boolean isOAuthReqd(OAuthConsumerDetails domain) {
if (_logger.isDebugEnabled()) {
_logger.debug("isOAuthReqd... domain="+domain);
}
return domain.getOauthReqd();
}
/**
* This method return whether the consumer is valid or not
* @return boolean
*/
private boolean isConsumerValid(OAuthConsumerDetails domain) {
if (_logger.isDebugEnabled()) {
_logger.debug("isConsumerValid... ");
}
return domain != null? true : false;
}
/*
* This method will check if the response json object has content or not
*/
private void validateResponse(OAuthDomain oAuthDomainObj) throws OAuthException{
if(null != oAuthDomainObj){
if(oAuthDomainObj.getOauthSignatureMethod() == null || oAuthDomainObj.getOauthConsumerKey() == null
|| oAuthDomainObj.getOauthSignature() == null || oAuthDomainObj.getOauthNonce() == null
|| oAuthDomainObj.getOauthTimestamp() == null ){
throw new OAuthException("Header is invalid. Some mandatory fields are missing.");
}
}
}
/* This method is used to check if oauth enabled or not for the whole application
*
* Param HttpServletRequest
* return OAuthDomain Object
*/
private boolean isAuthCheckEnabled()throws ConnectApplicationException, ConnectSystemException {
if (_logger.isDebugEnabled()) {
_logger.debug("isAuthCheckEnabled... ");
}
//commenting the calling of db every time
//String authEnabled = ServiceFactory.getInstance().getOpenAPIOAuthService().getOpenAPIValue(OAuthConstant.OAUTH_ENABLED);
//calling from the map
String authEnabled = OpenAPIConfiguration.getSystemValue(OAuthConstant.OAUTH_ENABLED);
if (_logger.isDebugEnabled()) {
_logger.debug("isAuthCheckEnabled...isAuthEnabled="+authEnabled);
}
return OAuthConstant.TRUE.equalsIgnoreCase(authEnabled) ? true : false;
}
/* This method is used to get header inputs & prepare OAuthDomain object
*
* Param HttpServletRequest
* return OAuthDomain Object
*/
private OAuthDomain getOAuthDomain(HttpServletRequest request){
OAuthDomain oAuthDomain = new OAuthDomain();
String header = request.getHeader("Authorization");
/* Parse & put the header elements into OAuthDomain */
if(null != header){
header = header.replaceAll(""", "");
String[] headerArr = header.split(",");
if (_logger.isDebugEnabled()) {
_logger.debug("in getoAuthDomain() header= "+header);
}
for(int i=0 ; i < headerArr.length ; i ++ ){
if(null != headerArr[i]){
String[] tempArr = headerArr[i].split("=");
if(null != tempArr && tempArr.length > 0){
if(null != tempArr[0] && null != tempArr[1]){
String value = tempArr[1].trim();
if(OAuthConstant.key.equalsIgnoreCase(tempArr[0].trim())){
oAuthDomain.setOauthConsumerKey(value);
} else if(OAuthConstant.oauth_timestamp.equalsIgnoreCase(tempArr[0].trim())){
oAuthDomain.setOauthTimestamp(value);
} else if(OAuthConstant.signature.equalsIgnoreCase(tempArr[0].trim())){
int indexSignature = headerArr[i].indexOf(value);
if (indexSignature != -1){
value = headerArr[i].substring(indexSignature, headerArr[i].length());
oAuthDomain.setOauthSignature(value);
}
} else if(OAuthConstant.algorithm.equalsIgnoreCase(tempArr[0].trim())){
oAuthDomain.setOauthSignatureMethod(value);
} else if(OAuthConstant.nonce.equalsIgnoreCase(tempArr[0].trim())){
int indexNonce = headerArr[i].indexOf(value);
if (indexNonce != -1){
value = headerArr[i].substring(indexNonce, headerArr[i].length());
oAuthDomain.setOauthNonce(value);
}
} else if(OAuthConstant.oauth_version.equalsIgnoreCase(tempArr[0].trim())){
oAuthDomain.setOauthVersion(value);
} else if(OAuthConstant.realm.equalsIgnoreCase(tempArr[0].trim())){
oAuthDomain.setOauthRealm(value);
} else if(OAuthConstant.oauth_token.equalsIgnoreCase(tempArr[0].trim())){
oAuthDomain.setOauthToken(value);
}
}
}
}
}
} else {
_logger.error("Received header:"+header);
throw new ConnectApplicationException("OAPI-OAUTH-000");
}
if (_logger.isDebugEnabled()) {
_logger.debug("in getoAuthDomain() oAuthDomain= "+oAuthDomain);
}
return oAuthDomain;
}
@Override
public void destroy() {
this.filterConfig = null;
}
/**
* @return the consumerDetailsService
*/
public OAuthConsumerDetailsService getConsumerDetailsService() {
return consumerDetailsService;
}
/**
* @param consumerDetailsService the consumerDetailsService to set
*/
public void setConsumerDetailsService(
OAuthConsumerDetailsService consumerDetailsService) {
this.consumerDetailsService = consumerDetailsService;
}
/**
* This will calculate the signature for the BaseString
* @param baseString
* @param secretKey
* @param algorithm
* @return
* @throws java.security.SignatureException
*/
public static String calculateRFC2104HMAC(String baseString,
String secretKey,String algorithm) throws java.security.SignatureException {
String result;
try {
Mac mac = Mac.getInstance(algorithm);
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(),
mac.getAlgorithm());
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(baseString.getBytes());
// base64-encode the hmac
result = Base64.encodeBase64String(rawHmac);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : "+ e.getMessage());
}
return result;
}
/* This method is used to create Customer secret key
*
* Param HttpServletRequest
* return OAuthDomain Object
*/
private void createSecretKey(HttpServletRequest request)throws ConnectApplicationException, ConnectSystemException {
try{
String customerName = request.getParameter("customerName");
String authCheckFlag = request.getParameter("authCheckFlag");
String algorithmName = request.getParameter("algorithmName");
if(null != customerName){
String customerKey = customerName.trim().replaceAll(" ", "_")+"_key";
String customerSecret = createCustomerSecretKey(customerKey);
String customerSecretResponse = ServiceFactory.getInstance().getOpenAPIOAuthService()
.createSecretKey(customerKey,customerSecret,authCheckFlag,algorithmName,customerName);
if(null != customerSecretResponse){
request.setAttribute(OAuthConstant.oauth_consumer_key, customerKey);
request.setAttribute(OAuthConstant.consumer_secret, customerSecretResponse);
}else{
throw new ConnectApplicationException(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4002"));
}
}else{
throw new ConnectApplicationException(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4013"));
}
} catch (OAuthException e) {
_logger.error(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4012")+":"+e.getMessage(), e);
throw new ConnectApplicationException(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4012")+":"+e.getMessage(),e);
} catch (ConnectApplicationException e) {
_logger.error(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4012")+":"+e.getMessage(), e);
throw new ConnectApplicationException(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4012")+":"+e.getMessage(),e);
} catch (ConnectSystemException e) {
_logger.error(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4012")+":"+e.getMessage(), e);
throw new ConnectSystemException(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4012")+":"+e.getMessage(),e);
} catch (Exception e) {
_logger.error(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4012")+":"+e.getMessage() , e);
throw new ConnectSystemException(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4012")+":"+e.getMessage() ,e);
}
}
/**
* Generate a fresh request token and secret for a consumer.
*
* @throws OAuthException
*/
private String createCustomerSecretKey(String customerKey)
throws OAuthException {
// for now use md5 of name + current time as token
String token_data = customerKey + System.nanoTime();
String token = DigestUtils.md5Hex(token_data);
return token;
}
/*
* This method is used to track each request
*/
private void insertRequestInfo (HttpServletRequest request) {
if (_logger.isDebugEnabled()) {
_logger.debug("Inside insertRequestInfo of OAuthController with parameter request {}", new Object []{request});
}
final int MAX_SIZE = 3990;
try {
String URI = getRequestURL (request);
String oauthInfo = request.getHeader("Authorization");
BufferedReader reader = null;//request.getReader();
String postDataInfo = null;
if ( reader != null ) {
//Gson gson = new Gson();
postDataInfo = null;//convertReaderToString (reader);
if ( isSizeExceed(postDataInfo, MAX_SIZE) ) {
postDataInfo = trancatePostDataInfo(postDataInfo, MAX_SIZE);
}
if ( postDataInfo != null && "".equals(postDataInfo.trim()) ) {
postDataInfo = null;
}
}
if (_logger.isDebugEnabled()) {
_logger.debug("The value of URI {} oauthInfo {} reader {} " +
"postDataInfo {}",new Object[]{URI,oauthInfo,reader, postDataInfo});
}
consumerDetailsService.insertRequestInfo(URI, oauthInfo, postDataInfo);
} catch ( Exception e) {
_logger.error(OPENAPI_ERROR_MESSAGE.getErrorMessage("OAPI_4015")+":"+e.getMessage(), e);
}
}
private String convertReaderToString ( BufferedReader reader) throws IOException{
Writer writer = new StringWriter();
char[] buffer = new char[1024];
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
return writer.toString();
}
private String getRequestURL ( HttpServletRequest request ) {
return request.getRequestURL().toString();
}
private boolean isSizeExceed ( String postDataInfo, int MAX_SIZE ) {
if ( postDataInfo != null ) {
if ( postDataInfo.length() > MAX_SIZE ) {
return true;
}
}
return false;
}
private String trancatePostDataInfo ( String postDataInfo, int MAX_SIZE ) {
postDataInfo = postDataInfo.substring(0, MAX_SIZE);
return postDataInfo;
}
}
OpenAPIConfiguration.java (Service Class)
--------------------------------------------------------------
package com.mhhe.openapi.common;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.oauth.common.signature.SharedConsumerSecret;
import com.mhe.connect.business.common.Logger;
import com.mhe.connect.openapi.business.oauth.vo.OAuthDomainVO;
import com.mhe.connect.util.StringUtilities;
import com.mhhe.openapi.domain.OAuthConsumerDetails;
public class OpenAPIConfiguration {
private static Logger _logger = Logger.getInstance(OpenAPIConfiguration.class);
private static Map<String, OAuthConsumerDetails> consumers = new HashMap<String, OAuthConsumerDetails>();
private static List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
//this intialization method is invoked by spring and load properties from db
private static Map<String, String> map;
private static Map<String, String> systemMap;
private static DataSource dataSource;
/**
* @return the dataSource
*/
public DataSource getDataSource() {
return dataSource;
}
/**
* @param dataSource the dataSource to set
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void init(){
if(_logger.isDebugEnabled()){
_logger.debug("in the init method properties");
}
map = new HashMap<String, String>();
systemMap = new HashMap<String, String>();
String propsTableName = StringUtilities.getNonNullString(System.getProperty("OPENAPI_PROPERTIES_TBLNAME"));
if(propsTableName.equals("")||propsTableName.trim().length()==0){
_logger.debug("there is no system property defined in weblogic.taking the default value");
propsTableName="OAPI_APP_SET";
}
String sql = "select key,value from "+propsTableName+" where RCRD_STS_ID =1";
if(_logger.isDebugEnabled()){
_logger.debug("sql is:"+sql);
}
JdbcTemplate jt = new JdbcTemplate(dataSource);
jt.query(sql, new ResultSetExtractor() {
@Override
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
while(rs.next()){
map.put(StringUtilities.getNonNullString(rs.getString("key")).trim(), StringUtilities.getNonNullString(rs.getString("value")).trim());
}
if(_logger.isDebugEnabled()){
_logger.debug("setting values in map.test_value:"+map.get("test_key"));
}
return null;
}
});
systemMap.putAll(System.getenv());
setOAuthCosumerMap();
}
static public String getSystemValue(String name) {
try {
return map.get(name) != null ? map.get(name) : systemMap.get(name);
} catch (Exception e) {
_logger.error("Error while getting the value:",e);
return null;
}
}
public static void reloadProperties(){
if(_logger.isDebugEnabled()){
_logger.debug("in the reloadProperties method properties");
}
map = new HashMap<String, String>();
systemMap = new HashMap<String, String>();
String propsTableName = StringUtilities.getNonNullString(System.getProperty("OPENAPI_PROPERTIES_TBLNAME"));
if(propsTableName.equals("")||propsTableName.trim().length()==0){
_logger.debug("there is no system property defined in weblogic.taking the default value");
propsTableName="OAPI_APP_SET";
}
String sql = "select key,value from "+propsTableName+" where RCRD_STS_ID =1";
if(_logger.isDebugEnabled()){
_logger.debug("sql is:"+sql);
}
JdbcTemplate jt = new JdbcTemplate(dataSource);
jt.query(sql, new ResultSetExtractor() {
@Override
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
while(rs.next()){
map.put(StringUtilities.getNonNullString(rs.getString("key")).trim(), StringUtilities.getNonNullString(rs.getString("value")).trim());
}
if(_logger.isDebugEnabled()){
_logger.debug("setting values in map.test_value:"+map.get("test_key"));
}
return null;
}
});
systemMap.putAll(System.getenv());
setOAuthCosumerMap();
}
static public Map<String, String> getAllSystemValues() {
try {
return systemMap;
} catch (Exception e) {
_logger.error("Error while getting the value:",e);
return null;
}
}
static public Map<String, String> getAllDBValues() {
try {
return map;
} catch (Exception e) {
_logger.error("Error while getting the value:",e);
return null;
}
}
@SuppressWarnings("unchecked")
public static void setOAuthCosumerMap() {
Map<String, OAuthDomainVO> allCustomer = new HashMap<String, OAuthDomainVO>();
List<OAuthDomainVO> oAuthDomainList = new ArrayList<OAuthDomainVO>();
String GET_ALL_CUSTOMER_DETAILS = "SELECT O.* FROM OAPI_OAUTH_CONFIG O WHERE O.RCRD_STS_ID=1";
if (_logger.isDebugEnabled()) {
_logger.debug("sql for getting all consumers :"
+ GET_ALL_CUSTOMER_DETAILS);
}
JdbcTemplate jt = new JdbcTemplate(dataSource);
oAuthDomainList = jt.query(GET_ALL_CUSTOMER_DETAILS,
new ParameterizedRowMapper<OAuthDomainVO>() {
@Override
public OAuthDomainVO mapRow(ResultSet rst, int rowNum)
throws SQLException {
OAuthDomainVO oAuthDomain = new OAuthDomainVO();
oAuthDomain.setConsumerKey(rst
.getString("consumer_key"));
oAuthDomain.setConsumerSecret(rst
.getString("consumer_secret"));
oAuthDomain.setAlgorithm(rst.getString("algorithm"));
oAuthDomain.setConsumerName(rst
.getString("consumer_name"));
oAuthDomain.setVersion(rst.getString("version"));
oAuthDomain.setNonceReqd("Y".equals(rst
.getString("nonce_reqd")) ? Boolean.TRUE
: Boolean.FALSE);
oAuthDomain.setIs2legged("Y".equals(rst
.getString("is_2legged")) ? Boolean.TRUE
: Boolean.FALSE);
oAuthDomain.setOauthReqd("Y".equals(rst
.getString("oauth_reqd")) ? Boolean.TRUE
: Boolean.FALSE);
oAuthDomain
.setWindowSize(rst.getString("window_size") == null ? 10
: Long.parseLong(rst
.getString("window_size")));
return oAuthDomain;
}
});
if (oAuthDomainList.size() > 0) {
for (OAuthDomainVO oAuthDomain : oAuthDomainList) {
allCustomer.put(oAuthDomain.getConsumerKey(), oAuthDomain);
}
}
loadAllConsumers(allCustomer);
}
public static void loadAllConsumers(Map<String, OAuthDomainVO> consumersFromDB) {
//first create a default Authroity object
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER" ));
//now iterate thru the one and create our own OAuthConsumerDetails
if (consumersFromDB != null) {
for (String key: consumersFromDB.keySet()) {
OAuthDomainVO domain = consumersFromDB.get(key);
OAuthConsumerDetails consumer = new OAuthConsumerDetails();
consumer.setAlgorithm(domain.getAlgorithm());
consumer.setAuthorities(grantedAuthorities);
consumer.setConsumerKey(domain.getConsumerKey());
consumer.setConsumerName(domain.getConsumerName());
consumer.setIs2legged(domain.getIs2legged());
consumer.setNonceReqd(domain.getNonceReqd());
consumer.setOauthReqd(domain.getOauthReqd());
consumer.setRequiredToObtainAuthenticatedToken(false);
consumer.setSignatureSecret(new SharedConsumerSecret(domain.getConsumerSecret()));
consumer.setSecret(domain.getConsumerSecret());
consumer.setVersion(domain.getVersion());
consumer.setWindowSize(domain.getWindowSize());
consumers.put(key, consumer);
}
if (_logger.isDebugEnabled()) {
_logger.debug(consumers);
}
}
}
/**
*
*/
public OAuthConsumerDetails loadConsumerByConsumerKey(String key) {
// TODO Auto-generated method stub
if (_logger.isDebugEnabled()) {
_logger.debug(" Inside the loadConsumerByConsumerKey..."+key);
}
OAuthConsumerDetails consumer = consumers.get(key);
if (_logger.isDebugEnabled()) {
_logger.debug(" Inside the loadConsumerByConsumerKey. consumer.."+consumer);
}
return consumer;
}
}
Output of Above Java Program