node_redis auth with pipeline - node-redis

With the following code, is there any situation that AUTH can be pipelined with other commands in node_redis?
This function is called every time node server accepts a request. In the callback function, other redis commands like get/set are issuing.
var client = null;
var getRedisClient = function(name, callback) {
var redis = require('redis');
var redisInfo = getRedisInfo(name);
if (client == null || client.connected == false) {
if (client != null) {
client.end();
client = null;
}
client = redis.createClient(redisInfo.port, redisInfo.host);
if (redisInfo.password != '') {
client.auth(redisInfo.password, function(err){
if (err) {
client.end();
client = null;
}
callback(err, client);
});
} else {
callback('', client);
}
} else {
callback('', client);
}
};
What's the right way to send auth to redis server using node_redis?

Related

Do I still need users in user pool if I want to work Custom Authentication workflow in AWS Cognito?

I have a webservice which validates user/pwd and returns true/false (valid/invalid). I am trying to leverage Custom Authentication Workflow of AWS Cognito to integrate with the webservice.
I read through the docs and came across the define, create and verify lambda triggers and I tried those as follows:
Define trigger:
exports.handler = async (event) => {
if (!event.request.session || event.request.session.length === 0) {
event.response.challengeName = "CUSTOM_CHALLENGE";
event.response.failAuthentication = false;
event.response.issueTokens = false;
} else if (event.request.session.length === 1) {
// If we passed the CUSTOM_CHALLENGE then issue token
event.response.failAuthentication = false;
event.response.issueTokens = true;
} else {
// Something is wrong. Fail authentication
event.response.failAuthentication = true;
event.response.issueTokens = false;
}
return event;
};;
Create Trigger:
exports.handler = async (event) => {
if (event.request.challengeName == 'CUSTOM_CHALLENGE') {
event.response.publicChallengeParameters = {};
event.response.privateChallengeParameters = {};
}
return event;
}
Verify Trigger:
exports.handler = async (event, context) => {
//call webservice using "event.userName" and "event.request.challengeAnswer" (password)
var result = <bool-result-received-from-webservice>
event.response.answerCorrect = result;
return event;
};
The JS client looks like this:
Amplify.configure({
Auth: {
region: 'dd',
userPoolId: 'eeee',
userPoolWebClientId: 'ffff',
authenticationFlowType: 'CUSTOM_AUTH'
}
})
let user = await Auth.signIn(username)
.then(u => {
console.log(u); //(1) TOKENS ARE ALREADY CREATED HERE WITHOUT VERIFYING PASSWORD. NOT SURE.
if (u.challengeName === 'CUSTOM_CHALLENGE') {
console.log("responding to challenge..");
// to send the answer of the custom challenge
Auth.sendCustomChallengeAnswer(u, password)
.then(u2 => {
console.log("after responding to challenge...");
console.log(u2); //(2) NEW TOKENS ARE CREATED HERE. NOT SURE.
return u2;
})
.catch(err => {
console.log("ERROR with Challenge:");
console.log(err);
});
} else {
console.log("no challenge needed..");
return u;
}
})
.catch(err => {
console.log("ERROR with sign-in:..");
console.log(err);
});
I mentioned 1 and 2 in the comments above. Not sure if it's behaving correctly.
If the username is not in the "users" list of "user pool", it throws it as invalid login. Is it possible to validate username/password only through webservice having no "users" in the "user pool"?

Flutter:400 Bad request when i make a request to gmail of googleapis

