Loopback current context is null sometime - node.js

In my loopback application i am getting the current logged-in user using currentcontext as follows..
exports.getCurrentUserId =function(){
var ctx = loopback.getCurrentContext();
var accessToken = ctx && ctx.get('accessToken');
var userId = accessToken && accessToken.userId;
return userId;
}
When i am calling this method getCurrentUserId, its working fine sometime, sometimes its giving null. Its unpredictable . Please share your ideas. Thanks in advance.
versions:
loopback-connector-mongo:1.15.1

Re. getCurrentContext(), there is a plan to deprecate this method as it has been unreliable ( see discussion here).
However, there is a suggested workaround to inject Remote Context via Options.

Related

Azure Schema Extensions in Graph Client

Whatever I tried I cannot set an extension property on a User object, here is a reproducible piece of code:
public async Task CleanTest(string extName)
{
ExtensionProperty ep = new ExtensionProperty
{
Name = extName,
DataType = "String",
TargetObjects = { "User" }
};
App app = (App)(await _client.Applications.Where(a => a.AppId == _managementAppClientId).ExecuteSingleAsync());
app.ExtensionProperties.Add(ep);
await app.UpdateAsync();
GraphUser user = (GraphUser)(await _client.Users.Where(u => u.UserPrincipalName.Equals("email")).ExecuteSingleAsync());
string propName = FormatExtensionPropertyName(extName); //formats properly as extesion_xxx_name
user.SetExtendedProperty(propName, "testvalue");
//user.SetExtendedProperty(extName, "testvalue");
await user.UpdateAsync(); // fails here
}
user.UpdateAsync() according to Fiddler doesn't even go out and application fails with an exception:
"The property 'extension_e206e28ff36244b19bc56c01160b9cf0_UserEEEqdbtgd3ixx2' does not exist on type 'Microsoft.Azure.ActiveDirectory.GraphClient.Internal.User'. Make sure to only use property names that are defined by the type."
This issue is also being tracked here:
https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console/issues/28
I've got an alternative workaround for this bug, for those that want to use the version 5.7 OData libraries rather than redirecting to the v5.6.4 versions.
Add a request pipeline configuration handler.
// initialize in the usual way
ActiveDirectoryClient activeDirectoryClient =
AuthenticationHelper.GetActiveDirectoryClientAsApplication();
// after initialization add a handler to the request pipline configuration.
activeDirectoryClient.Context
.Configurations.RequestPipeline
.OnMessageWriterSettingsCreated(UndeclaredPropertyHandler);
In the handler, change the ODataUndeclaredPropertyBehaviorKinds value on the writer settings to SupportUndeclaredValueProperty.
private static void UndeclaredPropertyHandler(MessageWriterSettingsArgs args)
{
var field = args.Settings.GetType().GetField("settings",
BindingFlags.NonPublic | BindingFlags.Instance);
var settingsObject = field?.GetValue(args.Settings);
var settings = settingsObject as ODataMessageWriterSettings;
if (settings != null)
{
settings.UndeclaredPropertyBehaviorKinds =
ODataUndeclaredPropertyBehaviorKinds.SupportUndeclaredValueProperty;
}
}
Just in case you still looking for solution to this problem or someone else is facing the same issue:
I got similar issue and it looks like, at least for me, the problem was in latest version of "Microsoft.Data.Services.Client" package - 5.7.0 (or in one of it dependencies). When I downgraded to previous version - 5.6.4 it worked as a charm.
I had same symptoms - updating of extended property was failing even w/o any request is made (also used Fiddler)
Hope it helps!
Artem Liman

How to set facebook logins for AWS cognito credential provider using iOS Swift

