I have a very simple scenario - I need my app to automatically authenticate against the UAG gateway. At the moment, I only have a file share application behind the portal, but I'm just trying to do an automatic authentication against the UAG by supplying the user credentials in code. I'm trying to access portal.mylab.com/dummylink - I know this will fail but I want the app to show me it passed the UAG authentication and failed when trying to find this dummylink application
What I have for now is simple, there is just a button in the WP8 app and everything else is hardcoded. I have a simple textblock under the button which shows the response from the website, but I get the authentication page everytime. This is what I have
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Uri targetUri = new System.Uri("portal.mylab.com/dummylink");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
request.CookieContainer = new CookieContainer();
request.Headers["User-Agent"] = "Microsoft Office Mobile";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("testuser" + ":" + "Password1")) + System.Environment.NewLine;
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
string results = httpwebStreamReader.ReadToEnd();
Dispatcher.BeginInvoke(() => TextBlockResults.Text = results);
}
}
When I look at the textblock, I can see the HTML code being returned for the login page (for a mobile portal), with 2 buttons to login either using a PIN or using credentials. What I expected (or rather wanted) to see is UAG authorization to be successful and get some kind of a "dummylink page not found" type of error. I am supplying the user credentials to UAG but it doesn't seem to be picking them up.
I'm probably missing something very obvious here, and also this is my first time with anything to do with UAG, so please excuse stupid mistakes :)
Thanks in advance
Turns out this approach is completely wrong! IF someone is looking on how to do the above, then please look at this brilliant blog
http://usingnat.net/sharepoint/2011/2/23/how-to-programmatically-authenticate-to-uag-protected-sharep.html
Related
I am new to using DocuSign and am trying to get a the authorization code as on this page: https://developers.docusign.com/platform/auth/authcode/authcode-get-token/.
I have constructed my code for this in C# as follows:
var docuSignUri = "https://account-d.docusign.com/oauth/auth?"; // base path
docuSignUri += "response_type=code"; //response type
docuSignUri += "&scope=signature"; //scopes
docuSignUri += "&client_id=0b86bXXX-XXX-XXX-XXX-XXXXXXXXee55"; //integration key
docuSignUri += "&redirect_uri=https://www.google.com"; //redirect uri
WebRequest request = WebRequest.Create(docuSignUri);
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();
System.Diagnostics.Debug.Print("docusign auth code:" + responseData);
I'm not getting a response anything like what the DocuSign documentation mentions though. I get a long HTML page that has stuff like:
"Certificate cannot contain a private key"
and that I need to confirm company details. I'm using the develop sandbox and the account-d url is correct for that? Can anyone point me to what I'm doing wrong?
You do need to actually have an interactive user. You cannot just use a web request for Auth Code Grant. You need to open a browser and have a human log in.
If you need the ability to do this without a human (say a commandline process), you may want to use JWT.
I am creating an application in Xamarin Forms for iOS and android. In VS, the test code works perfectly every time, with a response code of "OK" (200). However, in another little project which will work alongside the mobile apps (written in windows forms (.NET)), the EXACT same code, username, password, url, returns error "Unauthorised" (401).
The url in question that doesn't work is http://192.168.8.193/get.cgi?id=26&sid=255.
BUT
another url of similar function DOES work: http://-Hidden-/get.cgi?id=26&sid=255.
public static async Task<string> TestConnection(string url, string username, string password)
{
url = url + PanelCommands.GET_URL + PanelCommands.CONNECT_URL;
if (GetInternetConnectivity())
{
NetworkCredential credential = new NetworkCredential { UserName = username, Password = password };
HttpClientHandler handler = new HttpClientHandler { Credentials = credential };
HttpClient client = new HttpClient(handler);
client.Timeout = new TimeSpan(0, 0, 10);
try
{
var response = await client.GetAsync(url).ConfigureAwait(false);
return response.StatusCode.ToString();
}
catch (Exception e)
{
Debug.WriteLine(e);
return "Failed";
}
}
I have tried pre-authenticating, adding authentication headers, etc. But nothing seems to work.
Any help would be appreciated,
Thanks!
Sacked this off. Rewrote the project in Xamarin UWP. Worked perfectly first time.
The URL in question that doesn't work is http://192.168.8.193/get.cgi?id=26&sid=255.
First of all, I think you are missing the port in your URL. It should be something like http://192.168.8.193:5000/get.cgi?id=26&sid=255.
Edit: This is something I got wrong. You can perfectly have a URL without a specific port.
Secondly, your firewall may be blocking the connection between your projects, if they are running in different devices. You can try adding an inbound rule following this article for Windows 10 (it is somewhat similar in other versions of windows as well).
This is in context of multi-tenanted web solution, which intends to provide its users access to Office 365 calendar records via making REST API calls. User will be required to authenticate with Azure AD in order to have access.
This is what I'm doing.
0 ============= Windows Azure test account setup and Application is registered
I have set up an account on Windows Azure (presumably coupled with Office 365), using test e-mail that was initially created on Gmail.
I have registered my application within Windows Azure Active Directory, and provided this application with all access permissions possible. Basically added all possible resources and then ticked all the boxes for each. Client Secret key has also been issued.
1 ============= Redirecting Browser to Microsoft Login page
In my jabascript side of code, the following URL is constructed:
var url = 'https://login.microsoftonline.com/'
+ {tenant}
+ '/oauth2/authorize'
+ '?response_type=code'
+ '&client_id=' + {application_id}
+ '&redirect_uri=' + encodeURI({response_page_url})
+ '&state=' + {guid_1}
+ '&nonce=' + {guid_2}
;
Then redirection happens:
window.location.replace(url);
2 ============= Microsoft Login happens
Browser opens the Microsoft Login page, which asks for user e-mail and password. Once user e-mail is typed in and focus is changed to password, the page suddenly flips to something else and asks for e-mail again, and the for the password. Great Usability Microsoft!
3 ============= Back to Login Completion page
Once Microsoft Login procedure is over, browser lands to my http://localhost:5000/something page with some arguments in the query string.
I extract "state", "session_state", and "code" from the query string and pass it to server to do the next step.
4 ============= Trying to retrieve "id_token" for the "code"
On the server side, in C# code to be specific, I am trying to acquire "access_code" and "id_token" from Microsoft AD by the following request:
var url = "https://login.windows.net/common/oauth2/token";
var post = "grant_type=authorization_code"
+ "&code=" + {code_received_at_previous_step}
+ "&redirect_uri=" + HttpUtility.UrlEncode({same_redirect_url_as_before})
+ "&client_id=" + {application_id}
+ "&client_secret=" + {secret_key_issued_by_azure_ad}
+ "&resource=" + HttpUtility.UrlEncode("https://outlook.office365.com")
;
byte[] postData = new UTF8Encoding().GetBytes(post);
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using (var os = request.GetRequestStream())
{
os.Write(postData, 0, postData.Length);
}
WebResponse response;
bool isError = false;
try
{
response = request.GetResponse();
}
catch (WebException up)
{
isError = true;
response = up.Response;
}
string responseText = null;
using (response)
{
using (var dataStream = response.GetResponseStream())
using (var reader = new StreamReader(dataStream))
{
responseText = reader.ReadToEnd();
}
}
var json = Json.Parse(responseText);
if (isError)
{
throw new System.Exception(string.Format("{0}:{1}", json["error"], json["error_description"]));
}
At the last step an Exception is thrown with the following details:
An exception of type 'System.Exception' occurred in IdentityManagement.dll but was not handled in user code
Additional information: invalid_grant:AADSTS65001: The user or administrator has not consented to use the application with ID '{guid}'. Send an interactive authorization request for this user and resource.
Trace ID: 6fc18926-36bd-4731-a128-54fcb320718a
Correlation ID: 75a7617e-f03f-4d57-bdd2-f655dd615a2a
Timestamp: 2016-12-05 01:15:06Z
JSON data received in response in my case is the following:
{{"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID '{guid}'. Send an interactive authorization request for this user and resource.\u000D\u000ATrace ID: 6fc18926-36bd-4731-a128-54fcb320718a\u000D\u000ACorrelation ID: 75a7617e-f03f-4d57-bdd2-f655dd615a2a\u000D\u000ATimestamp: 2016-12-05 01:15:06Z","error_codes":[65001],"timestamp":"2016-12-05 01:15:06Z","trace_id":"6fc18926-36bd-4731-a128-54fcb320718a","correlation_id":"75a7617e-f03f-4d57-bdd2-f655dd615a2a"}}
So my questions are:
What is missing from my setup, environment, code or the execution AND how to fix it?
Is there a working example of C#/Javascript code that is successfully getting say calendar events from Office 365 via API requests (not functional calls to some libraries)?
Is there anyone who cal get in touch via Skype or something to help me with making my example working?
Great thanks is advance!
Much appreciate your attention.
It may be that you are requesting a scope that requires an administrator to consent, in which case an administrator for the organization must sign in and approve your app. The different scopes and whether they require administrative consent are here: https://graph.microsoft.io/en-us/docs/authorization/permission_scopes
Or possibly you aren't requesting any scopes at all? I don't see it in your URLs.
I want to open a page that required Basic authentication.
I want to pass the Basic authentication header to the browser along with the URL.
How can i do that?
Via a header you can:
string user = "uuuuuuu";
string pass = "ppppppp";
string authHdr = "Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(user + ":" + pass)) + "\r\n";
webBrowserCtl.Navigate("http://example.com", null, null, authHdr);
given that this needs to be done on a per-request basis, an easier option for basic auth is to just;
webBrowserCtl.Navigate("http://uuuuuuu:ppppppp#example.com", null, null, authHdr);
You could try the old "in URL" format which allowed this but it is insecure:
http(s)://username:password#server/resource.ext
This exposes credentials and IE has disabled it, but it may still work in other browsers. When this format is used the credentials are available to the browser and it makes the decision to send the basic authentication header depending on how the web server responds.
Try to use something like Watin
Here you can find good blog-posts about Watin.
The code looks like:
public void SearchForWatiNOnGoogle()
{
using (var browser = new IE("http://www.google.com"))
{
browser.TextField(Find.ByName("q")).TypeText("WatiN");
browser.Button(Find.ByName("btnG")).Click();
}
}
First check this code:
Dim result As String
Using wClnt As New Net.WebClient
wClnt.Credentials = New System.Net.NetworkCredential("username", "password")
Using strR As New IO.StreamReader(wClnt.OpenRead("http://ADDRESS_To_READ"))
result = strR.ReadToEnd
End Using
End Using
If it was not what your where looking for, Check this post, it may help:
How do I log into a site with WebClient?
Update:
This way you are not opening any browser. Just requesting the address you want and passing Credential.
The WebBrowser control in .Net uses Internet Explorer as it's browser, so if you don't mind using IE, this is the code I wrote. h5url is the url you want to open in a window. My program doesn't even show a browser control, this is spawns an instance of Internet Explorer with the web page logged in.
using (WebBrowser WebBrowser1 = new WebBrowser())
{
String auth =
System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(_User + ":" + _Password));
string headers = "Authorization: Basic " + auth + "\r\n";
WebBrowser1.Navigate(h5URL, "_blank", null, headers);
}
This opens a new browser with any headers you need for authentication, basic or otherwise.
I wonder of someone know a working sample of logging in using Twitter (OAuth) for .NET
I'm currently using this one http://www.voiceoftech.com/swhitley/?p=681
but it only works if I set the callback url to "oob", if I set a real callback url I get "401 unauthorized".
Thanks!
I wrote an OAuth manager for this, because the existing options were too complicated.
OAuth with Verification in .NET
The class focuses on OAuth, and works specifically with Twitter. This is not a class that exposes a ton of methods for the entire surface of Twitter's web API. It is just OAuth. If you want to update status on Twitter, this class exposes no "UpdateStatus" method. I figured it's a simple matter for app designers to construct the HTTP message they want to send. In other words the HTTP message is the API. But the OAuth stuff can get a little complicated, so that deserves an API, which is what the OAuth class is.
Here's example code to request a "request token":
var oauth = new OAuth.Manager();
oauth["consumer_key"] = MY_APP_SPECIFIC_CONSUMER_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_CONSUMER_SECRET;
oauth.AcquireRequestToken(SERVICE_SPECIFIC_REQUEST_TOKEN_URL, "POST");
THAT'S IT. In Twitter, the service-specific URL for requesting tokens is "https://api.twitter.com/oauth/request_token".
Once you get the request token, you pop the web browser UI in which the user will explicitly grant approval to your app, to access Twitter. You need to do this once, the first time the app runs. Do this in an embedded WebBrowser control, with code like so:
var url = SERVICE_SPECIFIC_AUTHORIZE_URL_STUB + oauth["token"];
webBrowser1.Url = new Uri(url);
For Twitter, the URL for this is "https://api.twitter.com/oauth/authorize?oauth_token=" with the oauth_token appended.
Grab the pin from the web browser UI, via some HTML screen scraping. Then request an "access token":
oauth.AcquireAccessToken(URL_ACCESS_TOKEN,
"POST",
pin);
For Twitter, that URL is "https://api.twitter.com/oauth/access_token".
You don't need to explicitly handle the access token; the OAuthManager class maintains it in state for you. But the token and secret are available in oauth["token"] and oauth["token_secret"], in case you want to write them off to permanent storage. To make requests with that access token, generate the authz header like this:
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
...where url is the resource endpoint. To update the user's status on Twitter, it would be "http://api.twitter.com/1/statuses/update.xml?status=Hello".
Then set the resulting string into the HTTP Header named Authorization, and send out the HTTP request to the url.
In subsequent runs, when you already have the access token and secret, you can instantiate the OAuth.Manager like this:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = MY_APP_SPECIFIC_CONSUMER_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_CONSUMER_SECRET;
oauth["token"] = your_stored_access_token;
oauth["token_secret"] = your_stored_access_secret;
Then just generate the authz header, and make your requests as described above.
Download the DLL
View the Documentation
Already solved my issue with http://www.voiceoftech.com/swhitley/?p=681
I was saving my app as "browser" but since I wasn't especifying a callback url it was transformed to "client" app on saving.
I am late to the conversation, but I have created a video tutorial for anyone else who is having this same task. Like you, I had a ton of fun figuring out the 401 error.
Video: http://www.youtube.com/watch?v=TGEA1sgMMqU
Tutorial: http://www.markhagan.me/Samples/Grant-Access-And-Tweet-As-Twitter-User-ASPNet
Code (in case you don't want to leave this page):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Twitterizer;
namespace PostFansTwitter
{
public partial class twconnect : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var oauth_consumer_key = "gjxG99ZA5jmJoB3FeXWJZA";
var oauth_consumer_secret = "rsAAtEhVRrXUTNcwEecXqPyDHaOR4KjOuMkpb8g";
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
oauth_consumer_key,
oauth_consumer_secret,
Request.Url.AbsoluteUri);
Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
reqToken.Token));
}
else
{
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(
oauth_consumer_key,
oauth_consumer_secret,
requestToken,
pin);
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = tokens.Token,
AccessTokenSecret = tokens.TokenSecret,
ConsumerKey = oauth_consumer_key,
ConsumerSecret = oauth_consumer_secret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
accesstoken,
"Testing!! It works (hopefully).");
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
}
}
}
}
"DotNetOpenAuth" will be great helps for u. http://www.dotnetopenauth.net/
I've developed a C# library for OAuth that is really simple to use and get up and running with. The project is an open source project and I've included a demo application that works against
1. Google
2. Twitter
3. Yahoo
4. Vimeo
Of course any other OAuth provider will do as well. You can find the article and library here
OAuth C# Library