I want to get a respond from Gmail of googleapis so I use a package:googleapis/gmail/v1.dart and make a code service.users.messages.list(_currentUser.email, q:'from:$searchingWord'); get list of email filtered by q:.
But there is a 400 Bad request, So, after debugging I found this url https://www.googleapis.com/gmail/v1/users/(myEmail)/messages?q=from%3Anoreply%40github.com&alt=json.
It's a bad request, so it's a url problem, but I'm not sure what's wrong.
I need your help.
The code where the problem occurred
Future<gMail.GmailApi> getGMailApi() async {
return gMail.GmailApi(await getGoogleClient());
}
Future<AuthClient> getGoogleClient() async {
return await clientViaServiceAccount(await getCredentials(), [
'email',
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.readonly'
]);
}
Future<ServiceAccountCredentials> getCredentials() async {
if (credentials == null) {
credentials = ServiceAccountCredentials.fromJson(await rootBundle
.loadString('android/app/todoapp-270005-c7e7aeec11f7.json'));
}
print(credentials);
return credentials;
}
Future<void> handleGetMail(String searchingWord) async {
gMail.GmailApi service = (await getGMailApi());
gMail.ListMessagesResponse response =
await service.users.messages.list(_currentUser.email, q:'from:$searchingWord');
List<gMail.Message> messages;
while (response.messages != null) {
messages.addAll(response.messages);
if (response.nextPageToken != null) {
String pageToken = response.nextPageToken;
response = await service.users.messages
.list(_currentUser.email, q:'from:$searchingWord', pageToken: pageToken);
} else {
break;
}
}
for (gMail.Message message in messages) {
print(message.toString());
}
}

Cortana - OAuth 2 connected service

We have created an OAuth2 provider as an app service as given in below example.
https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
Step 2:
We need to configure this endpoints to Cortana connected service OAuth2 end points to get the access token from Cortana app
Cortana Auth Config
Sample Code in the Auth provider authorize function is below:
public ActionResult Login()
{
var authentication = HttpContext.GetOwinContext().Authentication;
if (Request.HttpMethod == "POST")
{
var isPersistent = !string.IsNullOrEmpty(Request.Form.Get("isPersistent"));
if (!string.IsNullOrEmpty(Request.Form.Get("submit.Signin")))
{
authentication.SignIn(
new AuthenticationProperties { IsPersistent = isPersistent },
new ClaimsIdentity(new[] { new Claim(ClaimsIdentity.DefaultNameClaimType, Request.Form["username"]) }, "Application"));
}
}
return View();
// Response.End();
}
Authorize
public ActionResult Authorize()
{
if (Response.StatusCode != 200)
{
return View("AuthorizeError");
}
var authentication = HttpContext.GetOwinContext().Authentication;
var ticket = authentication.AuthenticateAsync("Application").Result;
var identity = ticket != null ? ticket.Identity : null;
if (identity == null)
{
authentication.Challenge("Application");
return new HttpUnauthorizedResult();
}
var scopes = (Request.QueryString.Get("scope") ?? "").Split(' ');
if (Request.HttpMethod == "POST")
{
if (!string.IsNullOrEmpty(Request.Form.Get("submit.Grant")))
{
identity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType);
foreach (var scope in scopes)
{
identity.AddClaim(new Claim("urn:oauth:scope", scope));
}
authentication.SignIn(identity);
}
//if (!string.IsNullOrEmpty(Request.Form.Get("submit.Login")))
//{
// authentication.SignOut("Application");
// authentication.Challenge("Application");
// return new HttpUnauthorizedResult();
//}
}
return View();
}
I want to change this code in a way that it could be able to send back data to Cortana channel. Please let know your suggestions.
Thanks

HTTP basic authentication method to authenticate the mobile client through Datapower

