Use encrypted password for logging in open fire through jsxc - openfire

I'm using JSXC as a client side chat solution so i need to pass my login details to server to do the login process,
jsxc.init({
xmpp: {
url: 'http://hasan-pc:7070/http-bind/'
},
root: '/MAM/resources/assets/global/jsxc',
autoLang: false,
defaultLang: 'fr'
});
$(function(){
var myItems;
$.getJSON('resources/assets/global/jsxc/test.json', function(data) {
myItems = data;
jsxc.storage.setItem('debug', false);
var rid= ''+Math.random()+'';
rid=rid.substr(2, 12)
var username = myItems.username;
var password = myItems.password;
var domain = myItems.domain;
var jid = username + '#'+domain;
jsxc.start(jid , password);
}).error(function(data) {
console.log("Error!");
});;
});
I need to know how can i send a encrypted password and validate it server-side in openfire, which class in open fire is the listener then i can change the behavior.
and i would be happy if anyone else has a better idea to have an encrypted login.
Thank you for your help!!

Related

IdentityServer4 authenticating against an external api

We have a requirement to authenticate users in IdentityServer4 against an external API. The scenario works like this:
User visits a Javascript client application and clicks the login button to redirect to IdentityServer login page (exact same client as provided in the docs here
User enters their username (email) and password
IdentityServer4 connects to an external API to verify credentials
User is redirected back to the JavaScript application
The above process works perfect when using the TestUsers provided in the QuickStarts. However, when an API is used, the login page resets and does not redirect the user back to the JavaScript client. The only change is the below code and a custom implementation of IProfileService.
Below is the custom code in the login action (showing only the relevant part):
var apiClient = _httpClientFactory.CreateClient("API");
var request = new HttpRequestMessage(HttpMethod.Post, "/api/auth");
var loginModel = new LoginModel
{
Email = model.Email,
Password = model.Password
};
var content = new StringContent(JsonConvert.SerializeObject(loginModel),
Encoding.UTF8, "application/json");
request.Content = content;
HttpResponseMessage result = await apiClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
var loginStatus = JsonConvert.DeserializeObject<ApiLoginStatus>(
await result.Content.ReadAsStringAsync());
if (loginStatus.LoginSuccess)
{
await _events.RaiseAsync(new UserLoginSuccessEvent(model.Email, model.Email, loginStatus.Name, clientId: context?.ClientId));
AuthenticationProperties props = null;
if (AccountOptions.AllowRememberLogin && model.RememberLogin)
{
props = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
};
};
var user = new IdentityServerUser(loginStatus.SubjectId)
{
DisplayName = loginStatus.Name
};
await HttpContext.SignInAsync(user, props);
if (context != null)
{
if (await _clientStore.IsPkceClientAsync(context.ClientId))
{
return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
}
return Redirect(model.ReturnUrl);
}
The code actually hits the return View() path, but for some reason it resets and the login page is shown again.
Code in Startup.cs:
var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients)
.AddProfileService<ProfileService>()
.AddDeveloperSigningCredential();
Code in ProfileService.cs:
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var profile = await GetUserProfile(context.Subject.GetSubjectId());
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, profile.Email),
new Claim(ClaimTypes.Name, profile.Name)
};
context.IssuedClaims.AddRange(claims);
}
public async Task IsActiveAsync(IsActiveContext context)
{
var profile = await GetUserProfile(context.Subject.GetSubjectId());
context.IsActive = (profile != null);
}
There are multiple sources online that show how to user a custom store for authentication, but they all seem to use ResourceOwnerPasswordValidator. If someone could point out what is missing here, it would help greatly. Thanks.
So the issue turned out to be very simple. We had missed removing the builder.AddTestUsers(TestUsers.Users) line when setting up IdentityServer in Startup.cs.
Looking at the code here, it turned out that this line was overriding our profile service with the test users profile service. Removing that line solved the problem.

AWS cognito: Auto login after registration confirmation

I am using the JavaScript SDK of AWS Cognito (http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html).
When a new user completes registration confirmation, the documentation says the user is now ready to sign in. Is it possible to automatically sign in the user at this time?
For eg., after confirmation when I use the following I get null:
userPool.getCurrentUser();
If this is the intended behavior, are there any ways to sign in the user without explicitly asking the user again?
I know this is not a good idea, one thing I can think of is to save the user credentials in local storage and use them after confirmation to automatically sign in. Any other ideas better than this?
Upon user signup, your backend will be receiving users credentials, which you can use to generate the JWT token. Then you can add the JWT token in the same response, which can be use by the browser client to request authorized endpoints.
Example:
AWSCognito.config.region = 'us-east-1'; //This is required to derive the endpoint
var poolData = {
UserPoolId: 'us-east-1_TcoKGbf7n',
ClientId: '4pe2usejqcdmhi0a25jp4b5sh3'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var attributeList = [];
var dataEmail = {
Name: 'email',
Value: 'email#mydomain.com'
};
var authenticationData = {
Username: 'username',
Password: 'password',
};
var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail);
attributeList.push(attributeEmail);
userPool.signUp(authenticationData.Username, authenticationData.Password, attributeList, null, function (err, result) {
if (err) {
alert(err);
return;
}
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var userData = {
Username: authenticationData.Username,
Pool: userPool
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
/*Use the idToken for Logins Map when Federating User Pools with Cognito Identity or when passing through an Authorization Header to an API Gateway Authorizer*/
console.log('idToken + ' + result.idToken.jwtToken);
/*Return the result.idToken.jwtToken with the response*/
},
onFailure: function (err) {
alert(err);
},
});
});

Chrome extensions: issue with identity.launchWebAuthFlow

