Anonymous Login to Open fire With Strophe - openfire

I want to login to Openfire Server anonymously. I have tried with null username and password but not able to login. I have used Strophe on client side. Please Help me and give any suggestions. Thanks in advance..

First of all from openfire admin panel add such property
xmpp.auth.anonymous true
Suppose your domain is test.com
var c = new Strophe.Connection("/http-bind/"); //if localhost
c.connect("test.com",null,function(constatus){
console.log(constatus);
if(constatus==5){//connected
c.addHandler(function(message){console.log(message);}, null, "message", "chat");
c.send($pres());
}
});
that's all on client side!
I've implemented PacketInterceptor to see all packets
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException {
if(packet instanceof Presence){
Presence presence = (Presence) packet;
log.info("Presence:"+presence.toXML());
Message msg = new Message();
msg.setType(Type.chat);
msg.setFrom("admin#test.com");
msg.setBody("Hello from server");
session.process(msg);
}
}

Related

How to send message to a specific user using SignalR

I'm trying to send a message using SignalR and it works if I send to everybody, but not to s specific user. I tried to use the ConnectionId that in theory should be unique, but every time I tried to use the same connectionId that I received by the client, it doesn't work.
The server-side:
public async Task SendMessage(string user, string message)
{
var a = Context.UserIdentifier;
await Clients.User(Context.ConnectionId).SendAsync("ReceiveMessage", user, message);
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
Trying to pass the same ConnectionId in context doesn't send the message, only when I call Clients.All
The client is an android app and I'm not sure if I should register something on my client-side.
hubConnection = HubConnectionBuilder.create("http://192.168.1.5:3000/notification").build()
hubConnection.start()
hubConnection.on<String, String>(
"ReceiveMessage",
Action2 { user: String?, message: String? ->
requireActivity().runOnUiThread(java.lang.Runnable {
Toast.makeText(
context,
"I'm here.",
Toast.LENGTH_LONG
).show()
})
},
String::class.java,
String::class.java
)
You should use
await Clients.Client(Context.ConnectionId).SendAsync("ReceiveMessage", message);
It should works well.
SignalR allows messages to be sent to a particular client connection, all connections associated with a specific user, as well as to named groups of connections. => await Clients. User(userId).
if you want to send message to specific user in SignalR, easiest way is the use Form authentication. Also you can use your custom session with form authentication. Right after creation your session code put this code. FormsAuthentication.SetAuthCookie (username.Trim (), false); Then in signalR you can use this line for send message to this user:

Xero API Allows connection but fails to redirect back, has an uncaughtreferenceerror: fbq is not defined

Upon running the program I am redirected to sign in with xero. Once I sign in I am able to choose an organization to allow access to the app
Upon clicking allow access I get redirected to the default "This site can't be reached" error page.
If I look at the console output when I click the button, for a few seconds an "uncaught reference error: fbq is not defined" is shown. Unfortunately it goes away before I can click on it.
Here is some of the relevant code:
void LoginToXero()
{
var xeroLoginUri = XeroService.GetLoginUri();
OpenBrowser(xeroLoginUri);
var listener = new HttpListener();
listener.Prefixes.Add(XeroService.CallbackUri);
listener.Start();
Console.WriteLine("Waiting for the browser to callback from Xero login page...");//Logs
var context = listener.GetContext();//Does not progress past here
//...
}
public static class XeroService
{
public static string CallbackUri => "xxxxxxxxxxxxx";
static string xeroState = Guid.NewGuid().ToString();
static string oAuth2Token = "";
static XeroClient xeroClient = new XeroClient(new XeroConfiguration
{
ClientId = "XXXXXXXXXXXXXX",
ClientSecret = "XXXXXXXXXXXXXXXXXXXX",
Scope = "openid payroll.employees",
CallbackUri = new Uri(CallbackUri)
});
public static string GetLoginUri()
{
xeroClient.xeroConfiguration.State = xeroState;
return xeroClient.BuildLoginUri();
}
}
Please note all sensitive data has been replaced by "XXXXXXXXX"
I have tested both localhost callback URI's (with specified ports) and custom ones that redirect to localhost via the host file on my machine
I have also tried running it on Windows 11 and Windows 10, both with the firewall enabled and then with it disabled
Any help would be greatly appreciated
The problem was that the listener and the App was set up for https, changing it to http and making sure there was an explicit port resolved the issue

Keycloak API: Getting specific message when user action is required

Im calling this API Keycloak endpoint
/auth/realms/master/protocol/openid-connect/token
to obtain the user token. But the response is
{
"error":"invalid_grant",
"error_description":"Account is not fully set up"
}
and status code 400.
This response is too ambiguous. How can I get more detailed response to know that i have to redirect the user to my custom "change password" page and how can i get the user token?
Login to Keycloak and check if there are any Required User Actions pending for the user
like (Update Password, Verify email, etc)
You can check Keycloak logs for more detail about the error
I had the same problem, so I used workaround. Workaround is Authentication SPI. I added new step into authentication flow like this:
#Override
public void authenticate(AuthenticationFlowContext context) {
var user = context.getUser();
var foundUpdatePasswordRequiredAction = user.getRequiredActionsStream()
.anyMatch(actionName -> UserModel.RequiredAction.UPDATE_PASSWORD.name().equals(actionName));
if (foundUpdatePasswordRequiredAction) {
context.getEvent().user(user);
context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "temporary_password", "Constant password is not set up");
context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
return;
}
context.success();
}
It means if user has required action and the action equals "UPDATE_PASSWORD" return my error code and my error message. It works good for me.

