I am writing a Windows App on Windows Phone Emulator to communicate with DropBox account and am using DropNet package from NuGet gallery.
The page that I am referring is: http://dkdevelopment.net/what-im-doing/dropnet/
Here are the steps I have done:
Step 1) Creating the client
DropNetClient GlobalClient = new DropNetClient("TOKEN", "SECRET", "testUserName", "testPassword");
I am not sure what goes in userToken and userSecret, it can't be hard-coded username and password!
Step 2) Requesting Token
GlobalClient.GetTokenAsync((userToken) =>
{
//Dont really need to do anything with userLogin,
//DropNet takes care of it for now
},
(error) =>
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(error.Message);
});
});
Step 3) Building authorizing URL
var url = GlobalClient.BuildAuthorizeUrl("http://dkdevelopment.net/BoxShotLogin.htm");
Step 4) Redirecting browser to DropBox Login Page. After this, DropBox does allow to login, but it displays this warning: "The request to link the app is invalid" And more importantly, the browser does not get redirected to http://dkdevelopment.net/BoxShotLogin.htm. This indicates something went wrong. Not sure what though.
Uri testUri = new Uri(url.ToString());
WebBrowserTask task = new WebBrowserTask();
task.Uri = testUri;
task.Show();
Step 5) This does not work. GlobalClient.UserLogin.Token and GlobalClient.UserLogin.Secret does not get set.
GlobalClient.GetAccessTokenAsync((accessToken) =>
{
//Store this token for "remember me" function
GlobalClient.UserLogin.Token = accessToken.Token;
GlobalClient.UserLogin.Secret = accessToken.Secret;
},
(error) =>
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(error.Message);
});
});
Anybody knows how to fix this?
Thanks!
I figured out the problem. In Step 2, request token needs to be stored in order to build correct authorize URL and that request token needs to be passed as the first parameter. However when I try to store in the statement lambda like this, it does not get stored. What's the issue here? I think it's the way I might be using lambdas.
GlobalClient.GetTokenAsync((userToken) =>
{
infoTextBlock.Text = userToken.Token;
GlobalClient.UserLogin.Token = userToken.Token;
}
(error) =>
{
});
Thanks!
The issue is in the following code:
UserLogin.Token = userToken.Token;
Assigning a value to token doesn't mean the underlying credentials are set for the request. This is only done when you call the following:
UserLogin = userToken;
Poor design in the class interface if you ask me. There should be no difference between calling UserLogin.Token = Something, and UserLogin = NewLogin (with regards to underlying business rules).
Related
I need to force re-authentication of Microsoft Graph within an MVC Core application.
The Graph object is obtained in ConfigureServices using the code segment:
var tokenAcquisition = context.HttpContext.RequestServices
.GetRequiredService<ITokenAcquisition>();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) => {
var token = await tokenAcquisition
.GetAccessTokenForUserAsync(_scopes, user: context.Principal);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
})
);
The problem is the token goes stale and a later call to Graph fails. Easy to trap and to put in some reauthentication code except it also fails, with a "MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call" error. Plenty of reference to this scenario online but no definitive response that I can find.
Reauthentication code in the controller is:
if (ex.InnerException.InnerException is MsalUiRequiredException)
{
string[] _scopes = _config.GetValue<string>("AzureAd:GraphScopes")?.Split(' ');
var tokenAcquisition = _http.RequestServices.GetRequiredService<ITokenAcquisition>();
_graph = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) =>
{
var options = new TokenAcquisitionOptions() { ForceRefresh = true };
var token = await tokenAcquisition.GetAccessTokenForUserAsync(_scopes, user: User, tokenAcquisitionOptions: options);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
})
);
}
Question is how to successfully force reauthentication and obtain a new Graph client?
Answering my own question, turns out it's easily handled in the Controller:
try
{
string token = await _tokenAcquisition
.GetAccessTokenForUserAsync(GraphConstants.Scopes);
return View().WithInfo("Token acquired", token);
}
catch (MicrosoftIdentityWebChallengeUserException)
{
return Challenge();
}
This code segment is from https://learn.microsoft.com/en-us/graph/tutorials/aspnet-core?tutorial-step=3
I assume that your application is forcing the user to log in and you're using that identity to get a Graph token based on the use of context.Principal:
.GetAccessTokenForUserAsync(_scopes, user: context.Principal);
When the token expires I assume the original token that was used to get in has also expired about the same time. That means that there is no user and therefore calls fail with the error that you're describing. It makes me think you need to reauthenticate before you try to get a new graph token.
However, you should monitor the token and get a new one just before it expires - silently -using the refresh token rather than a new authentication.
https://learn.microsoft.com/en-us/advertising/guides/authentication-oauth-get-tokens?view=bingads-13#refresh-accesstoken
I'm trying to add a new comment to a work item which mentions a user, but using the traditional "#adamh" as you would do on the website does not seem to work via the API.
The data updates fine, however the "#adamh" is just plain text, I need to be able to somehow chuck an identity into here. Can anyone point me in the right direction?
Thanks!
A snippet is here
const vsts = require('vso-node-api');
const item = require('vso-node-api/WorkItemTrackingApi')
const ti = require('vso-node-api/interfaces/WorkItemTrackingInterfaces');
// your collection url
const collectionUrl = "https://myArea.visualstudio.com/defaultcollection";
// ideally from config
const token = "helloWorld";
async function run() {
let authHandler = vsts.getPersonalAccessTokenHandler(token);
let connection = new vsts.WebApi(collectionUrl, authHandler);
let itemTracking = await connection.getWorkItemTrackingApi();
//Add all task data to new array
let taskData = await itemTracking.getWorkItems([15795,15796])
let newData = taskData[0]
let wijson = [
{
"op": "add",
"path": "/fields/System.History",
"value": "#adamh"
}
];
const updateItem = itemTracking.updateWorkItem(null, wijson, 15795).catch(err => {
console.log(err)
}).then(() => console.log("updated"))
return newData
}
const express = require('express')
const app = express()
app.get('/', async (req, res) => {
let data = await run()
res.send(data)
})
app.listen(3000, () => console.log('Example app listening on port 3000!'))
You can use the format shown here as part of the text value for your new comment:
...
This will create a mention link to that user. The link text can be the person's name or any other text you choose to put there. An email alert will be sent to the mentioned user if your system is configured to do so (same as in the UI).
To get your users' userid strings, you can follow the method shown here.
You can use the # to notify another team member about the discussion. Simply type # and their name.
It's using the #mention control , the person you #mention will receive an email alert with your comment and a link to the work item, commit, changeset, or shelveset.
There is not any public API shows how this work in VSTS, you could try to use F12 in google browser to track the process. Another workaround is directly using API to send a notification to the user you want to mention at.
I am following the instructions on this page
to implement the invisible recaptcha. Everything works great, but how do I know it is working? Is there a way to force a false to test it?
Also, The documentation is not clear on the above page, but some places have additional code to verify the users "response" (it's invisible so i'm not sure what the response is here) - so do I need to add additional back end logic to hit this endpoint with the invisible reCaptcha resulting token and my secret key?
What happens when the user clicks submit on the invisible recaptcha? What is done in the API to return the token? What is the token for? What does the siteverify api then do to determine its a person? Why isnt additional verification needed when the reCAPTCHA V2 (visible click one) is used?
After some testing it looks like you could just do the front end part. The data callback function is not called until google is sure you are a person, if google is not sure then it loads the "select which tiles have a thing in them" reCaptcha to be sure. Once the reCaptcha api is sure that it is a person, the data callback function is fired - at that time you can do further validation to ensure that the token you received during the callback is the one that google actually sent and not a bot trying to fool you by hitting your callback funct - so from there you do server side processing for further validation. Below is an example of a C# ashx handler - and ajax for the validation
function onTestSubmit(token) {
$.ajax({
type: "POST",
url: "testHandler.ashx",
data: { token: token },
success: function (response) {
if (response == "True") {
//do stuff to submit form
}
}
});
}
And the ashx
public class testHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string token = context.Request.Form["token"];
bool isCaptchaValid = ReCaptcha.Validate(token);
context.Response.Write(isCaptchaValid.ToString());
}
public bool IsReusable {
get {
return false;
}
}
}
public class ReCaptcha
{
private static string URL =
"https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";
private static string SECRET = "shhhhhhhhhhhhhhSecretTOken";
public bool Success { get; set; }
public List<string> ErrorCodes { get; set; }
public static bool Validate(string encodedResponse)
{
if (string.IsNullOrEmpty(encodedResponse)) return false;
var client = new System.Net.WebClient();
var googleReply = client.DownloadString(string.Format(URL, SECRET, encodedResponse));
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var reCaptcha = serializer.Deserialize<ReCaptcha>(googleReply);
return reCaptcha.Success;
}
}
Yes, you do.
You need to understand that invisible reCaptcha is a process with multiple steps, all of which end up providing a final response regarding the humanity of the user.
In simple words, when the users submits a form (or does whatever it is you are trying to keep bots away from with Invisible reCaptcha) you'll be sending your public sitekey to your backend, which will fire up a verification payload to Google.
In my very basic example, this is the button which the hopefully human visitor clicks to submit a form on my site:
<button type="submit" class="g-recaptcha" data-sitekey="xxxxxxxx_obscured_xxxxxxxx" data-callback="onSubmit">Submit Form</button>
Note how the the button has the data-callback "onSubmit", which upon submission runs this small script:
<script type="text/javascript">
var onSubmit = function(response) {
document.getElementById("simpleForm").submit(); // send response to your backend service
};
</script>
The backend service in my example is a vanilla PHP script intended to process the form input and store it on a database and here comes the tricky part. As part of the POST to the backend, besides the form fields the user filled is the response from the service (and since you may or may not be doing a lot of things on the front-end where the user could manipulate the response before it's posted to your backend, Google's response is not explicit at this point)
On your backend, you'll need to take g-recaptcha-response that came from google and post it to a verification API using your private key (which is not the one on the form) in order to get the human/robot verdict which you can act upon. Here's a simple example written in PHP and hitting the API with cURL:
$recaptcha_response = $_POST["g-recaptcha-response"];
$api_url = 'https://www.google.com/recaptcha/api/siteverify';
$api_secret = 'zzzzzzz_OBSCURED_SECRET_KEY_zzzzzzzzzzz';
$remoteip = '';
$data = array('secret' => $api_secret, 'response' => $recaptcha_response);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($api_url, false, $context);
$captcha_response = json_decode($result, true);
// at this point I have the definite verdict from google. Should I keep processing the form?.
if ($captcha_response['success'] == true) {
// I heart you, human. Keep going
$captcha_error = 0;
}
else {
// Damn robot, die a slow and painful death
$captcha_error = 1;
}
I make a final decision based on $captcha_error (basically 1 means halt, 0 means keep processing)
If you rely solely on getting the g-recaptcha-response you're having Google do the work and then ignoring the result
I have custom middleware that provides global error handling. If an exception is caught it should log the details with a reference number. I then want to redirect the user to an error page and only show the reference number. My research shows that TempData should be ideal for this but it only seems to be accessible from within a controller context. I tried adding the reference number to HttpContext.Items["ReferenceNumber"] = Guid.NewGuid();
But this value is lost through the redirect.
How can middleware pass information through a redirect? Do I just have to put the number in a querystring?
Inside the middleware class you need to add a reference to get access to the required interfaces. I have this middleware in a separate project and needed to add this NuGet package.
using Microsoft.AspNetCore.Mvc.ViewFeatures;
This then allows you to request the correct services within the middleware.
//get TempData handle
ITempDataDictionaryFactory factory = httpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
ITempDataDictionary tempData = factory.GetTempData(httpContext);
After you have ITempDataDictionary you can use it like you would use TempData within a controller.
//pass reference number to error controller
Guid ReferenceNum = Guid.NewGuid();
tempData["ReferenceNumber"] = ReferenceNum.ToString();
//log error details
logger.LogError(eventID, exception, ReferenceNum.ToString() + " - " + exception.Message);
Now when I get the the controller after a redirect I have no issues pulling out the reference number and using it in my view.
//read value in controller
string refNum = TempData["ReferenceNumber"] as string;
if (!string.IsNullOrEmpty(refNum))
ViewBag.ReferenceNumber = refNum;
#*display reference number if one was provided*#
#if (ViewBag.ReferenceNumber != null){<p>Reference Number: #ViewBag.ReferenceNumber</p>}
Once you put this all together, you give users a reference number that they can give you to help troubleshoot the problem. But, you are not passing back potentially sensitive error information which could be misused.
You can register an ITempDataProvider yourself and use it in your middleware. Here is a small sample I got working between two simple paths. If you are already using MVC the ITempDataProvider is probably already registered. The issue I faced was the path of the cookie that was written. It was /page1 so /page2 did not have access to the cookie. So I had to override the options as you can see in code below.
I hope this will help you :)
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDataProtectionProvider>(s => DataProtectionProvider.Create("WebApplication2"));
services.Configure<CookieTempDataProviderOptions>(options =>
{
options.Path = "/";
});
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ITempDataProvider tempDataProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Map("/page1", (app1) =>
{
app1.Run(async context =>
{
tempDataProvider.SaveTempData(context, new Dictionary<string, object> { ["Message"] = "Hello from page1 middleware" });
await context.Response.WriteAsync("Hello World! I'm page1");
});
});
app.Map("/page2", (app1) =>
{
app1.Run(async context =>
{
var loadTempData = tempDataProvider.LoadTempData(context);
await context.Response.WriteAsync("Hello World! I'm page2: Message from page1: " + loadTempData["Message"]);
});
});
}
This led me in the right direction: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state#cookie-based-tempdata-provider
Happy coding! :)
I am trying to write an activity in Google+ using the dotnet-client. The issue is that I can't seem to get the configuration of my client app correctly. According to the Google+ Sign-In configuration and this SO question we need to add the requestvisibleactions parameter. I did that but it did not work. I am using the scope https://www.googleapis.com/auth/plus.login and I even added the scope https://www.googleapis.com/auth/plus.moments.write but the insert still did not work.
This is what my request url looks like:
https://accounts.google.com/ServiceLogin?service=lso&passive=1209600&continue=https://accounts.google.com/o/oauth2/auth?scope%3Dhttps://www.googleapis.com/auth/plus.login%2Bhttps://www.googleapis.com/auth/plus.moments.write%26response_type%3Dcode%26redirect_uri%3Dhttp://localhost/%26state%3D%26requestvisibleactions%3Dhttp://schemas.google.com/AddActivity%26client_id%3D000.apps.googleusercontent.com%26request_visible_actions%3Dhttp://schemas.google.com/AddActivity%26hl%3Den%26from_login%3D1%26as%3D-1fbe06f1c6120f4d<mpl=popup&shdf=Cm4LEhF0aGlyZFBhcnR5TG9nb1VybBoADAsSFXRoaXJkUGFydHlEaXNwbGF5TmFtZRoHQ2hpa3V0bwwLEgZkb21haW4aB0NoaWt1dG8MCxIVdGhpcmRQYXJ0eURpc3BsYXlUeXBlGgdERUZBVUxUDBIDbHNvIhTeWybcoJ9pXSeN2t-k8A4SUbfhsygBMhQivAmfNSs_LkjXXZ7bPxilXgjMsQ&scc=1
As you can see from there that there is a request_visible_actions and I even added one that has no underscore in case I got the parameter wrong (requestvisibleactions).
Let me say that my app is being authenticated successfully by the API. I can get the user's profile after being authenticated and it is on the "insert moment" part that my app fails. My insert code:
var body = new Moment();
var target = new ItemScope();
target.Id = referenceId;
target.Image = image;
target.Type = "http://schemas.google.com/AddActivity";
target.Description = description;
target.Name = caption;
body.Target = target;
body.Type = "http://schemas.google.com/AddActivity";
var insert =
new MomentsResource.InsertRequest(
// this is a valid service instance as I am using this to query the user's profile
_plusService,
body,
id,
MomentsResource.Collection.Vault);
Moment result = null;
try
{
result = insert.Fetch();
}
catch (ThreadAbortException)
{
// User was not yet authenticated and is being forwarded to the authorization page.
throw;
}
catch (Google.GoogleApiRequestException requestEx)
{
// here I get a 401 Unauthorized error
}
catch (Exception ex)
{
} `
For the OAuth flow, there are two issues with your request:
request_visible_actions is what is passed to the OAuth v2 server (don't pass requestvisibleactions)
plus.moments.write is a deprecated scope, you only need to pass in plus.login
Make sure your project references the latest version of the Google+ .NET client library from here:
https://developers.google.com/resources/api-libraries/download/stable/plus/v1/csharp
I have created a project on GitHub showing a full server-side flow here:
https://github.com/gguuss/gplus_csharp_ssflow
As Brettj said, you should be using the Google+ Sign-in Button as demonstrated in the latest Google+ samples from here:
https://github.com/googleplus/gplus-quickstart-csharp
First, ensure you are requesting all of the activity types you're writing. You will know this is working because the authorization dialog will show "Make your app activity available via Google, visible to you and: [...]" below the text that starts with "This app would like to". I know you checked this but I'm 90% sure this is why you are getting the 401 error code. The following markup shows how to render the Google+ Sign-In button requesting access to Add activities.
<div id="gConnect">
<button class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-clientId="YOUR_CLIENT_ID"
data-accesstype="offline"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
Assuming you have a PlusService object with the correct activity type set in data-requestvisibleactions, the following code, which you should be able to copy/paste to see it work, concisely demonstrates writing moments using the .NET client and has been tested to work:
Moment body = new Moment();
ItemScope target = new ItemScope();
target.Id = "replacewithuniqueforaddtarget";
target.Image = "http://www.google.com/s2/static/images/GoogleyEyes.png";
target.Type = "";
target.Description = "The description for the activity";
target.Name = "An example of add activity";
body.Target = target;
body.Type = "http://schemas.google.com/AddActivity";
MomentsResource.InsertRequest insert =
new MomentsResource.InsertRequest(
_plusService,
body,
"me",
MomentsResource.Collection.Vault);
Moment wrote = insert.Fetch();
Note, I'm including Google.Apis.Plus.v1.Data for convenience.
Ah it's that simple! Maybe not? I am answering my own question and consequently accept it as the answer (after a few days of course) so others having the same issue may be guided. But I will definitely up-vote Gus' answer for it led me to the fix for my code.
So according to #class answer written above and as explained on his blog the key to successfully creating a moment is adding the request_visible_actions parameter. I did that but my request still failed and it is because I was missing an important thing. You need to add one more parameter and that is the access_type and it should be set to offline. The OAuth request, at a minimum, should look like: https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/plus.login&response_type=code&redirect_uri=http://localhost/&request_visible_actions=http://schemas.google.com/AddActivity&access_type=offline.
For the complete and correct client code you can get Gus' example here or download the entire dotnet client library including the source and sample and add what I added below. The most important thing that you should remember is modifying your AuthorizationServerDescription for the Google API. Here's my version of the authenticator:
public static OAuth2Authenticator<WebServerClient> CreateAuthenticator(
string clientId, string clientSecret)
{
if (string.IsNullOrWhiteSpace(clientId))
throw new ArgumentException("clientId cannot be empty");
if (string.IsNullOrWhiteSpace(clientSecret))
throw new ArgumentException("clientSecret cannot be empty");
var description = GoogleAuthenticationServer.Description;
var uri = description.AuthorizationEndpoint.AbsoluteUri;
// This is the one that has been documented on Gus' blog site
// and over at Google's (https://developers.google.com/+/web/signin/)
// This is not in the dotnetclient sample by the way
// and you need to understand how OAuth and DNOA works.
// I had this already, see my original post,
// I thought it will make my day.
if (uri.IndexOf("request_visible_actions") < 1)
{
var param = (uri.IndexOf('?') > 0) ? "&" : "?";
description.AuthorizationEndpoint = new Uri(
uri + param +
"request_visible_actions=http://schemas.google.com/AddActivity");
}
// This is what I have been missing!
// They forgot to tell us about this or did I just miss this somewhere?
uri = description.AuthorizationEndpoint.AbsoluteUri;
if (uri.IndexOf("offline") < 1)
{
var param = (uri.IndexOf('?') > 0) ? "&" : "?";
description.AuthorizationEndpoint =
new Uri(uri + param + "access_type=offline");
}
// Register the authenticator.
var provider = new WebServerClient(description)
{
ClientIdentifier = clientId,
ClientSecret = clientSecret,
};
var authenticator =
new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization)
{ NoCaching = true };
return authenticator;
}
Without the access_type=offline my code never worked and it will never work. Now I wonder why? It would be good to have some explanation.