I'm tring to login via my own service. This is what I have now:
manifest.json
"background": {
"scripts": ["background.js"]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({
url: 'index.html'
});
});
index.html is where all the extension's logic resides. Here I have a function that starts authentication process:
function goLogin(callback)
{
var redirectUrl = chrome.identity.getRedirectURL('receiveToken');
chrome.identity.launchWebAuthFlow({
url: 'http://todolist.dev/app_dev.php/login?response_type=token&redirect_url=' + redirectUrl,
interactive: true
}, function(redirectUrl) {
if (!redirectUrl) {
return;
}
// Get an access token from the url and save it in localStorage
var queryString = decodeURIComponent(redirectUrl.substr(redirectUrl.indexOf('?') + 1));
var params = queryString.split('&');
var accessToken = null;
for (var i = 0; i < params.length; i++) {
params[i] = params[i].split('=');
if (params[i][0] == 'access_token') {
accessToken = params[i][1];
break;
}
}
localStorage.setItem('accessToken', accessToken);
callback();
});
}
The problem is that the popup with the service's login page sometimes doesn't open or opens and closes automatically with the response that the user didn't approve access. Sometimes when the popup opens and I try to login with wrong credentials several times, the popup closes automatically as well (with the same "you didn't approve access" response). In the backend I don't have any restrictions to a number of login attempts.
In the backend I have a FOSUserBundle with overridden AuthenticationSuccessHandler (it does what the default success handler does + returns an access token).

Attempt to reuse auth token to connect xamarin app to azure fails

This initial login succeeds:
public static MobileServiceClient MOBILE = new MobileServiceClient("https://myapp.azure-mobile.net/",myApplicationKey);
MobileServiceAuthenticationProvider GOOGLEPROVIDER = MobileServiceAuthenticationProvider.Google;
private async Task Connect() {
var USER = await MOBILE.LoginAsync(this, GOOGLEPROVIDER);
var CACHE = new Dictionary<string, string> { { "token", USER.MobileServiceAuthenticationToken } };
var ACCOUNT = new Account(USER.UserId, CACHE);
var STORE = AccountStore.Create(this);
STORE.Save(ACCOUNT, "Google");
}
but then this attempt to reuse the token to reconnect without a login page fails:
public async Task Reconnect() {
var STORE = AccountStore.Create(this);
var token = STORE.FindAccountsForService("Google").ToArray()[0].Properties["token"];
// token seems ok
var jsonToken = new JObject();
jsonToken.Add("access_token", token);
var USER = await MOBILE.LoginAsync(MobileServiceAuthenticationProvider.Google, jsonToken); // BOOM!
}
... with the following message: "The POST Google login request must contain both code and id_token in the body of the request."
What I am getting wrong here?
The token you use in the code, viz.
var CACHE = new Dictionary { { "token",USER.MobileServiceAuthenticationToken } };
The MobileServiceAuthenticationToken above is a token specific to MobileServices and cannot be used in the LoginAsync method (LoginAsync method requires a Google OAuth token.)
Please see this Get User Info from Google Api Using Azure Mobile Services for Xamarin Android

Logout from external login service (Gmail, facebook) using oauth

I have an ASP.NET MVC 4 application that allows users to login with external service like Gmail.
So far, the user is able to login and navigate inside the application. But The problem is in logout. I have a button to logout that request call the controller action LogOff() inside my AccountController. Inside that method, how can I logout if the user is authenticated via oauth?
With a local account, I use:
public ActionResult LogOff()
{
WebSecurity.Logout();
return RedirectToAction("Login", "Account");
}
But with oauth I don't see anything similar...
I think I need to clear some kind of cookie but I don't know how...
Based on this, I implemented the following client-side solution (I'm asking previously if the user want to logout also in the provider):
//get accountType, accessToken, redirectUrl and clientID
var accountType = ...;
var accessToken = ...;
var redirectUrl = ...;
var clientID = ...;
$("#logoutConfirmButton").on('click', function () {
externalLogout();
});
function externalLogout() {
var url, params;
if (accountType== "facebook") {
url = "https://www.facebook.com/logout.php";
params = {
next: redirectUrl,
access_token: encodeURIComponent(accessToken)
};
performCallLogout(url, params, accountType);
} else if (accountType== "google") {
url = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout";
params = {
next: redirectUrl
}
performCallLogout(url, params, accountType);
} else if (accountType == "microsoft") {
url = "https://login.live.com/oauth20_logout.srf";
params = {
clientId: clientID,
redirectUrl: redirectUrl
}
performCallLogout(url, params, accountType);
}
}
function performCallLogout(url, params, accountType) {
if (accountType == "facebook") {
window.location.href = url + "?next=" + params.next + "&access_token=" + params.access_token;
} else if (accountType == "google") {
window.location.href = url + "?continue=" + params.next;
} else if (accountType == "microsoft") {
window.location.href = url + "?client_id=" + params.clientId + "&redirect_url=" + params.redirectUrl;
}
}
Hope this help someone.
WebSecurity.Logout(); will log out the user even if they authenticated through OAuth.
If you want to be sure the token does not persist after logout you can call
Session.Remove("facebooktoken"); //Facebook example
The information is from this webpage. Some more details worth reading on there too.
Sounds like you want to log the user out of the source authenticating site? Only the authenticating site can delete/modify its cookies.
The solution will be to redirect the user to the logout page for the authenticating site, or use an API script to log the user out (if one exists for that site.) You could use a form with the "target" attribute to open a new window if you don't want the main browser window to redirect.
FaceBook, for example, has an API call:
FB.logout(function(response) {
// user is now logged out
});
The MVC FaceBook client has a method GetLogoutUrl, too, which returns a URL you could use on the server side.