How to do Active Directory authentication in Razor (cshtml)

I am doing a simple website with Razor. Currently, I have database-based authentication that works, as follows:
In _AppStart.chtml:
WebSecurity.InitializeDatabaseConnection("db_connection",
"users", "id", "username", true);
In login.cshtml page:
username = Request["username"];
password = Request["password"];
if (WebSecurity.Login(username, password, true))
{
Response.Redirect("/admin");
}
else
{
errorMessage = "Login was not successful.";
}
In protected CSHTML pages, I have the following at the top of a page:
if (!WebSecurity.IsAuthenticated)
{
Response.Redirect("/login.cshtml");
}
Everything is pretty simple and works well. Now I would like to add authentication with AD. I don't know how to do it.
I came from the Java world with many years of experience. For this simple website, I do not need MVC architecture. I need simple things similar to the above (if possible). I need to do authentication just within the login.cshtml file. I googled a lot and am unable to find a tutorial (so that I can copy and paste) for what I need.
Any pointers or help is really appreciated!
Thanks and Regards
Update: This application sits on the internal network.
Update 2: Here is the code I have after successfully implemented X3074861X's code
if (IsPost)
{
username = Request["username"];
password = Request["password"];
var domain = "domain";
var host = "host";
var port = "389";
LdapConnection ldapConnection = new LdapConnection(host + ":" + port);
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(username, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// this is where the authentication occurs
ldapConnection.Bind(networkCredential);
//check local database to make sure the user is one of we allowed
if (WebSecurity.Login(username, "fixed-password, just to check whether someone is on the list of allowed people", true))
{
Response.Redirect("/admin");
}
else
{
errorMessage = "Login was not successful.";
}
}
}
catch (LdapException exception)
{
//Authentication failed, exception will dictate why
errorMessage = "Login was not successful.";
}
Some explanation. I dont have control over the AD and so I can only authenticate users against it. I still have a little local database that indicates who can access the app. Everyone with access to the app has the same rights.
Thanks and credit goes to X3074861X.
Since this is an internal application, and you're looking for something simple, I would consider writing a single class to do the Active Directory authentication. You're going to need a couple things though, in order for this to work :
A reference to System.DirectoryServices.Protocols in your project.
The IP or DNS name of your Active Directory server. We'll call it host in the code below.
The port it's running on (LDAPS will be port 636, basic LDAP will be port 389). We'll call it port in the code below.
The Domain to which your users belong. We'll call it domain in the code below.
Now that you have that, you can wire this up to check the credentials from the request against your AD instance. I would try something like this :
// the username and password to authenticate
username = Request["username"];
password = Request["password"];
// define your connection
LdapConnection ldapConnection = new LdapConnection("host:port");
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(username, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// authenticate the user
ldapConnection.Bind(networkCredential);
}
catch (LdapException ldapException)
{
//Authentication failed, exception will dictate why
}
}
Also, in the same way you'd communicate an authorization issue before, the ldapException can tell you why the call failed. If you want to display custom messaging, I would check the LdapException.ErrorCode property, and maybe create a case statement of return messages based on the error codes.
Or, you could just output LdapException.Message directly to the page - either way, that will at least dictate to the user why their login didn't work.