I am using Mobilefirst Platform 8.0 for my app development.
How can we use HTTP basic authentication method to authenticate the mobile client through datapower. Please help me out with challnegHandler sample code.
I tried the below code in challengeHandler but Datapower always returning 401.
var DataPowerChallengeHandler = function() {
var dataPowerChallengeHandler = WL.Client.createGatewayChallengeHandler("LtpaBasedSSO");
dataPowerChallengeHandler.canHandleResponse = function(response) {
if (!response || response.responseText === null) {
return false;
}
if (response.status=="401") {{
return true;
}
return false;
};
dataPowerChallengeHandler.handleChallenge = function(response) {
document.getElementById('result').style.display = 'none';
document.getElementById('auth').style.display = 'block';
};
dataPowerChallengeHandler.submitLoginFormCallback = function(response) {
var isLoginFormResponse = dataPowerChallengeHandler.canHandleResponse(response);
if (isLoginFormResponse) {
dataPowerChallengeHandler.handleChallenge(response);
} else {
document.getElementById('result').style.display = 'block';
document.getElementById('auth').style.display = 'none';
dataPowerChallengeHandler.submitSuccess();
}
};
document.getElementById("AuthSubmitButton").addEventListener("click", function() {
var username = document.getElementById('txtusername').value;
var password = document.getElementById('txtpassword').value;
var mystring = convertBase64(username+":"+password);
var headerString = "Basic "+ mystring;
WL.Client.addGlobalHeader("Authorization",headerString);
dataPowerChallengeHandler.submitSuccess();
});
document.getElementById("logout").addEventListener("click", function() {
WLAuthorizationManager.logout("LtpaBasedSSO").then(
function() {
WL.Logger.debug("logout onSuccess");
alert("Success logout");
},
function(response) {
WL.Logger.debug("logout onFailure: " + JSON.stringify(response));
});
});
document.getElementById('AuthCancelButton').addEventListener("click",function(){
document.getElementById('result').style.display = 'block';
document.getElementById('auth').style.display = 'none';
dataPowerChallengeHandler.cancel();
});
return dataPowerChallengeHandler;
};
Your gateway challenge handler code is improper and causing all these issues.
canHandleResponse method is used to determine whether it is a challenge thrown by datapower or not. Your client code is returning true whenever there is a 401 challenge. This will return true even though for non-datapower challenges which should be corrected.
and handleChallenge is explicitly getting called in submitLoginFormCallback method which is wrong. handleChallenge will get called by SDK only when canHandleResponse method returns true.
Kindly go through this tutorial for more information on how to use gateway challenge handler in your client application.

Worklight - How to check if a client is already logged in

LoginViewModel.js
function login(){
var username='worklight';
var password = 'worklight';
var invocationData = {
adapter : "AuthenticationAdapter",
procedure : "submitAuthentication",
parameters : [ username, password ]
};
adapterAuthRealmChallengeHandler.submitAdapterAuthentication(invocationData, {});
AdapterAuthRealmChallengeProcessor.js
var adapterAuthRealmChallengeHandler = WL.Client.createChallengeHandler("AdapterAuthRealm");
adapterAuthRealmChallengeHandler.isCustomResponse = function(response) {
if (!response || !response.responseJSON || response.responseText === null) {
return false;
}
if (typeof(response.responseJSON.authRequired) !== 'undefined'){
return true;
} else {
return false;
}
};
adapterAuthRealmChallengeHandler.handleChallenge = function(response){
var authRequired = response.responseJSON.authRequired;
if (authRequired == true){
window.location = "#login";
alert(response.responseJSON.errorMessage);
} else if (authRequired == false){
adapterAuthRealmChallengeHandler.submitSuccess();
window.location = "#Home";
}
};
AuthenticationAdapter-impl.js
function onAuthRequired(headers, errorMessage){
errorMessage = errorMessage ? errorMessage : null;
return {
authRequired: true,
errorMessage: errorMessage
};
}
function submitAuthentication(username, password){
var userIdentity = {
userId: username,
displayName: username,
attributes: {
foo: "bar"
}
};
WL.Server.setActiveUser("AdapterAuthRealm", userIdentity);
return {
authRequired: false
};
}
I am not able to set setActiveUser. How to set it and get it. Above wat I have to done for maintaining session. Is it right way to do it. Sometimes I got error Illegal State: Cannot change identity of an already logged in user in realm 'Adapter AuthRealm'. The application must logout first. If I tried to set it null first then it causes my application to enter an infinite loop of attempting to authenticate. Any idea why I would see this behavior?
Anything I am doing wrong?
please help mi out.
Check the SO answer for Worklight logout does not clear active user
Try reloading app onSuccess of Logout.
WL.Client.logout("AdapterAuthRealm",{
onSuccess: function(){ WL.Client.reloadApp(); },
onFailure: function(){ WL.Logger.debug("Error on logout");}
});
And you can check realm is authenticated or not by using wl client Java script API
WL.Client.isUserAuthenticated("AdapterAuthRealm");