Getting error when removing the defalt apiAuthentication handler and adding myCustomhandler, any idea? - handler

(previously it was working fine but don't what is changed )
When i am removing the default handler from synapse configs and adding my custom handler it is giving this error
[2022-01-13 10:44:41,924] ERROR - ServerWorker Error processing POST request for : /dev/21.2/ext-rt/publish/TestTenant/SmooksProviderTranslation.csv.
java.lang.NullPointerException: null
at org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler.doRoleBasedAccessThrottlingWithCEP_aroundBody0(ThrottleHandler.java:193) ~[org.wso2.carbon.apimgt.gateway_6.7.206.jar:?]
at org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler.doRoleBasedAccessThrottlingWithCEP(ThrottleHandler.java:145) ~[org.wso2.carbon.apimgt.gateway_6.7.206.jar:?]
at org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler.doThrottle_aroundBody12(ThrottleHandler.java:585) ~[org.wso2.carbon.apimgt.gateway_6.7.206.jar:?]
at org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler.doThrottle(ThrottleHandler.java:562) ~[org.wso2.carbon.apimgt.gateway_6.7.206.jar:?]
at org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler.handleRequest_aroundBody8(ThrottleHandler.java:522) ~[org.wso2.carbon.apimgt.gateway_6.7.206.jar:?]
at org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler.handleRequest(ThrottleHandler.java:503) ~[org.wso2.carbon.apimgt.gateway_6.7.206.jar:?]
at org.apache.synapse.rest.API.process(API.java:373) ~[synapse-core_2.1.7.wso2v183.jar:2.1.7-wso2v183]
at org.apache.synapse.rest.RESTRequestHandler.apiProcessNonDefaultStrategy(RESTRequestHandler.java:144) ~[synapse-core_2.1.7.wso2v183.jar:2.1.7-wso2v183]
at org.apache.synapse.rest.RESTRequestHandler.identifyAPI(RESTRequestHandler.java:164) ~[synapse-core_2.1.7.wso2v183.jar:2.1.7-wso2v183]
at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:95) ~[synapse-core_2.1.7.wso2v183.jar:2.1.7-wso2v183]
at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:73) ~[synapse-core_2.1.7.wso2v183.jar:2.1.7-wso2v183]
at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:331) ~[synapse-core_2.1.7.wso2v183.jar:2.1.7-wso2v183]
at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:99) ~[synapse-core_2.1.7.wso2v183.jar:2.1.7-wso2v183]
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) ~[axis2_1.6.1.wso2v41.jar:?]
at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:367) [synapse-nhttp-transport_2.1.7.wso2v183.jar:?]
at org.apache.synapse.transport.passthru.ServerWorker.processEntityEnclosingRequest(ServerWorker.java:426) [synapse-nhttp-transport_2.1.7.wso2v183.jar:?]
at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:181) [synapse-nhttp-transport_2.1.7.wso2v183.jar:?]
at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) [axis2_1.6.1.wso2v41.jar:?]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
at java.lang.Thread.run(Thread.java:834) [?:?]
Below is the authenticate() method from myCustomHandler.java class, which has the AuthenticationContext object
public boolean authenticate(MessageContext synCtx) throws APISecurityException {
Map headers = getTransportHeaders(synCtx);
String authHeader = getAuthorizationHeader(headers);
String postmanToken = getPostmanToken(headers);
String clientIP = "10.110.67.195";
org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx)
.getAxis2MessageContext();
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
// Can modify to support scopes based throttle policy selection
authContext.setTier(APIConstants.UNLIMITED_TIER);
authContext.setStopOnQuotaReach(true);
authContext.setApiKey(clientIP);
authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
authContext.setUsername((String) axis2MessageContext.getProperty("user"));
authContext.setCallerToken(null);
authContext.setApplicationName(null);
authContext.setApplicationId(clientIP);
authContext.setConsumerKey(null);
log.debug("**** applicationID is --- " + authContext.getApplicationId());
APISecurityUtils.setAuthenticationContext(synCtx, authContext, null);
System.out.println("**** TE is HERE");
log.debug("**** TE is HERE2");
log.debug("**** Header is --- " + headers);
log.debug("**** AuthHeader is --- " + authHeader);
log.debug("**** Postman token is --- " + postmanToken);
return true;
/*
* if (authHeader.startsWith("Bearer ")) { return true; } return false;
*/
}

I think the problem is with the AuthenticationContext object. We populate the authContext object at the Authentication handler(in each authenticator [1]) and this object is used at the throttle handler[2]. when you replaced the Authentication handler with your custom handler, you might have missed populating this object. Try populating this object as [1].
[1] - https://github.com/wso2/carbon-apimgt/blob/v6.7.206/components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/oauth/OAuthAuthenticator.java#L301
[2] - https://github.com/wso2/carbon-apimgt/blob/v6.7.206/components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/throttling/ThrottleHandler.java#L193