I am using AWS iOS SDK v2 & Facebook iOS SDK v2.2. I am trying to use Facebook token as the "logins" for AWS credentials provider. The problem is, I don't know how to set the logins in iOS Swift. Below is my code:
if (FBSession.activeSession().state == FBSessionState.CreatedTokenLoaded) {
// If there's one, just open the session silently, without showing the user the login UI
FBSession.openActiveSessionWithReadPermissions(["public_profile", "email", "user_friends"], allowLoginUI: false, completionHandler: { (fbSession, fbSessionState, error) -> Void in
// Handler for session state changes
// This method will be called EACH time the session state changes,
// also for intermediate states and NOT just when the session open
if (error == nil) && (fbSessionState == FBSessionState.Open) {
var token: String = fbSession.accessTokenData.accessToken
var logins: NSDictionary = NSDictionary(dictionary: ["AWSCognitoLoginProviderKey.Facebook" : token])
self.credentialsProvider.logins = logins
self.credentialsProvider.refresh()...}
but I don't think the logins dictionary is correct...I've tried
[AWSCognitoLoginProviderKey.Facebook : token]
but XCode says it does not conform to NSCopying.
Hints are soooo welcome here! THANKS!!!
I've got the answer from AWS forum:
var logins: NSDictionary = NSDictionary(dictionary: ["graph.facebook.com" : token])

HttpClient fails to authenticate via NTLM on the second request when using the Sharepoint REST API on Windows Phone 8.1

Sorry for the long title, but it seems to be the best summary based on what I know so far.
We’re currently working on a Universal App that needs to access some documents on a Sharepoint server via the REST API using NTLM Authentication, which proves to be more difficult than it should be. While we were able to find workarounds for all problems (see below), I don’t really understand what is happening and why they are even necessary.
Somehow the HttpClient class seems to behave differently on the phone and on the PC. Here’s what I figured out so far.
I started with this code:
var credentials = new NetworkCredential(userName, password);
var handler = new HttpClientHandler()
{
Credentials = credentials
};
var client = new HttpClient(handler);
var response = await client.GetAsync(url);
This works fine in the Windows app, but it fails in the Windows Phone app. The server just returns a 401 Unauthorized status code.
Some research revealed that you need to provide a domain to the NetworkCredential class.
var credentials = new NetworkCredential(userName, password, domain);
This works on both platforms. But why is the domain not required on Windows?
The next problem appears when you try to do multiple requests:
var response1 = await client.GetAsync(url);
var response2 = await client.GetAsync(url);
Again, this works just fine in the Windows app. Both requests return successfully:
And again, it fails on the phone. The first request returns without problems:
Strangely any consecutive requests to the same resource fail, again with status code 401.
This problem has been encountered before, but there doesn’t seem to be a solution yet.
An answer in the second thread suggests that there’s something wrong with the NTLM handshake. But why only the second time?
Also, it seems to be a problem of the HttpClient class, because the following code works without problems on both platforms:
var request3 = WebRequest.CreateHttp(url);
request3.Credentials = credentials;
var response3 = await request3.GetResponseAsync();
var request4 = WebRequest.CreateHttp(url);
request4.Credentials = credentials;
var response4 = await request4.GetResponseAsync();
So the problem only appears:
on Windows Phone. The same code in a Windows App works.
when connecting to Sharepoint. Accessing another site with NTLM authentication works on both platforms.
when using HttpClient. Using WebRequest, it works.
So while I'm glad that I at least found some way to make it work, I’d really like to know what’s so special about this combination and what could be done to make it work?
Hi Daniel at the same problem when I do my sync, because windows phone had a lot of problems with cache, finallt I could solve with add headers.
Also I think so it's good idea that you use the timeout because it's a loooong response you can wait a lot of time... And the other good way to work it's use "using", it's similar that use ".Dispose()". Now I show you the code:
var request3 = WebRequest.CreateHttp(url);
request3.Credentials = credentials;
request.ContinueTimeout = 4000; //4 seconds
//For solve cache problems
request.Headers["Cache-Control"] = "no-cache";
request.Headers["Pragma"] = "no-cache";
using(httpWebResponse response3 = (httpWebResponse) await request3.GetResponseAsync()){
if (response3.StatusCode == HttpStatusCode.OK)
{
//Your code...
}
}
var request4 = WebRequest.CreateHttp(url);
request4.Credentials = credentials;
request.ContinueTimeout = 4000; //4 seconds
//For solve cache problems
request.Headers["Cache-Control"] = "no-cache";
request.Headers["Pragma"] = "no-cache";
using(httpWebResponse response4 = (httpWebResponse) await request4.GetResponseAsync()){
if (response4.StatusCode == HttpStatusCode.OK)
{
//Your code...
}
}
I wait that my code can help you. Thanks and good luck!

Can't Resolve a service using AppHostBase.ResolveService<T> API in ServiceStack 4

I'm using ASP.NET MVC 5 and attempting to resolve a few services using the example:
var authService = AppHostBase.Resolve<AuthService>();
authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
var response = authService.Authenticate(new Auth
{
UserName = model.UserName,
Password = model.Password,
RememberMe = model.RememberMe
});
or I've also tried:
using (var helloService = AppHostBase.ResolveService<HelloService>())
{
ViewBag.GreetResult = helloService.Get(name).Result;
return View();
}
In the first case I needed the RequestContext injected so I tried that approach and in the second case I was using the example which I understand has the RequestContext automatically injected through Funq.
ResolveService could not be found when I tried the second approach and in the first approach RequestContext is not a valid property. Am I missing something simple or has there been changes to the API?
The documentation does appear to be wrong for this as there is no longer a ResolveService<T> on AppHostBase. It needs to be updated due to changes in the Api.
You can do this in ServiceStack v4 with MVC:
var authService = HostContext.Resolve<AuthService>();
...

Set Cookie for UIWebView requests

I want to embed an UIWebView into my MonoTouch application for an area that is not yet implemented natively.
In order to authenticate with the website I want to set a cookie containing a key for the current session.
I tried creating a NSDictionary with the properties for the Cookie and then create a new NSHttpCookie and add it to the NSHttpCookieStorage.SharedStorage.
Sadly the cookie seems to be empty and not used for the request.
An example of how to build be cookie with properties and a comment on whether or not this is the simplest way to do this would be greatly appreciated.
Following Anuj's bug report I felt bad about how many lines of code were required to create the cookies. So the next MonoTouch versions will have new constructors for NSHttpCookie, similar to System.Net.Cookie that will allow you do to something like:
// this ctor requires all mandatory parameters
// so you don't have to guess them while coding
var cookie = new NSHttpCookie ("iherd", "ulikecookies", "/", "yodawg.com");
You'll even be able to create a NSHttpCookie from a .NET System.Net.Cookie.
Note: Never hesitate to fill a bug report when an API proves to be way more complicated than it should be :-)
Whenever I need to send cookies and params up to the server I use something like RestSharp or Hammock and then pass the response.Content value into UIWebView's loadHtmlString method:
//setup cookies and params here
var response = client.Execute(req);
_webView = new UIWebView();
_webView.LoadHtmlString(response.Content, new NSUrl(baseUrl));
The NSDictionary API is fairly trivial too:
var props = new NSMutableDictionary ();
props.Add (NSHttpCookie.KeyOriginURL, new
NSString("http://yodawg.com"));
props.Add (NSHttpCookie.KeyName, new NSString("iherd"));
props.Add (NSHttpCookie.KeyValue, new NSString("ulikecookies"));
props.Add (NSHttpCookie.KeyPath, new NSString("/"));
AFAIK every application has its own cookie storage so try to use this code before rendering the page in the UIWebView
NSHttpCookie cookie = new NSHttpCookie()
{
Domain = "yourdomain.com",
Name = "YourName",
Value = "YourValue" //and any other info you need to set
};
NSHttpCookieStorage cookiejar = NSHttpCookieStorage.SharedStorage;
cookiejar.SetCookie(cookie);
I'm not in a MAC right now so im not able to test it hope this helps
okay sorry, i wasn't able to test it before posting, anyways I won't get home until tonight so give this a spin
var objects = new object[] { "http://yoururl.com", "CookieName", "CookieValue", "/" };
var keys = new object[] { "NSHTTPCookieOriginURL", "NSHTTPCookieName", "NSHTTPCookieValue", "NSHTTPCookiePath" };
NSDictionary properties = (NSDictionary) NSDictionary.FromObjectsAndKeys(objects, keys);
NSHttpCookie cookie = NSHttpCookie.CookieFromProperties(properties);
NSHttpCookieStorage.SharedStorage.SetCookie(cookie);
As you stated above, in the case that doesn't work might be a bug on monotouch binding so you can bind it manually by doing this
var objects = new object[] { "http://yoururl.com", "CookieName", "CookieValue", "/" };
var keys = new object[] { "NSHTTPCookieOriginURL", "NSHTTPCookieName", "NSHTTPCookieValue", "NSHTTPCookiePath" };
NSDictionary properties = (NSDictionary) NSDictionary.FromObjectsAndKeys(objects, keys);
NSHttpCookie cookie = (NSHttpCookie) Runtime.GetNSObject(Messaging.IntPtr_objc_msgSend_IntPtr(new Class("NSHTTPCookie").Handle, new Selector("cookieWithProperties:").Handle, properties.Handle))
NSHttpCookieStorage.SharedStorage.SetCookie(cookie);
also don't forget to include using MonoTouch.ObjCRuntime; if manually binding it
if manually binding works please don't forget to post a bug report on https://bugzilla.xamarin.com/
Alex
I’ve wrote the NSMutableURLRequest+XSURLRequest catagory and XSCookie class to do this;-) http://blog.peakji.com/cocoansurlrequest-with-cookies/
This might give you a lead. Previously I used a similar strategy to make a
WebRequest to a site and collect cookies which were stored in the .Net/Mono CookieStore. Then when loading a url in the UIWebView I copied those cookies over to the NSHttpCookieStorage.
public NSHttpCookieStorage _cookieStorage;
/// <summary>
/// Convert the .NET cookie storage to the iOS NSHttpCookieStorage with Login Cookies
/// </summary>
void DotNetCookieStoreToNSHttpCookieStore()
{
foreach (Cookie c in _cookies.GetCookies(new Uri(UrlCollection["Login"], UriKind.Absolute))) {
Console.WriteLine (c);
_cookieStorage.SetCookie(new NSHttpCookie(c));
}
}

Resources