NTLM Authentication using RestSharp? - ntlm

I am trying to use NTLM authentication for my REST calls to TeamCity using RestSharp.
IRestClient _client=new RestClient(_url);
_client.Authenticator = new NtlmAuthenticator
(System.Net.CredentialCache.DefaultNetworkCredentials);
However it is not working. Please suggest if I am missing something.

This now appears to be working properly and can be done very easily utilizing the NTLMAuthenticator like so:
RestClient client = new RestClient(_baseURL);
client.Authenticator = new NtlmAuthenticator();

Try this:
var client = new RestClient(_baseURL)
{
Authenticator = new RestSharp.Authenticators.NtlmAuthenticator()
};

As of RestSharp v107, The NtlmAuthenticator is deprecated.
This worked for me:
var credentials = new NetworkCredential(username, password, domain);
var options = new RestClientOptions(_settings.ServiceEndPoint)
{
UseDefaultCredentials = false,
Credentials=credentials
};
var client = new RestClient(options);

Not supported currently. Refer to the below thread.
http://devnet.jetbrains.com/thread/451079?tstart=0

Related

Lost session data after MS AD Oauth2 redirect

I am losing original session data after MS AD Oauth2 redirect back today. It is now a totally new session after redirect to and back from https://login.microsoftonline.com/**************/oauth2/v2.0/authorize". But, it worked a few days ago and failed now after some automatic windows10 updates (and rekeying some tfs password from credential manager.) However, If I use my GitHub authorization server, the same code works and keeps my session data: Session["state"]. What am I missing? Any help would be greatly appreciated! I am doing manual redirection using something like below:
private void SignUpOAuth()
{
var state = Guid.NewGuid().ToString();
var nonce = Guid.NewGuid().ToString();
var clientId = "*************";
var scope = "openid";
var serviceUrl = ConfigurationManager.AppSettings.Get("OAuthServiceUrl");
var redirectUrl = ConfigurationManager.AppSettings.Get("OAuthRedirectUrl");
var paramtersPart = string.Format("response_type={0}&client_id={1}&scope={2}&redirect_uri={3}&aud{4}&state={5}&nonce={6}&response_mode=form_post",
"id_token+code",
HttpUtility.UrlEncode(clientId),
HttpUtility.UrlEncode(scope),
HttpUtility.UrlEncode(redirectUrl),
HttpUtility.UrlEncode(serviceUrl),
state,
nonce);
_context.Session.Add("state", state);
_context.Session.Add("nonce", nonce);
_context.Response.Redirect($"{ serviceUrl}?{paramtersPart}", false);
}

Puppeteer - issues passing token in headless

Im new in Puppeteer and im stuck.
Project is related to Angular App, on which user is logged in by link from email.
I need to pass barear token to the headless browser. Whatever solution i found online, its not working.
Is there any option to pass user object in Local Storage perhaps?
Or any other idea?
Thanks
faced the same issue but tried to copy the cookies and worked with me
var browserFetcher = new BrowserFetcher();
await browserFetcher.DownloadAsync();
await using var browser = await Puppeteer.LaunchAsync(
new LaunchOptions { Headless = true,IgnoreHTTPSErrors=true });
await using var page = await browser.NewPageAsync();
var keys = HttpContext.Request.Cookies.Keys;
string cookieString = "";
foreach (var key in HttpContext.Request.Cookies.Keys) {
cookieString = cookieString + key +"="+ HttpContext.Request.Cookies[key]+";";
}
await page.SetExtraHttpHeadersAsync(new Dictionary<string, string> {
{ "cookie" , string.Join(';',cookieString) }
});
rojaswilmer has already suggested to use setExtraHTTPHeaders. Just change Basic with Bearer since it's not HTTP Basic auth, as explained also in another question in StackOverflow.
Hello did you try with the api to modify the header?
const headers = new Map();
headers.set(
'Authorization',
`Basic ${new Buffer(`${myuser}:${mypass}`).toString('base64')}`
);
await page.setExtraHTTPHeaders(headers);
https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md#pagesetextrahttpheadersheaders

How to use a proxy with the instagram-private-api for Node.js

Using a proxy with instagram-private-api.
Hi all, I spent a decent amount of time trying to figure this out and there is probably a really simple answer but I was seriously confused. When creating a session needed for the Instagram nodeJS API (private) you need a proxyUrl. I was wondering how to do / configure this? Do you need to create your own proxy server that you host?
Here is my code so far.
var Upload = require('instagram-private-api').V1;
var Client = require('instagram-private-api').V1;
var device = new Client.Device('test');
var storage = new Client.CookieFileStorage(__dirname +
'/cookies/test.json');
var photo = require('instagram-private-api').V1;
var username = 'testusername'
var password = 'testpassword'
var proxyUrl = '???'
Client.Session.create(device, storage, username, password, proxyUrl)
var Upload = require('./node_modules/instagram-private-api/client/v1/Upload.js')
var session = new Client.Session(device, storage, 'test', 'test')
Upload.photo(session, 'aaaa.jpg')
.then(function(upload) {
console.log(upload.params.uploadId);
return Media.configurePhoto(session, upload.params.uploadId, 'henlo world');
})
.then(function(medium) {
console.log(medium.params)
})
I know my code is probably seriously flawed as well, criticism is appreciated! Here's the link to the GitHub of the Node.JS wrapper mentioned. Here.
e
Hi there Benjamin,
I'm really looking forward to helping you.
As already stated, this library won't be upkept and maintained and could become irrelevant in updates to the official API.
I believe one has to set up a proxy url on their phone.

Using AuthenticationContext & ActiveDirectoryClient with an application proxy?

Using the Azure Active Directory Graph Client API, how would I configure the underlying HttpClient to use an HttpClientHander, where I can define an authenticated application proxy?
var proxy = new WebProxy(...);
proxy.Credentials = ...;
var handler = new HttpClientHandler { Proxy = proxy, UseProxy = true};
var auth = new AuthenticationContext(...);
var client = new ActiveDirectoryClient(...);
Or, can I not use the Graph Client behind a proxy?
Thanks
I was exploring the same problem. It took some digging, but I found a solution. Now, I realize you asked specifically how to apply an HttpClientHandler. I don't know if this can be done; however, you can apply a proxy. Here's how.
The ActiveDirectoryClient class provides a DataServiceContextWrapper property called Context, which is, not surprisingly, a wrapper to a DataServiceContext.
This is good. It reduces the problem to figuring out how to apply a proxy to the DataServiceContext class. I used some old code I had sitting around, and things pretty much exploded. This is because I used the deprecated SendingRequest event to intercept a request and apply a proxy before it goes out the door. This client is not compatible with the deprecated event.
It took a little more digging to figure out how to do it with the SendingRequest2 event; it only required a little type casting.
Do this:
var client = new ActiveDirectoryClient(...);
client.Context.SendingRequest2 += OnSendingRequest2;
// ...
static void OnSendingRequest2(object sender, SendingRequest2EventArgse)
{
var request = ((HttpWebRequestMessage)e.RequestMessage).HttpWebRequest;
request.Proxy = new WebProxy("http://myproxy:port");
}
Don't Do This: (It is deprecated and will produce an exception.)
var client = new ActiveDirectoryClient(...);
client.Context.SendingRequest += OnSendingRequest;
// ...
static void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
e.Request.Proxy = new WebProxy("http://myproxy:port");
}
a bit late but i ran into the same issue.
using the code below in app.config saved my day !
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>

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!

Resources