disconnect client from server side signalr

I'm using SignalR 1 with MVC4 C# web application with form authentication.
I have a code in my layout page in JavaScript :
$(documnet).ready(function(){
connect to hub code ...
})
I want to disconnect a user form the hub and start connect again after he does a login and validate ok.
I want to do it from server side inside my account controller and method :
public ActionResult LogOn(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (System.Web.Security.Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
....here , disconnect from hub
....to make the user reconnect
}
The reason I want to do it is because SignalR throws an error if user changed to authenticated after login and the connection remains . The error is:
The connection id is in the incorrect format.
You cannot stop and start SignalR connections from the server. You will need to call
$.connection.hub.stop(); //on the client before the user attempts to log on and then call
$.connection.hub.start(); //after the log on attempt has completed.
One way you could do what you ask is to write a disconnect event on your client that the server can call through SignalR. Maybe something somewhat like this:
myHub.client.serverOrderedDisconnect = function (value) {
$.connection.hub.stop();
};
Then, on the server, something like this:
Clients.Client(Context.ConnectionId).serverOrderedDisconnect();
If someone is still looking for solution(SignalR version 2.4.1):
GlobalHost.DependencyResolver.Resolve<ITransportHeartbeat>().GetConnections().First(c => c.ConnectionId == "YourId").Disconnect();
Try controlling everything from javascript. The following is a logout example, login would be similar.
From http://www.asp.net/signalr/overview/security/introduction-to-security:
If a user's authentication status changes while an active connection
exists, the user will receive an error that states, "The user identity
cannot change during an active SignalR connection." In that case, your
application should re-connect to the server to make sure the
connection id and username are coordinated. For example, if your
application allows the user to log out while an active connection
exists, the username for the connection will no longer match the name
that is passed in for the next request. You will want to stop the
connection before the user logs out, and then restart it.
However, it is important to note that most applications will not need
to manually stop and start the connection. If your application
redirects users to a separate page after logging out, such as the
default behavior in a Web Forms application or MVC application, or
refreshes the current page after logging out, the active connection is
automatically disconnected and does not require any additional action.
The following example shows how to stop and start a connection when
the user status has changed.
<script type="text/javascript">
$(function () {
var chat = $.connection.sampleHub;
$.connection.hub.start().done(function () {
$('#logoutbutton').click(function () {
chat.connection.stop();
$.ajax({
url: "Services/SampleWebService.svc/LogOut",
type: "POST"
}).done(function () {
chat.connection.start();
});
});
});
});
You can the hub context to abort() the connection directly in .Net Core
Context.Abort();
See the method below
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.signalr.hubcallercontext.abort
Try this:
public ActionResult LogOn(LoginModel model, string returnUrl) {
if (ModelState.IsValid) {
if (System.Web.Security.Membership.ValidateUser(model.UserName, model.Password)) {
FormsAuthentication.SetAuthCookie(model.UserName, false);
connection.Stop();
}
}
Assuming your connection handle is connection. The challenge is accessing a handle to your connection object in your Action Method.
Copy and paste the following function into your Hub
Use HttpContext.Current.Response.End();
to force the client to disconnect in your hub