presence control in asp.net web applications - asp.net

I've managed to implement the Name.NameCtrl.1 active x used in sharepoint in my own custom built apps for presence. All is working fine and I'm updating presence status correctly based on a users status on Office Comunication Server. However I'm not getting any other details on the user propulated in the presence control like it does in SharePoint. All I get is the sip address in the email field (rather than the real default email address in AD) and a link to schedule a meeting.
Can anyone tell me how to get the control to populate with details from AD (dept, email, phone etc) like it does in sharepoint?? Also I don't get an organization tab in the control like sharepoint.
Any ideas?
Thanks,
Keeney

NameCtrl gets the majority of its data from the running instance of Communicator (or Lync, if you're using that) on the client machine. No data is directly pulled back from SharePoint. To have NameCtrl work properly on your web pages, you need to make sure that:
Communicator (or Lync) is running on the client, and signed in
The web page you are calling NameCtrl from is in the Intranet or Trusted Sites zone in your browser
The recommended pattern is to call PresenceEnabled on the NameCtrl object before calling any other methods - if this returns false, then one (or both) of the above prereqs is false. The code below generally works for me
<script>
var sipUri = "your.contact#your.domain.com";
var nameCtrl = new ActiveXObject('Name.NameCtrl.1');
if (nameCtrl.PresenceEnabled)
{
nameCtrl.OnStatusChange = onStatusChange;
nameCtrl.GetStatus(sipUri, "1");
}
function onStatusChange(name, status, id)
{
// This function is fired when the contacts presence status changes.
// In a real world solution, you would want to update an image to reflect the users presence
alert(name + ", " + status + ", " + id);
}
function ShowOOUI()
{
nameCtrl.ShowOOUI(sipUri, 0, 15, 15);
}
function HideOOUI()
{
nameCtrl.HideOOUI();
}
</script>
<span onmouseover="ShowOOUI()" onmouseout="HideOOUI()" style="border-style:solid">Your Contact</span>
In case you haven't already seen it, there is a good(ish) NameCtrl reference here

I think in SharePoint, the control is populated with data that exists in the user profile service. If you want this in a non-sharepoint ASP.NET web app, then you'd have to build a repository of user profile details from AD (and cache it!) which your control will look to to display that information.

Related

Adding a button for google signin using f#/fable/asp.net/react

I'm working with the SAFE stack (https://safe-stack.github.io/) and through the example dojo. It's great so far.
I'd like to extend the example to include a button to login/auth via Google. So I looked at an example on the Google website (https://developers.google.com/identity/sign-in/web/build-button). And then I had a look how to do authentication using ASP.NET (https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-2.1&tabs=aspnetcore2x) As a result I ended up confused as to how to integrate this into a SAFE project. Can someone tell me what they would do? SHould I be trying to use ASP.NET Identity or should I be using the JWT approach? I don't even know if they are the same since I'm very new to web frameworks.....
The other question I have is how would one inject raw Javascript into the client side of a SAFE project. The google example above shows raw JS/CSS/HTML code? Should I be injecting that as is or should I look in React for some button that does this and map that idea back through Fable?
Setting up OAuth
The easiest way to use Google OAuth is to wait until the next release of Saturn, at which point Saturn will include the use_google_oauth feature that I just added. :-) See the source code if you're interested in how it works, though I'm afraid you can't implement this yourself with use_custom_oauth because you'll run into a type error (the underlying ASP.NET code has a GoogleOptions class, and use_custom_oauth wants an OAuthOptions class, and they aren't compatible).
To use it, add the following to your application CE:
use_google_oauth googleClientId googleClientSecret "/oauth_callback_google" []
The last parameter should be a sequence of string * string pairs that represent keys and values: you could use a list of tuples, or a Map passed through Map.toSeq, or whatever. The keys of that sequence are keys in the JSON structure that Google returns for the "get more details about this person" API call, and the values are the claim types that those keys should be mapped to in ASP.NET's claims system. The default mapping that use_google_oauth already does is:
id → ClaimTypes.NameIdentifier
displayName → ClaimTypes.Name
emails[] (see note) → ClaimTypes.Email
Those three are automatically mapped by ASP.NET. I added a fourth mapping:
avatar.url → `"urn:google:avatar:url"
There's no standard ClaimTypes name for this one, so I picked an arbitrary URN. Caution: this feature hasn't been released yet, and it's possible (though unlikely) that this string might change between now and when the feature is released in the next version of Saturn.
With those four claim types mapped automatically, I found that I didn't need to specify any additional claims, so I left the final parameter to use_google_oauth as an empty list in my demo app. But if you want more (say you want to get the user's preferred language to use in your localization) then just add them to that list, e.g.:
use_google_oauth googleClientId googleClientSecret "/oauth_callback_google" ["language", "urn:google:language"]
And then once someone has logged in, look in the User.Claims seq for a claim of type "urn:google:language".
Note re: the emails[] list in the JSON: I haven't tested this with a Google account that has multiple emails, so I don't know how ASP.NET picks an email to put in the ClaimTypes.Email claim. It might just pick the first email in the list, or it might pick the one with a type of account; I just don't know. Some experimentation might be needed.
Also note that third-party OAuth, including GitHub and Google, has been split into a new Saturn.Extensions.Authorization package. It will be released on NuGet at the same time that Saturn's next version (probably 0.7.0) is released.
Making the button
Once you have the use_google_oauth call in your application, create something like the following:
let googleUserIdForRmunn = "106310971773596475579"
let matchUpUsers : HttpHandler = fun next ctx ->
// A real implementation would match up user identities with something stored in a database, not hardcoded in Users.fs like this example
let isRmunn =
ctx.User.Claims |> Seq.exists (fun claim ->
claim.Issuer = "Google" && claim.Type = ClaimTypes.NameIdentifier && claim.Value = googleUserIdForRmunn)
if isRmunn then
printfn "User rmunn is an admin of this demo app, adding admin role to user claims"
ctx.User.AddIdentity(new ClaimsIdentity([Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, "MyApplication")]))
next ctx
let loggedIn = pipeline {
requires_authentication (Giraffe.Auth.challenge "Google")
plug matchUpUsers
}
let isAdmin = pipeline {
plug loggedIn
requires_role "Admin" (RequestErrors.forbidden (text "Must be admin"))
}
And now in your scope (NOTE: "scope" will probably be renamed to "router" in Saturn 0.7.0), do something like this:
let loggedInView = scope {
pipe_through loggedIn
get "/" (htmlView Index.layout)
get "/index.html" (redirectTo false "/")
get "/default.html" (redirectTo false "/")
get "/admin" (isAdmin >=> htmlView AdminPage.layout)
}
And finally, let your main router have a URL that passes things to the loggedInView router:
let browserRouter = scope {
not_found_handler (htmlView NotFound.layout) //Use the default 404 webpage
pipe_through browser //Use the default browser pipeline
forward "" defaultView //Use the default view
forward "/members-only" loggedInView
}
Then your login button can just go to the /members-only route and you'll be fine.
Note that if you want multiple OAuth buttons (Google, GitHub, Facebook, etc) you'll probably need to tweak that a bit, but this answer is long enough already. When you get to the point of wanting multiple OAuth buttons, go ahead and ask another question.

Google reCAPTCHA response success: false, no error codes

UPDATE: Google has recently updated their error message with an additional error code possibility: "timeout-or-duplicate".
This new error code seems to cover 99% of our previously mentioned mysterious
cases.
We are still left wondering why we get that many validation requests that are either timeouts or duplicates. Determinining this with certainty is likely to be impossible, but now I am just hoping that someone else has experienced something like it.
Disclaimer: I cross posted this to Google Groups, so apologies for spamming the ether for the ones of you who frequent both sites.
I am currently working on a page as part of a ASP.Net MVC application with a form that uses reCAPTCHA validation. The page currently has many daily users.
In my server side validation** of a reCAPTCHA response, for a while now, I have seen the case of the reCAPTCHA response having its success property set to false, but with an accompanying empty error code array.
Most of the requests pass validation, but some keep exhibiting this pattern.
So after doing some research online, I explored the two possible scenarios I could think of:
The validation has timed out and is no longer valid.
The user has already been validated using the response value, so they are rejected the second time.
After collecting data for a while, I have found that all cases of "Success: false, error codes: []" have either had the validation be rather old (ranging from 5 minutes to 10 days(!)), or it has been a case of a re-used response value, or sometimes a combination of the two.
Even after implementing client side prevention of double-clicking my submit-form button, a lot of double submits still seem to get through to the server side Google reCAPTCHA validation logic.
My data tells me that 1.6% (28) of all requests (1760) have failed with at least one of the above scenarios being true ("timeout" or "double submission").
Meanwhile, not a single request of the 1760 has failed where the error code array was not empty.
I just have a hard time imagining a practical use case where a ChallengeTimeStamp gets issued, and then after 10 days validation is attempted, server side.
My question is:
What could be the reason for a non-negligible percentage of all Google reCAPTCHA server side validation attempts to be either very old or a case of double submission?
**By "server side validation" I mean logic that looks like this:
public bool IsVerifiedUser(string captchaResponse, string endUserIp)
{
string apiUrl = ConfigurationManager.AppSettings["Google_Captcha_API"];
string secret = ConfigurationManager.AppSettings["Google_Captcha_SecretKey"];
using (var client = new HttpClient())
{
var parameters = new Dictionary<string, string>
{
{ "secret", secret },
{ "response", captchaResponse },
{ "remoteip", endUserIp },
};
var content = new FormUrlEncodedContent(parameters);
var response = client.PostAsync(apiUrl, content).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
GoogleCaptchaResponse googleCaptchaResponse = JsonConvert.DeserializeObject<GoogleCaptchaResponse>(responseContent);
if (googleCaptchaResponse.Success)
{
_dal.LogGoogleRecaptchaResponse(endUserIp, captchaResponse);
return true;
}
else
{
//Actual code ommitted
//Try to determine the cause of failure
//Look at googleCaptchaResponse.ErrorCodes array (this has been empty in all of the 28 cases of "success: false")
//Measure time between googleCaptchaResponse.ChallengeTimeStamp (which is UTC) and DateTime.UtcNow
//Check reCAPTCHAresponse against local database of previously used reCAPTCHAresponses to detect cases of double submission
return false;
}
}
}
Thank you in advance to anyone who has a clue and can perhaps shed some light on the subject.
You will get timeout-or-duplicate problem if your captcha is validated twice.
Save logs in a file in append mode and check if you are validating a Captcha twice.
Here is an example
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'])
file_put_contents( "logfile", $verifyResponse, FILE_APPEND );
Now read the content of logfile created above and check if captcha is verified twice
This is an interesting question, but it's going to be impossible to answer with any sort of certainly. I can give an educated guess about what's occurring.
As far as the old submissions go, that could simply be users leaving the page open in the browser and coming back later to finally submit. You can handle this scenario in a few different ways:
Set a meta refresh for the page, such that it will update itself after a defined period of time, and hopefully either get a new ReCAPTCHA validation code or at least prompt the user to verify the CAPTCHA again. However, this is less than ideal as it increases requests to your server and will blow out any work the user has done on the form. It's also very brute-force: it will simply refresh after a certain amount of time, regardless of whether the user is currently actively using the page or not.
Use a JavaScript timer to notify the user about the page timing out and then refresh. This is like #1, but with much more finesse. You can pop a warning dialog telling the user that they've left the page sitting too long and it will soon need to be refreshed, giving them time to finish up if they're actively using it. You can also check for user activity via events like onmousemove. If the user's not moving the mouse, it's very likely they aren't on the page.
Handle it server-side, by catching this scenario. I actually prefer this method the most as it's the most fluid, and honestly the easiest to achieve. When you get back success: false with no error codes, simply send the user back to the page, as if they had made a validation error in the form. Provide a message telling them that their CAPTCHA validation expired and they need to verify again. Then, all they have to do is verify and resubmit.
The double-submit issue is a perennial one that plagues all web developers. User behavior studies have shown that the vast majority occur because users have been trained to double-click icons, and as a result, think they need to double-click submit buttons as well. Some of it is impatience if something doesn't happen immediately on click. Regardless, the best thing you can do is implement JavaScript that disables the button on click, preventing a second click.

Paypal Processing - Need to grab TransactionId, CorrelationId and TimeStamp

Current Project:
ASP.NET 4.5.2
MVC 5
PayPal API
I am using this example to build myself a PayPal transaction (and yes, my code is virtually identical), as I do not know of any other method that will return the three values in the title.
My main problem is that, the example I am utilizing is much more concise and compact than the one I used for a much older Web Forms application, and as such, I am unsure as to where or even how to grab the three values I need.
My initial thought was to do so right after the ACK, and indeed I was able to obtain the CorrelationId as well as the TimeStamp, but because this was prior to the user being carted off to PayPal’s site (sandbox in this case -- see the return new PayPalRedirect contained within the if), the TransactionId was blank. And in this example, PayPal explicitly redirects the user to a Success page without returning to the Action that sent the user to PayPal in the first place, and I am not seeing any GET values in the URL at all aside from the Token and the PayerId, much less ones that could provide me with the TransactionId.
Suggestions?
I have also looked at the following examples:
For ASP.NET Core, was unsure how to adapt to my current project particularly due to appsettings.json, but it looked quite well done. I really liked how the values were rolled up in lists.
For MVC 4, but I couldn’t find where ACK was being used to determine success or successwithwarning so I couldn’t hook into that.
I have also found the PayPal content to be like trying to drink from a fire hose at full blast -- not only was the content was hopelessly outdated (Web Forms code, FTW!) but there was also so many different examples it would have taken me days to determine which one was most appropriate to use.
Any assistance would be greatly appreciated.
Edit: my initial attempt at modifying the linked code has this portion:
values = Submit(values);
var ack = values["ACK"].ToLower();
if(ack == "success" || ack == "successwithwarning") {
using(_db = new ApplicationDbContext()) {
var updateOrder = await _db.Orders.FirstOrDefaultAsync(x => x.OrderId == order.OrderId);
if(updateOrder != null) {
updateOrder.OrderProcessed = false;
updateOrder.PayPalCorrelationId = values["CORRELATIONID"];
updateOrder.PayPalTransactionId = values["TRANSACTIONID"];
updateOrder.PayPalTimeStamp = values["TIMESTAMP"];
updateOrder.IPAddress = HttpContext.Current.Request.UserHostAddress;
_db.Entry(updateOrder).State = EntityState.Modified;
await _db.SaveChangesAsync();
}
}
return new PayPalRedirect {
Token = values["TOKEN"],
Url = $"https://{PayPalSettings.CgiDomain}/cgi-bin/webscr?cmd=_express-checkout&token={values["TOKEN"]}"
};
}
Everything within and including the using() is my added content. As I mentioned, the CorrelationId and the TimeStamp come through just fine, but I have yet to successfully obtain the TransactionId.
Edit 2:
More problems -- the transactions that are “successful” through the sandbox site (the ReturnUrl is getting called) aren’t reflecting properly on my Facilitator and Buyer accounts, even when I do payments straight from the buyer’s PayPal account (not using the Credit Card). I know I am supposed to see transactions in the Buyer’s account, either through the overall Dev account (Accounts -> Profile -> balance or Accounts -> Notifications) or through the Buyer’s account in the sandbox front end. And yet -- multiple transactions returning me to the ReturnUrl path, and yet no transactions in either.
Edit 3:
Okay, this is really, really weird. I have gone over all settings with a fine-toothed comb, and intentionally introduced errors to see where things should crap out. It turns out that the entire process goes swimmingly - except nothing shows up in my notifications and no amounts get moved between my different accounts (Facilitator and Buyer). It’s like all my transactions are going into /dev/null, yet the process is successful.
Edit 4: A hint!
In the sandbox, where Buyer accepts the transaction, there is a small note, “You will be able to review the transaction before completing it” or something like that -- suggesting that an additional page is not coming up and that the user is being uncerimoniously dumped back to the success page. Why the success page? No clue. But it’s happening.
It sounds like you are only doing the first part of the process.
Express Checkout consists of 3 API calls:
SetExpressCheckout
GetExpressCheckoutDetails
DoExpressCheckoutPayment
SEC generates a token, and then you redirect to PayPal where the user signs in and reviews the transactions before agreeing to pay.
They are then sent to the ReturnURL included in your SEC request, and this is where you'll call GECD in order to obtain all the buyer details that are now available since they signed in.
Using that data you can complete the final DECP request, which is what finalizes the procedure. No money is actually processed until this final call is completed successfully.

I can't get my account to authorise itself using linqtotwitter

I know this has been asked many times before, but I have used info from the linqtotwitter docs and examples along with other posts on here to get this far. I can get my new app to send a tweet, but only by letting it take me to twitters authorise page and me having to click the authorise button to continue.
The app itself is authorised fine, so I don't need my password each time, it's just the use of the app that it wants permission for.
I know the reason for this is because nowhere in my code is there my access token or access token secret. I have added them in but every time I get a 401 unauthorised (invalid or expired token).
My code is as follows, perhaps you can see where I'm going wrong?
private IOAuthCredentials credentials = new SessionStateCredentials();
private MvcAuthorizer auth;
private TwitterContext twitterCtx;
public ActionResult Index()
{
credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
credentials.AccessToken = "MYaccessTOKENhere"; // Remove this line and line below and all works fine with manual authorisation every time its called //
credentials.OAuthToken = "MYaccessTOKENsecretHERE";
auth = new MvcAuthorizer
{
Credentials = credentials
};
auth.CompleteAuthorization(Request.Url);
if (!auth.IsAuthorized)
{
Uri specialUri = new Uri(Request.Url.ToString());
return auth.BeginAuthorization(specialUri);
}
twitterCtx = new TwitterContext(auth);
twitterCtx.UpdateStatus("Test Tweet Here"); // This is the line it fails on //
return View();
}
Here's the FAQ that has help on resolving 401 errors: http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20FAQ&referringTitle=Documentation
A couple items that might be helpful too:
You can't tweet the same text twice - so either delete the previous tweet with the same text or change the text. All my test append DateTime.Now.ToString() to avoid this error.
The SessionStateCredentials holds credentials in SessionState. The persistence mode default for Session state is InProc, meaning that your session variables will be null if the process recycles, which will happen unpredictably. You might want to make sure that you are using either StateServer or SQL Server modes.

As3 Graph API Logout

i'm developing an application that'll be played by different's users, but i'm using the as3 graph api for authenticating users and posting on their wall, and i need to logout each user, before next user start his session on as3 graph api:
http://code.google.com/p/facebook-actionscript-api/
I search to force FB to ask for login's info but after a logout when login again, API skip the step and log, on the last user session.
None of the solutions I have seen on the web did work for me. The problem is indeed with StageWebView facebook cookie not being cleared on logout with FacebookMobile.logout() call. Loading logout.php with access token did not help me probably because there is no "next" parameter value for air applications that makes sense. I have seen people suggest to use localhost or facebook.com there but none of these options worked.
I have come up with a really questionable solution, but it works for now.
The point is to logout user in facebook normally like he would logout on his own. To do this we need to load facebook.com in StageWebView and click logout. Logout button is a submit form item for "logout_form" html form. So we need to make a javaScript call
document.getElementById('logout_form').submit();
in our StageWebView. And we can do just that by calling
webView.loadURL("javascript:document.getElementById('logout_form').submit();");
in ActionScript.
The full code that I use for now
protected var _logoutAttemptInProgress:Boolean = false;
public function fbLogout():void{
if(!_isLoggedIn) return;
if(_logoutAttemptInProgress) return;
_logoutAttemptInProgress = true;
var webView:StageWebView = new StageWebView();
webView.viewPort = new Rectangle(-1, 0, 1, 1);
webView.stage = this.stage;
webView.loadURL("http://www.facebook.com/lksmlrsgnlskn");
webView.addEventListener(Event.COMPLETE, runLogoutJs);
function runLogoutJs(event:Event):void{
webView.removeEventListener(Event.COMPLETE, runLogoutJs);
var jsString:String = "document.getElementById('logout_form').submit();";
webView.loadURL("javascript:"+jsString);
webView.addEventListener(Event.COMPLETE, closeWebView);
}
function closeWebView(event:Event):void{
webView.removeEventListener(Event.COMPLETE, closeWebView);
webView.stage = null;
webView.dispose();
_isLoggedIn = false;
_logoutAttemptInProgress = false;
}
FacebookDesktop.logout(null, APP_ORIGIN);
}
"lksmlrsgnlskn" is just some random garbage to get to error page that is much smaller than main page and loads faster.
FacebookDesktop.logout is to clear any local SharedObject data that Facebook lib might still have.
This is an issue that's been continuously revised by FacebookMobile, Facebook, and FacebookDesktop. Basically, you'll need to make sure you set FacebookDesktop.manageSession = false; and pass in the 2nd argument of "logout" your site's api url. If that doesn't work, the other method is to use "reallyLogout", as detailed here in this thread.
The notes in comment #24 detail the way to expos the Access Token from FacebooMobile (or whichever singleton you're using), and then manually calling the logout.php method on Facebook, with the access token.
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=297#c24
This is a problem with the cookies, i mean, the firts user session remains and when you press to login the API logs in the first user.
I dont know why but the Facebook Api log out method dont log the user out of facebook, only log the user out from your application.
If you came to a solution or think something else, let me know so we could get the solution.

Resources