Related

javax.cache.CacheException: Failed to find SQL table for type: XXXXXX

I am using ignite 2.7 version and getting the below exception while querying the ignite cache:
19/10/30 05:33:14 ERROR yarn.ApplicationMaster: User class threw exception: javax.cache.CacheException: Failed to find SQL table for type: CanonicalXXXXX
javax.cache.CacheException: Failed to find SQL table for type: CanonicalXXXXX
This is my code to start ignite:
def getIgnite(): Ignite = {
val clusterName = clusterProperties.getProperty("XXXXXXXX")
Ignition.setClientMode(true)
try {
val ignite = Ignition.ignite(clusterName);
if ( clusterName == ignite.name() ) {
logInfo("#### Found and returning client for cluster: " +
clusterName)
return ignite
}
}
catch {
case e: Exception => e.printStackTrace()
}
val configFilePath = clusterProperties.getProperty("XXXXXXXX")
logInfo("#### configFilePath: " + configFilePath)
val configInputStream = FileSystem.get(new Configuration()).open(new
Path(configFilePath));
logInfo("#### Starting Ignite Client")
return Ignition.start(configInputStream) }
I am loading data into the cache and data get loaded successfully and cache size also get printed as below:
INFO dataloader.IgniteDataLoader: #### OFFICIAL_NAME_CACHE SIZE => 51016471
Below code is for accessing the cache:
def createXXXXXXCache: IgniteCache[String, CanonicalXXXXX] = {
val orgCacheCfg: CacheConfiguration[String, CanonicalXXXXX] =
new CacheConfiguration[String, CanonicalXXXXX](OFFICIAL_NAME_CACHE)
orgCacheCfg.setIndexedTypes(classOf[String], classOf[CanonicalXXXXX])
orgCacheCfg.setCacheMode(CacheMode.PARTITIONED)
orgCacheCfg.setAtomicityMode(CacheAtomicityMode.ATOMIC)
orgCacheCfg.setBackups(3)
getIgnite().getOrCreateCache(orgCacheCfg) }
But while trying to query the cache I am getting the exception. Below code is for querying the cache:
val companyName = "SUFFOLK CONST CO"
val queryString = "orgName = '" + companyName + "'"
val companyNameQuery = new SqlQuery[String, CanonicalXXXXX]
(classOf[CanonicalXXXXX], queryString)
val queryCursor = igniteXXXXXX.createXXXXXXCache.query(companyNameQuery)
val queryResults = Future {
queryCursor.getAll()
}
try {
val companyResults = extractXXXXXVO(queryResults)
logInfo(s"Ignite Results returned - $companyResults")
} catch {
case exe: Exception => logInfo(s"OfficialXXXX exact search timed out")
queryCursor.close()
Vector.empty
}
The code throwing exception at query() method for the below line:
val queryCursor = igniteXXXXXX.createXXXXXXCache.query(companyNameQuery)
19/10/30 05:33:14 INFO dataloader.IgniteServerXXXXXX: Examplelogger1 - 'SqlQuery [type= CanonicalXXXXX, alias=null, sql=orgName = 'SUFFOLK CONSTRUCTION CO INC', args=null, timeout=0, distributedJoins=false, replicatedOnly=false]'
19/10/30 05:33:14 INFO dataloader.igniteXXXXXX: #### Found and returning client for cluster: JalaDalaXXXXX
19/10/30 05:33:14 ERROR yarn.ApplicationMaster: User class threw exception: javax.cache.CacheException: Failed to find SQL table for type: CanonicalXXXXX
javax.cache.CacheException: Failed to find SQL table for type: CanonicalXXXXX
at org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.query(IgniteCacheProxyImpl.java:697)
at org.apache.ignite.internal.processors.cache.GatewayProtectedCacheProxy.query(GatewayProtectedCacheProxy.java:376)
at xx.xx.dataloader.IgniteServerXXXXXX$.loadOAData(IgniteServerXXXXXX.scala:70)
at xx.xx.StartXXXXXXX$.startIgniteAndDataloading(StartXXXXXXX.scala:49)
at xx.xx.StartXXXXXXX$delayedInit$body.apply(StartXXXXXXX.scala:13)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32)
at scala.App$class.main(App.scala:71)
at xx.xx.StartXXXXXXX$.main(StartXXXXXXX.scala:12)
at xx.xx.StartXXXXXXX.main(StartXXXXXXX.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$2.run(ApplicationMaster.scala:567)
Caused by: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to find SQL table for type: CanonicalNameOAVO
at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSql(IgniteH2Indexing.java:1843)
at org.apache.ignite.internal.processors.query.GridQueryProcessor$7.applyx(GridQueryProcessor.java:2289)
at org.apache.ignite.internal.processors.query.GridQueryProcessor$7.applyx(GridQueryProcessor.java:2287)
at org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:2707)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.queryDistributedSql(GridQueryProcessor.java:2286)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.querySql(GridQueryProcessor.java:2267)
at org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.query(IgniteCacheProxyImpl.java:682)
Could someone please suggest how to resolve the issue.
Thanks,
Chandan
I'm not sure about the root cause of the issue, but first of all you should replace
val queryString = "orgName = '" + companyName + "'"
val companyNameQuery = new SqlQuery[String, CanonicalXXXXX](classOf[CanonicalXXXXX], queryString)
with
val queryString = "orgName = ?"
val companyNameQuery = new SqlQuery[String, CanonicalXXXXX](classOf[CanonicalXXXXX], queryString)
companyNameQuery.setArgs(companyName)
That's the correct way of using of this API. By the way SqlQuery is a kind of deprecated stuff. You should prefer to use SqlFieldsQuery instead of it.

