How to get external login profile picture from Microsoft account in asp.net core - asp.net

how can I get profile picture from Microsoft account using Microsoft.AspNetCore.Authentication.Facebook library? I tried using Claims, but they don't have profile picture value... I also tried looking in account's source control by checking image url, but I noticed that the url is made of some parameters that I can't get with claims, so I can't construct url like I can with facebook... Can someone can help me?

You can obtain the profile picture from Microsoft accounts by using Microsoft Graph:
https://developer.microsoft.com/en-us/graph/quick-start
Specific instructions on how to request the profile picture:
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/profilephoto_get
If you follow the quick start (select asp.net, click "Get an app ID and secret" and download the sample code), it's easy to obtain the data like so:
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
var photoStream = await graphService.GetCurrentUserPhotoStreamAsync(graphClient);
EDIT: Sorry, forgot the asp.net core part (it doesn't seem that Microsoft.Identity.Client is available for asp.net core).
In ExternalLoginCallback you can obtain the access token from the ExternalLoginInfo object returned by var info = await _signInManager.GetExternalLoginInfoAsync();
Remember to set SaveTokens to true when configuring authentication (otherwise the access token won't be available):
services.AddAuthentication()
.AddMicrosoftAccount(options =>
{
options.ClientId = Configuration["ExternalProviders:Microsoft:ClientId"];
options.ClientSecret = Configuration["ExternalProviders:Microsoft:ClientSecret"];
options.SaveTokens = true;
...
Then it's just a matter of making a http request - something like this:
var httpClient = new HttpClient();
httpClient.SetBearerToken(info.AuthenticationTokens.Where(t => t.Name.Equals("access_token")).First().Value);
var pictureResult = httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photo/$value").Result;

Related

Using ResourceOwnerPassword flow for .NET Core 3.1/IdentityModel 5.1

I am playing with the IdentityServer4. Part of that I am trying to build a client using IdentityModel 5.1.0 and trying to use following piece of code available here
// request token
var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.client", "secret");
var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("alice", "password", "api1");
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");
But this is giving me following error.
error CS1729: 'TokenClient' does not contain a constructor that takes 3 arguments
From the docs, it looks like that page is only applicable to Core 1.0. When I change the documentation to 3.1.0, I get
Sorry This pages does not exist yet
Does this mean that ResourceOwnerPassword flow is not supported for the .NET Core 3.1?
Ctrl + clicking on the method takes to to its signature, where you can find out the specific parameters that the method expects.
Browsing the repo, I've found this snippet on using the password credentials token request:
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
ClientId = "client",
UserName = "user",
Password = "password",
Scope = "scope",
Resource = { "resource1", "resource2" }
});
another overload:
var response = await tokenClient.RequestPasswordTokenAsync(userName: "user", password: "password", scope: "scope");
Or see the actual method definition or another helper.
A useful tip: popular packages usually have a lot of tests. You can check them out to learn how to use the library.

ASP.Net Identity reset password with website and web api

We have 2 separate ways for people to perform a forgot password:
1. Via the website - mywebsite.com/account/forgotpassword
2. Via our App - Clicking the "Forgot Password" passes the users email address to our asp.net web api which in turn creates the code and sends the email.
Clicking the link in the email brings up the correct page where we can enter the email and new password. When resetting the password using option 1, it works fine. Using option 2 gives an invalid token error. Both the website and web api are on the same server.
Here's the Web api code:
var user = await UserManager.FindByEmailAsync(email);
var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = $"/Account/ResetPassword?userId={user.Id}&code={code}";
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/emails/ResetPassword.html");
var body = GenerateEmailBody(user);
await UserManager.SendEmailAsync(user.Id, "Reset Password", body);
Here's the website code
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null)// || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// Send an email with this link
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
var body = GenerateEmailBody(user);
await UserManager.SendEmailAsync(user.Id, "Reset Password", body);
I verified that the UserTokenProvider is the same in both as well.
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("IdentityStuff"));
I read that MachineKey can cause this issue except we're only using a single server.
An additional piece of info that is worth mentioning is when the website was created, it didn't have identity added to it. This was an after thought. The web api started off with identity.
For clarity purposes I thought I would answer my question.
Instead of have the reset logic in both the website and api, I have both the website and our app call the api to reset the password.
I did, however run into an additional problem when using a load balancer. Since one server may create the code for the reset and another may respond to the link, we run into the same issue.
To fix this problem, I have a DNS entry that always points to a single server which is used to create the code as well as actually reset the password. This eliminates the issue of getting an invalid token.
HTH.

X509Certificate2 Access denied error