GDAX Post Call returns invalid signature

I am trying to make a post request on GDAX.
But I always receive a "invalid signature" message.
GDAX API Docs for creating request + signing: https://docs.gdax.com/#creating-a-request
Preshash string returns the following:
1500627733POST/orders{"price":"1000.0","size":"0.02","type":"limit","side":"sell","product_id":"BTC-EUR"}
My signature method:
public String generateSignature(String requestPath, String method, String body, String timestamp) {
try {
String prehash = timestamp + method.toUpperCase() + requestPath + body;
byte[] secretDecoded = Base64.getDecoder().decode(secretKey);
SecretKeySpec keyspec = new SecretKeySpec(secretDecoded, "HmacSHA256");
Mac sha256 = (Mac) Mac.getInstance("HmacSHA256").clone();
sha256.init(keyspec);
return Base64.getEncoder().encodeToString(sha256.doFinal(prehash.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
My request method:
private boolean placeLimitOrder(String currencyPair, String side, String price, String size)
throws UnirestException {
String timestamp = Instant.now().getEpochSecond() + "";
String api_method = "/orders";
String path = base_url + api_method; //base_url = https://api.gdax.com
String method = "POST";
String b = "{\"price\":\"1000.0\",\"size\":\"0.02\",\"type\":\"limit\",\"side\":\"sell\",\"product_id\":\"BTC-EUR\"}";
JsonNode n = new JsonNode(b);
String sig = generateSignature(api_method, method,b, timestamp);
HttpResponse<JsonNode> rep = Unirest.post(path).header("accept", "application/json")
.header("content-type", "application/json")
.header("CB-ACCESS-KEY", publicKey)
.header("CB-ACCESS-PASSPHRASE", passphrase)
.header("CB-ACCESS-SIGN", sig)
.header("CB-ACCESS-TIMESTAMP", timestamp)
.body(n)
.asJson();
System.out.println(rep.getStatusText()); //Bad Request
System.out.println(rep.getBody().toString()); //invalid signature
System.out.println(sig); //returns something
return false;
}
I also tried to make a API Request Call with Insomnia but it returns the same message ("invalid signature").
Any clues?
Thank you very much in advance!
Looks like you are signing the price order data which is a string, but for the body in the post you are turning it into a json node. Which may not match when gdax decodes the signing and compares the payload data to the decrypted(signed body) when they receive it.
Why not just send the string as the body and remove the ".asJson"?
.body(b)
I was stuck on a similar issue when I was testing the API in C#. After 3 afternoons of trying. I tested sending the data as a string and I was able to get pass the invalid signature error.
I had the same problem.
I used http:
but the right one httpS:
Problem solved.

C# "The request was aborted: Could not create SSL/TLS secure channel." - happening occasionally

This is a request to GoCardless test API from a Dynamics CRM plugin. I receive "The request was aborted: Could not create SSL/TLS secure channel." error. It only happens on the first request after some time without sending one. If I send it again, it will be OK. I would appreciate a lot your help.
Here is my code:
//I have tried all the following lines in comment without success
//ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
//ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//ServicePointManager.Expect100Continue = true;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
// Create a new WebClient instance.
string baseURL = "https://api-sandbox.gocardless.com/";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", "Bearer " + t);
client.Headers.Add("GoCardless-Version", "2015-07-06");
client.Headers.Add("Accept", "application/json");
Customers model = new Customers();
customer.country_code = "GB";
model.customers = customer;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customers));
ser.WriteObject(stream1, model);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
// Apply ASCII Encoding to obtain the string as a byte array.
byte[] byteArray = Encoding.ASCII.GetBytes(sr.ReadToEnd());
ReturnedCustomers result = new ReturnedCustomers();
//Upload the input string using the HTTP 1.0 POST method.
try
{
byte[] responseArray = client.UploadData(baseURL + "customers", "POST", byteArray);
string responseText = Encoding.ASCII.GetString(responseArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ReturnedCustomers));
using (Stream s = GenerateStreamFromString(responseText))
{
result = (ReturnedCustomers)serializer.ReadObject(s);
}
}
catch (WebException exception)
{
}
From the Microsoft documentation (https://msdn.microsoft.com/en-us/library/gg334752.aspx) are the following limitations:
Only the HTTP and HTTPS protocols are allowed.
Access to localhost (loopback) is not permitted.
IP addresses cannot be used. You must use a named web address that requires DNS name resolution.
Anonymous authentication is supported and recommended.
5.There is no provision for prompting the logged on user for credentials or saving those credentials.
The error may be due to seguneti things:
The certificate is invalid
The certification authority is not public
Could you check what is the value of ServicePointManager.Expect100Continue and ServicePointManager.SecurityProtocol attributes in your environment?

Apache Shiro login failed using JDBC Realm

I am trying to connect to oracle DB .
I want to retrieve list of passwords from data base using the authentication query. Here is my sample shiro.ini file:
# password matcher
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordMatcher.passwordService = $passwordService
# datasource
ds = oracle.jdbc.pool.OracleDataSource
ds.URL = jdbc:oracle:thin:#matrix-oracle11g:1521:dev11g
ds.user = cit1am
ds.password = cit1
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR
jdbcRealm.credentialsMatcher = $passwordMatcher
jdbcRealm.dataSource = $ds
securityManager.realms = $jdbcRealm
[users]
[roles]
[urls]
Sample code snippet of login:
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
try{
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("cit1am", "cit1") ;
token.setRememberMe(true);
try {
currentUser.login(token); //problem occurs here
log.info("inside try block ==========>>" );
}
catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
}
I am getting following error:
[main] ERROR org.apache.shiro.realm.jdbc.JdbcRealm - There was a SQL error while authenticating user [cit1am]
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
Please suggest what i am doing wrong?
After debugging more i found issue with my code and sql query in .ini file.
I changed following in .INI file
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR where USR_NM = ?
Also commented
#cm = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
#jdbcRealm.credentialsMatcher = $cm and removedconfiguration related to password matcher
I also removed role and permission check from java code.
As i have just started with shrio it's bit difficult to understand flow at start.
Though it can help some one in future.
Thanks

adding authentification header to client stub axis2

I built the wsdl-client-stub based on xmlbeans. Now I got stuck adding a custom header for authentification using xmlbeans since xmlbeans stubs are lacking the necessary Classes(?)
Actually, the header should look like:
<SOAP-ENV:Header>
<ns2:verifyingToken>
<UserID>9</UserID>
<Token>29438094lkjslfkjlsdkjf</Token>
</ns2:verifyingToken>
</SOAP-ENV:Header>
So I tried as fallback going in between stub and ServiceClient:
ServiceClient sc = stub._getServiceClient();
OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMElement omElement = omFactory.createOMElement(new QName("SOAP-ENV", "Header", "ver"), null);
OMElement omElementVeri = omFactory.createOMElement(new QName("", "verifyingToken", ""), omElement);
OMElement omElementUser = omFactory.createOMElement(new QName("", "UserID", ""), omElementVeri);
omElementUser.setText(""+userid);
OMElement omElementPass = omFactory.createOMElement(new QName("", "Token", ""), omElementVeri);
omElementPass.setText(""+token);
sc.addHeader(omElement);
eclipse is raising errors saying:
The method createOMElement(String, OMNamespace) in the type OMFactory is not applicable for the arguments (QName, null)
- The constructor QName(String, String, String) is undefined
Does anyone has a hint, what I should fix, to get this to work.
I really appreciate your help,
Alex
ServiceClient client = stub._getServiceClient();
SOAP11Factory factory = new SOAP11Factory();
OMNamespace SecurityElementNamespace = factory.createOMNamespace("http://schemas.xmlsoap.org/ws/2002/12/secext", "wss");
OMElement usernameTokenEl = factory.createOMElement("UsernameToken", SecurityElementNamespace);
OMElement usernameEl = factory.createOMElement("Username", SecurityElementNamespace);
usernameEl.setText("123");
usernameTokenEl.addChild(usernameEl);
OMElement passwordEl = factory.createOMElement("Password", SecurityElementNamespace);
passwordEl.setText("123");
usernameTokenEl.addChild(passwordEl);
SOAPHeaderBlockImpl block = new SOAP11HeaderBlockImpl("Security", SecurityElementNamespace, factory);
block.addChild(usernameTokenEl);
client.addHeader(block);