EDIT: This is my final code after taking your(#DalmTo) advice:
public static AnalyticsService Authenticate()
{
string[] scopes = new string[] { AnalyticsService.Scope.Analytics,
AnalyticsService.Scope.AnalyticsManageUsers};
string keyFilePath = #"G:\PleskVhosts\mydomainname\httpdocs\App_Data\API Project-2f74017ed363.p12"; // found in developer console
string serviceAccountEmail = "myconsoleapiaccount#developer.gserviceaccount.com"; // found in developer console
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate));
AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "myappname",
});
Thank you so much for the tutorial you linked me, I examined it carefully and your code was so much less work than trying to do it manually. I am aware of the tips you have given me, and I have necessary permissions for that account in my Google Analytics account. I followed your tutorial, and it works like a charm in my localhost, but when I publish my website, this is the current error I am getting this error:
{"Message":"Access is denied.\r\n","StackTrace":" at System.Security.Cryptography.X509Certificates.X509Store.Add(X509Certificate2 certificate)\r\n at Thunder.Main.Default.Authenticate()\r\n at Thunder.Main.Default.GetChartData()","ExceptionType":"System.Security.Cryptography.CryptographicException"}
I have contacted with my hosting provider, and they are telling me that they won't be making changes in IIS, I've added trust level full tag to the web.config, but I am still getting this error.I am currently working on it, but if you have any advices, please let me know. I will update here If I can come up with a solution. Thanks!
As mentioned above you need to configure IIS but as our case, some time you need to check the permission of the following folder:
C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
If you set X509KeyStorageFlags parameter it will create a key file in this folder. In my case there was a difference in permission of this folder. Pool account was not added in the mentioned folder.
You really are making things harder for yourself here. I am not sure whats wrong with your code. TBH I have never tried doing it manually because I use the client library
NuGet Package
PM> Install-Package Google.Apis.Analytics.v3
Authentication with a service account.
You need to send the full path to the key file or sometimes it complains. Ideally it should be out side of the web root but it needs to be someplace that the webserver has access to read it since you are using asp for this.
string[] scopes =
new string[] {
AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data
AnalyticsService.Scope.AnalyticsManageUsers}; // View Google Analytics data
string keyFilePath = #"c:\file.p12" ; // found in developer console
string serviceAccountEmail = "xx#developer.gserviceaccount.com"; // found in developer console
//loading the Key file
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail)
{Scopes = scopes }.FromCertificate(certificate));
Creating Service
You pass the credential created above to the service. All of your requests will then go though the service.
AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Analytics API Sample",
});
Tips
For a service account to work with Google Analytics it must have access to your Google Analytics account. Go to the Google Analytics website admin section create a new user at the account level it must be the account level. Did I mention it wont work if it isn't the account level.
Code is taken from my tutorial series. Google Analtics with C# enjoy

Google OpenId Connect migration: getting the openid_id in ASP.NET app

I've gone through plenty of Google documentation and SO Q/A's but with no luck. I wonder if anyone has yet succesfully used the OpenId to OpenId Connect migration as advised by Google.
This is what we used to do:
IAuthenticationResponse response = _openid.GetResponse();
if (response != null) {
//omitted for brevity
} else {
IAuthenticationRequest req = _openid.CreateRequest("https://www.google.com/accounts/o8/id");
req.AddExtension(new ClaimsRequest
{
Country = DemandLevel.Request,
Email = DemandLevel.Request,
Gender = DemandLevel.Require,
PostalCode = DemandLevel.Require,
TimeZone = DemandLevel.Require
});
req.RedirectToProvider();
}
That was done using a version of DotNetOpenAuth that dates back a few years. Because Google has deprecated OpenId authentication we are trying to move over to OpenID Connect. The key question here is: can I somehow get my hands on the OpenId identifier (in the form of https://www.google.com/accounts/o8/id?id=xyz) using the latest version of DotNetOpenAuth library or by any other means?
I have tried the latest DotNetOpenAuth and I can get it to work but it gives me a new Id (this was expected). I have also tried the Javascript way by using this URL (line breaks for readibility):
https://accounts.google.com/o/oauth2/auth?
scope=openid%20profile%20email
&openid.realm=http://localhost/palkkac/
&client_id=//here is the client id I created in google developer console
&redirect_uri=http://localhost/palkkac/someaspxpagehere
&response_type=id_token%20token
I checked (using Fiddler) the realm value that we currently send using the old DotNetOpenAuth code and it is http://localhost/palkkac/. I've put the same realm in the url above. The redirect url starts with the realm value but it is not entirely the same.
When I redirect to a simple page that parses the id_token and decrypts it (using the https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=zyx endpoint) I get this:
audience "client id is here"
email "mikkark#gmail.com"
expires_in 3597
issued_at //some numbers here
issued_to "client id is here"
issuer "accounts.google.com"
user_id "here is a sequence of numbers, my id in the OpenID Connect format that is"
verified_email true
So there is no sign of the openid_id field that you would expect to find here, though the whole structure of the message seems different from the Google docs, there is no field titled sub, for example. I wonder if I'm actually using the wrong endpoint, parameters or something?
What I have been reading is the migration guide: https://developers.google.com/accounts/docs/OpenID. I skipped step 2 because it seemed like an optional step. In step 3 the field openid_id is discussed and I would like to get that to work as a proof-of-concept first.
We registered the app on Google in order to create the client id etc. There are now also numerous allowed redirect url's as well as javascript origins listed in the Google dev console. Let me know if those might mess up the system and I'll post them here for review.
Side note: we are supposed to be moving our app behind a strictly firewalled environment where we would need to open ports in order to do this on the server side. Therefore, a client-side Javascript solution to access Google combined with HTTPS and redirecting the result to the server would be prefered (unless there are other issues that speak against this).
There are other resources on SO regarding this same issue, although all of these seem to use different libraries on the server side to do the job and nobody seems to have made any attempts at using Javascript:
Here (https://stackoverflow.com/questions/22842475/migrating-google-openid-to-openid-connect-openid-id-does-not-match) I think the problem was resolved by setting the realm to be the same as in the old OpenId2.0 flow. This does not seem to work in my case.
over here the openid_id field is also missing, but the problem here is more about how to request the id_token from Google using libraries other than DotNetOpenAuth.
and in here there seem to be similar problems getting Google to return the openid_id field.
You can use the GoogleAuthentication owin middleware.
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
{
SignInAsAuthenticationType = signAs,
AuthenticationType = "Google",
ClientId = "xxx.apps.googleusercontent.com",
ClientSecret = "xx",
CallbackPath = PathString.FromUriComponent("/oauth2callback"),
Provider = new GoogleOAuth2AuthenticationProvider
{
OnApplyRedirect = context =>
{
context.Response.Redirect(context.RedirectUri + "&openid.realm=https://mydomain.com/"); // DotNetOpenAuth by default add a trailing slash, it must be exactly the same as before
}
},
BackchannelHttpHandler = new MyWebRequestHandler()
}
Then, add a new class called MyWebRequestHandler:
public class MyWebRequestHandler : WebRequestHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var httpResponse = await base.SendAsync(request, cancellationToken);
if (request.RequestUri == new Uri("https://www.googleapis.com/plus/v1/people/me")) return httpResponse;
var configuration = await OpenIdConnectConfigurationRetriever.GetAsync("https://accounts.google.com/.well-known/openid-configuration", cancellationToken); // read the configuration to get the signing tokens (todo should be cached or hard coded)
// google is unclear as the openid_id is not in the access_token but in the id_token
// as the middleware dot not expose the id_token we need to parse it again
var jwt = httpResponse.Content.ReadAsStringAsync().Result;
JObject response = JObject.Parse(jwt);
string idToken = response.Value<string>((object)"id_token");
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
try
{
SecurityToken token;
var claims = tokenHandler.ValidateToken(idToken, new TokenValidationParameters()
{
ValidAudience = "xxx.apps.googleusercontent.com",
ValidIssuer = "accounts.google.com",
IssuerSigningTokens = configuration.SigningTokens
}, out token);
var claim = claims.FindFirst("openid_id");
// claim.Value will contain the old openid identifier
if (claim != null) Debug.WriteLine(claim.Value);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
return httpResponse;
}
}
If like me you found this not really straightforward, please help by upvoting this issue https://katanaproject.codeplex.com/workitem/359

DropboxServiceProvider api with .Net

Trying to use Spring Net Social Dropbox
OAuthToken oauthToken = dropboxServiceProvider.OAuthOperations.FetchRequestTokenAsync(callBackUrl, null).Result;
Console.WriteLine("Done");
OAuth1Parameters parameters = new OAuth1Parameters();
parameters.Add("locale", CultureInfo.CurrentUICulture.IetfLanguageTag); // for a localized version of the authorization website
string authenticateUrl = dropboxServiceProvider.OAuthOperations.BuildAuthorizeUrl(oauthToken.Value, parameters);
Console.WriteLine("Redirect user for authorization");
Process.Start(authenticateUrl);
After redirecting user to authenticate him with dropbox how to get the request access token as I am the request would be going to call back url.
Can I create new instance of OAuthToken and new instance of dropboxserviceprovider and use it to get the access token.
AuthorizedRequestToken requestToken = new AuthorizedRequestToken(oauthToken, null);
OAuthToken oauthAccessToken = dropboxServiceProvider.OAuthOperations.ExchangeForAccessTokenAsync(requestToken, null).Result;
Console.WriteLine("Done");
/* API */
Console.WriteLine(oauthAccessToken.Value);
Console.WriteLine(oauthAccessToken.Secret);
IDropbox dropbox = dropboxServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret);
You can store the access token in the session.
You can create a DropboxServiceProvider any time you need, what's important is the oauth access token.
Take a look to the MVC quickstart provided in the package.

Resources