ASP.NET Identity + Facebook login: Pass in "rerequest?" - facebook-graph-api

(Using ASP.NET Identity 2.1, Microsoft.Owin.Security.Facebook 3.0.1 in a Web API project)
From here: https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.2
This is because once someone has declined a permission, the Login Dialog will not re-ask them for it unless you explicitly tell the dialog you're re-asking for a declined permission.
You do this by adding the auth_type: rerequest flag to your FB.login() call:
FB.login(
function(response) {
console.log(response);
},
{
scope: 'user_likes',
auth_type: 'rerequest'
}
);
When you do that, the Login Dialog will re-ask for the declined permission. The dialog will look very much like the dialog in the section on re-asking for permissions but will let you re-ask for a declined permission.
So, using ASP.NET Identity's integration with Facebook login, I know how to pass in the requested scope, but if the user declines the permission, I need to pass in the extra parameter "auth_type" : 'rerequest." How do I do that?

You first add your custom FacebookAuthenticationProvider
public class FacebookProvider : FacebookAuthenticationProvider
{
public override void ApplyRedirect(FacebookApplyRedirectContext context)
{
//To handle rerequest to give some permission
string authType = string.Empty;
if (context.Properties.Dictionary.ContainsKey("auth_type"))
{
authType = string.Format("&auth_type={0}", context.Properties.Dictionary["auth_type"]);
}
//If you have popup loggin add &display=popup
context.Response.Redirect(string.Format("{0}{1}{2}", context.RedirectUri, "&display=popup", authType));
}
}
now in the startup you need to use this provider
var options = new FacebookAuthenticationOptions
{
AppId = "appid",
AppSecret = "secret",
Provider = new FacebookProvider
{
OnAuthenticated = async context =>
{
foreach (var x in context.User)
{
if (x.Key == "birthday")
{
context.Identity.AddClaim(new Claim("dateofbirth", x.Value.ToString()));
}
else
{
context.Identity.AddClaim(new Claim(x.Key, x.Value.ToString()));
}
}
context.Identity.AddClaim(new Claim("fb_accecctoken", context.AccessToken));
await Task.FromResult(context);
}
}
};
options.Scope.Add("public_profile");
options.Scope.Add("email");
options.Scope.Add("user_birthday");
options.Scope.Add("user_location");
app.UseFacebookAuthentication(options);
and finally in your account controller you need to set auth_type when you need
private const string XsrfKey = "xsrfkey";
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null, false)
{
}
public ChallengeResult(string provider, string redirectUri, string userId, bool isRerequest)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
IsRerequest = isRerequest;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public bool IsRerequest { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
if (IsRerequest)
{
properties.Dictionary["auth_type"] = "rerequest";
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}

I had the same issue when I wanted to ensure the user had accepted all my permissions. As you probably know this can be detected by calling the /me/permissions url.
So I eventually solved it by simply deleting my app from the user's account.
You can do so by doing a DELETE request on the /me/permissions URL as documented here.
This will remove all permissions you requested from the user, so next time you try authenticating him through Facebook, the prompt appears again.

Related

Blazor-Server side authentication with Cookie

I am trying to implement on a Blazor-Server side application a simple login against LDAP server and use cookie to store user claims. I have the MainLayout set to Authorized, if the user is not authenticated it will be re-direct to Login page. I have already tested the LDAP connection and it works properly, the problem is no matter what I do the cookie doesn't get created in the browser. When I run the POST command I see the HttpStatusCode.OK but the cookie it's not created and the browser re-direct again to login page of course.
Can someone please tell me what am I doing wrong? My code:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
AuthenticationController.cs
[ApiController]
public class AuthenticationController : Controller
{
[HttpPost]
[Route("authentication/login")]
public async Task<ActionResult> Login([FromBody]UserCredentials credentials)
{
string path = "LDAP://serveraddress.xxx";
try
{
using DirectoryEntry entry = new(path, credentials.Username, credentials.Password);
using DirectorySearcher searcher = new(entry);
searcher.Filter = $"(&(objectclass=user)(objectcategory=person)(samaccountname={credentials.Username}))";
var result = searcher.FindOne();
if (result != null)
{
List<Claim> claims = new();
claims.Add(new Claim(ClaimTypes.Name, credentials.Username));
//Get Groups
ResultPropertyCollection fields = result.Properties;
foreach (var group in result.Properties["memberof"])
{
var distinguishedName = new X500DistinguishedName(group.ToString());
var commonNameData = new AsnEncodedData("CN", distinguishedName.RawData);
var commonName = commonNameData.Format(false);
if (!string.IsNullOrEmpty(commonName))
{
claims.Add(new Claim(ClaimTypes.Role, commonName));
}
}
//Get Emails
foreach (var email in result.Properties["mail"])
{
claims.Add(new Claim(ClaimTypes.Email, email.ToString()));
}
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
AuthenticationProperties authProperties = new()
{
AllowRefresh = true,
IssuedUtc = DateTime.Now,
ExpiresUtc = DateTimeOffset.Now.AddDays(1),
IsPersistent = true,
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
return Ok();
}
else
{
return NotFound("User Not Found!");
}
}
catch (Exception)
{
return NotFound("Login credentials is incorrect!");
}
}
[HttpPost]
[Route("authentication/logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
}
Login.razor
#page "/login"
#page "/login/{ErrorMessage}"
#layout CenteredBlockLayout
#attribute [AllowAnonymous]
<MudPaper Elevation="25" Class="pa-8" Width="100%" MaxWidth="500px">
<MudItem><img src="/images/logo.svg" alt="Logo" style="width:400px; height:50px;" /></MudItem>
<MudText Typo="Typo.h4" GutterBottom="true">Sign In</MudText>
<MudTextField #bind-Value="#Username" T="string" Label="Username"/>
<MudTextField #bind-Value="#Password" T="string" Label="Password"/>
<MudButton OnClick="(() => PerformLoginAsync())">Sign In</MudButton>
</MudPaper>
#if (!string.IsNullOrEmpty(ErrorMessage))
{
<MudAlert Severity="Severity.Error">#ErrorMessage</MudAlert>
}
Login.razor.cs
public partial class Login
{
public string Username { get; set; }
public string Password { get; set; }
[Parameter]
public string ErrorMessage { get; set; }
[Inject]
HttpClient Client { get; set; }
[Inject]
private NavigationManager NavMan { get; set; }
private async Task PerformLoginAsync()
{
if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
{
UserCredentials cred = new UserCredentials
{
Username = Username,
Password = Password
};
var serialized = JsonConvert.SerializeObject(cred);
var stringContent = new StringContent(serialized, Encoding.UTF8, "application/json");
using var result = await Client.PostAsync($"NavMan.BaseUri}authentication/login", stringContent);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
NavMan.NavigateTo("/", true);
}
else
{
ErrorMessage = await result.Content.ReadAsStringAsync();
}
}
}
}
I believe you need to append the cookie to the response. I haven't tested this with your code but it should work something like this:
HttpContext.Response.Cookies.Append("my_cookie", claimsString, new CookieOptions()
{
Domain = "mydomain.com",
SameSite = SameSiteMode.Lax,
Secure = true,
Path = "/",
Expires = DateTime.UtcNow.AddDays(1)
}
(These cookie options are just an example, of course. Tailor them to your specific needs.)
Keep in mind that you'll need to convert your claims to a string so that you can store it as the value in a cookie. In our case we store claims in a JWT, so that's what gets stored in the cookie. Here's how I do it:
public string CreateJWT(HttpContext httpContext, User user)
{
var handler = new JwtSecurityTokenHandler();
var descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[] {
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
new Claim(ClaimTypes.Email, user.Email),
}),
Expires = DateTime.UtcNow.AddMinutes(Config.AccessExpMins),
Issuer = Config.Issuer,
Audience = Config.Audience,
SigningCredentials = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256)
};
var token = handler.CreateJwtSecurityToken(descriptor);
var accessToken = handler.WriteToken(token);
httpContext.Response.Cookies.Append("my_cookie", accessToken, new CookieOptions()
{
Domain = Config.CookieDomain,
SameSite = SameSiteMode.Lax,
Secure = true,
Path = "/",
Expires = DateTime.UtcNow.AddMinutes(Config.AccessExpMins)
});
return accessToken;
}
As for parsing the JWT, I'm sure there are a number of ways to go about it. The one that worked for me was this one.

How to manage Facebook login to avoid authentication frequently in Xamarin.Forms?

I use following code for Facebook login and access user information like albums and pictures. I have set code to get access token using following code. Now, the problem is I need to get access token everytime when user open application. However, once user authenticate, application will not ask for authenticate until user close the application. But it will ask for authenticate again after user reopen application. This way user will frustrate if they will ask to authentication everytime they will try to access albums or any other things of facebook.
Is there anyway to skip this? I mean once user provided access of Facebook, application must not ask for login(authenticate). I will have access token but I don't know how to use to play with authentication. So, we can avoid authentication frequently.
My Code:
public class FacebookService : IFacebookService
{
private readonly string[] permissions = { "public_profile", "email", "user_birthday", "user_photos" };
public event EventHandler<FacebookUser> LoginCompleted;
public string Token => AccessToken.CurrentAccessToken.TokenString;
public void Logout()
{
LoginManager manager = new LoginManager();
manager.LogOut();
}
public void LogInToFacebook()
{
if (AccessToken.CurrentAccessToken == null)
{
ObtainNewToken(LogInToFacebook);
return;
}
var fields = new[] { "name", "email", "birthday", "gender", "picture" };
var query = $"/me?fields={string.Join(",", fields)}";
var token = AccessToken.CurrentAccessToken.TokenString;
var request = new GraphRequest(query, null, token, null, "GET");
request.Start((connection, result, error) =>
{
if (error != null)
{
HandleError(error.LocalizedDescription);
}
else
{
var userInfo = result as NSDictionary;
var id = userInfo["id"].ToString();
var email = userInfo["email"].ToString();
var name = userInfo["name"].ToString();
var birthday = userInfo["birthday"].ToString();
var gender = userInfo["gender"].ToString();
var picture = ((userInfo["picture"] as NSDictionary)["data"] as NSDictionary)["url"].ToString();
var args = new FacebookUser(id, email, name, birthday, gender, picture);
LoginCompleted?.Invoke(this, args);
}
});
}
public async System.Threading.Tasks.Task RequestAlbums(Action<FacebookAlbum[]> callback)
{
if (AccessToken.CurrentAccessToken == null)
{
ObtainNewTokenForAlbum(callback);
return;
}
using (HttpClient client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
var host = "https://graph.facebook.com/";
var json = await client.GetStringAsync($"{host}me/albums");
var data = JObject.Parse(json).First.First.ToString();
var albums = JsonConvert.DeserializeObject<FacebookAlbum[]>(data);
var getPhotosTasks = new List<System.Threading.Tasks.Task>();
foreach (var album in albums)
getPhotosTasks.Add(System.Threading.Tasks.Task.Run(() => RequestPhotos(album)));
await System.Threading.Tasks.Task.WhenAll(getPhotosTasks.ToArray());
callback(albums);
}
catch (Exception ex1)
{
HandleError(ex1.Message);
}
}
}
private void ObtainNewTokenForAlbum(Action<FacebookAlbum[]> callback)
{
var login = new LoginManager();
login.LogInWithReadPermissions(permissions, null, (r, e) =>
{
if (e == null && !r.IsCancelled)
{
RequestAlbums(callback);
}
else
HandleError(e?.LocalizedDescription);
});
}
private async System.Threading.Tasks.Task RequestPhotos(FacebookAlbum album)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
try
{
var host = "https://graph.facebook.com/";
var json = await client.GetStringAsync($"{host}{album.Id}/photos?fields=source,picture");
var data = JObject.Parse(json)["data"].ToString();
album.Photos = JsonConvert.DeserializeObject<FacebookPicture[]>(data);
}
catch (Exception exc)
{
HandleError(exc.Message);
}
}
}
private void ObtainNewToken(Action callback)
{
var login = new LoginManager();
login.LogInWithReadPermissions(permissions, null, (r, e) =>
{
if (e == null && !r.IsCancelled)
callback?.Invoke();
else
HandleError(e?.LocalizedDescription);
});
}
private void HandleError(string messageDescription)
{
messageDescription = messageDescription ?? "Request was cancelled";
_notificationService.DisplayNotification(messageDescription, Colors.d8Red);
}
}
AppDelegate
public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
{
UAirship.TakeOff();
RegisterServices();
SetupFacebookSDK();
FFImageLoading.Forms.Touch.CachedImageRenderer.Init();
var dummy = new FFImageLoading.Forms.Touch.CachedImageRenderer();
Xamarin.Forms.Forms.Init();
LoadApplication(new App());
UIApplication.SharedApplication.StatusBarHidden = false;
UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false);
_networkManager = new NetworkManager();
OverrideDefaultListViewCustomActionsColors();
UAirship.Push.UserPushNotificationsEnabled = true;
new PhotoAccessChecker();
return ApplicationDelegate.SharedInstance.FinishedLaunching(uiApplication, launchOptions);
}
void SetupFacebookSDK()
{
FacebookProfile.EnableUpdatesOnAccessTokenChange(true);
FacebookSettings.AppID = "000000000049000";
FacebookSettings.DisplayName = "MyProduct";
}
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
return ApplicationDelegate.SharedInstance.OpenUrl(application, url, sourceApplication, annotation);
}
I guess you forgot initialize FBSDK in AppDelegate.
Check your code if return ApplicationDelegate.SharedInstance.FinishedLaunching (application, launchOptions); has been executed in FinishedLaunching.
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
Settings.AppID = appId;
Settings.DisplayName = appName;
// ...
// This method verifies if you have been logged into the app before, and keep you logged in after you reopen or kill your app.
return ApplicationDelegate.SharedInstance.FinishedLaunching (application, launchOptions);
}
public override bool OpenUrl (UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
// We need to handle URLs by passing them to their own OpenUrl in order to make the SSO authentication works.
return ApplicationDelegate.SharedInstance.OpenUrl (application, url, sourceApplication, annotation);
}

Auth0 OWIN API not validating JWT token when published via Docker Container on AWS EC2

My OWIN Web.API 2 Hosted on EC2 will not authorize a JWT token. I have tested the functionality locally with out a problem but once I publish it out to my docker container hosted on EC2 it responds with a 401. I am using the default RS256 Algorithm and these settings:
var domain = Environment.GetEnvironmentVariable("AUTH0_DOMAIN");
var audience = Environment.GetEnvironmentVariable("AUTH0_CLIENT_IDS");
var keyResolver = new OpenIdConnectSigningKeyResolver(domain);
appBuilder.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = audience,
ValidIssuer = domain,
IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) => keyResolver.GetSigningKey(identifier)
}
});
My Endpoint simply states whether your are authenticated or not.
[Authorize]
[Route("secure")]
public HttpResponseMessage GetSecured()
{
var userId = ClaimsPrincipal.Current.Identity.GetUserId();
return Request.CreateResponse($"Hello, {userId}! You are currently authenticated.");
}
Here is my Startup config:
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.UseCors(CorsOptions.AllowAll); //must be first
Auth0Config.Register(appBuilder);
var httpConfiguration = new HttpConfiguration();
httpConfiguration.MapHttpAttributeRoutes();
UnityConfig.Register(httpConfiguration);
appBuilder.UseWebApi(httpConfiguration);
}
I no longer use the OWIN pipeline but from a previous project here is how I had it configured. It looks like you are using OpenID, I did not. Not sure if this helps.
var issuer = AppSettings.Auth0Domain;
var audience = AppSettings.Auth0ClientID;
var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["Auth0ClientSecret"]);
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] {audience},
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
Provider = new Auth0AuthenticationProvider()
});
EDIT Added Auth0AuthenticationProvider
public class Auth0AuthenticationProvider : IOAuthBearerAuthenticationProvider
{
private string token;
public Task ApplyChallenge(OAuthChallengeContext context)
{
return Task.FromResult<object>(null);
}
public Task RequestToken(OAuthRequestTokenContext context)
{
token = context.Token;
return Task.FromResult<object>(null);
}
public Task ValidateIdentity(OAuthValidateIdentityContext context)
{
if (string.IsNullOrEmpty(token))
return Task.FromResult<object>(null);
var notPadded = token.Split('.')[1];
var padded = notPadded.PadRight(notPadded.Length + (4 - notPadded.Length % 4) % 4, '=');
var urlUnescaped = padded.Replace('-', '+').Replace('_', '/');
var claimsPart = Convert.FromBase64String(urlUnescaped);
var obj = JObject.Parse(Encoding.UTF8.GetString(claimsPart, 0, claimsPart.Length));
// simple, not handling specific types, arrays, etc.
foreach (var prop in obj.Properties().AsJEnumerable())
{
switch (prop.Name)
{
case "app_metadata":
SetAppMetadataClaims(context, prop.Value.ToString());
break;
}
}
return Task.FromResult<object>(null);
}
private static void SetAppMetadataClaims(OAuthValidateIdentityContext context, string jsonString)
{
var appMetadata = JsonConvert.DeserializeObject<Auth0AppMetaDataModel>(jsonString);
if(!context.Ticket.Identity.HasClaim("AccountId", appMetadata.accountId.ToString()))
context.Ticket.Identity.AddClaim(new Claim("AccountId", appMetadata.accountId.ToString()));
if (!context.Ticket.Identity.HasClaim("ClientId", appMetadata.clientId.ToString()))
context.Ticket.Identity.AddClaim(new Claim("ClientId", appMetadata.clientId.ToString()));
if (!context.Ticket.Identity.HasClaim("IsActive", appMetadata.isActive.ToString()))
context.Ticket.Identity.AddClaim(new Claim("IsActive", appMetadata.isActive.ToString()));
if (appMetadata.roles == null)
return;
foreach (var role in appMetadata.roles)
{
if (context.Ticket.Identity.HasClaim(ClaimTypes.Role, role))
continue;
context.Ticket.Identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
}
}
The problem was not with Auth0 using HS256 or RS256 but instead with the base image I was using. Mono was failing silently most likely blocking the validation of my token. I have switched over to dotnet core in order to use the docker image: microsoft/dotnet:latest
My Startup file now appears like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("CorsPolicy");
var options = new JwtBearerOptions
{
Audience = Configuration["Auth0:ApiIdentifier"],
Authority = $"https://{Configuration["Auth0:Domain"]}/"
};
app.UseJwtBearerAuthentication(options);
...
}

Extracting users friend list from facebook graph api v2.3

I am using facebook SDK 4.0.1. I gave permission for user_friends but I am not able to get friend list of the user. I am getting the count of the user's friends but I want the name of the user's friends and ids
private FacebookCallback<LoginResult> mcallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
Log.d("Access Token", accessToken.toString());
Profile profile = Profile.getCurrentProfile();
// Log.d("PROFILE","PROFILE IMAHE"+profile.getName());
displayWelcomeMessage(profile);
GraphRequestBatch batch = new GraphRequestBatch(
GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
try {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constant.KEY_ID,jsonObject.getString("id"));
editor.putString(Constant.KEY_USER_NAME,jsonObject.getString("name"));
editor.putString(Constant.KEY_USER_FNAME,jsonObject.getString("first_name"));
editor.putString(Constant.KEY_USER_LNAME,jsonObject.getString("last_name"));
// hometown = jsonObject.getJSONObject("hometown");
// editor.putString(Constant.KEY_USER_HOMETOWN,hometown.getString("name"));
editor.putString(Constant.KEY_USER_EMAIL,jsonObject.getString("email"));
editor.putString(Constant.KEY_USER_GENDER,jsonObject.getString("gender"));
// editor.putString(Constant.KEY_USER_DOB,jsonObject.getString("birthday"));
editor.commit();
// town = hometown.getString("name");
// personId = jsonObject.getString("id");
// gen = jsonObject.getString("gender");
// email = jsonObject.getString("email");
Log.d("RESPONCE", "RESPONCE user=" + jsonObject.toString());
Log.d("RESPONCE", "RESPONCE =" + response.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
}),
GraphRequest.newMyFriendsRequest(accessToken, new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray jsonArray, GraphResponse response) {
//Lo Application code for users friends
Log.d("RESPONCE FRIEND", "RESPONCE FRIEND=" + jsonArray.toString());
Log.d("RESPONCE FRIEND", "RESPONCE =" + response.toString());
response.getJSONArray();
}
}));
batch.addCallback(new GraphRequestBatch.Callback() {
#Override
public void onBatchCompleted(GraphRequestBatch graphRequests) {
// Application code for when the batch finishes
}
});
batch.executeAsync();
Since v2.0 of the Graph API, it is only possible to get friends who authorized your App too - for privacy reasons. More information can be found in this and many other threads about that exact same question: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app

Get Rendered HTML From Sitecore Item

I need to get the rendered HTML output from a given Sitecore item, assuming it has a layout. I need it to be the latest version of the rendered content whether it's published or not. Using a web request approach like WebClient or HtmlAgility pack will not work because they make the request as an anonymous user which will only render the latest published version (and I need the latest version no matter the state.) Any thoughts? I have everything working I just cant find a way to impersonate or elevate the rights while I execute the page requests.
You could go the WebClient or HtmlAgility pack, but silently login the user based on a token in the query string:
public static class UserExtensions
{
public const string TokenKey = "UserToken";
public const string TokenDateKey = "UserTokenDate";
public static ID CreateUserToken(this User user)
{
if (user.IsAuthenticated)
{
var token = ID.NewID;
user.Profile.SetCustomProperty(TokenKey, token.ToString());
user.Profile.SetCustomProperty(TokenDateKey, DateTime.Now.ToString());
user.Profile.Save();
return token;
}
else
return ID.Null;
}
public static bool IsTokenValid(this User user, string token, TimeSpan maxAge)
{
var tokenId = ID.Null;
if (ID.TryParse(token, out tokenId))
{
var minDate = DateTime.Now.Add(-maxAge);
var tokenDateString = user.Profile.GetCustomProperty(TokenDateKey);
var tokenDate = DateTime.MinValue;
DateTime.TryParse(tokenDateString, out tokenDate);
if (tokenDate < minDate)
return false;
var storedToken = user.Profile.GetCustomProperty(TokenKey);
var storedTokenId = ID.NewID;
if (ID.TryParse(storedToken, out storedTokenId))
return storedTokenId == tokenId;
}
return false;
}
}
Then patch in a HttpRequestProcessor to look for the token:
public class SilentUserLogin : HttpRequestProcessor
{
public TimeSpan MaximumAge
{
get;
set;
}
public override void Process(HttpRequestArgs args)
{
var userValue = args.Context.Request.QueryString["user"];
var tokenValue = args.Context.Request.QueryString["token"];
if (!string.IsNullOrEmpty(userValue) && !string.IsNullOrEmpty(tokenValue))
{
// find user
var user = User.FromName(userValue, AccountType.User);
if (user != null)
{
// Check token is valid
if ((user as User).IsTokenValid(tokenValue, MaximumAge))
{
// log user in
AuthenticationManager.Login(user as User);
}
else
Log.Audit("User token has expired for user: '{0}'".FormatWith(user.Name), this);
}
else
Log.Audit("Failed to locate auto login user " + userValue, this);
}
}
Patch this in with a config file:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<httpRequestBegin>
<processor type="Namespace.SilentUserLogin,Assembly" patch:after="*[#type='Sitecore.Pipelines.HttpRequest.StartMeasurements, Sitecore.Kernel']">
<MaximumAge>00:02:00</MaximumAge>
</processor>
</httpRequestBegin>
</pipelines>
</sitecore>
</configuration>
Finally, call the page via WebClient or HtmlAgility:
var token = Sitecore.Context.User.CreateUserToken();
var url = new UrlString();
url.HostName = HttpContext.Current.Request.Url.Host;
url.Protocol = HttpContext.Current.Request.IsSecureConnection ? "https" : "http";
url.Path = "/";
url["sc_itemid"] = myItem.ID.ToString();
url["sc_lang"] = myItem.Language.ToString();
// Add parameters to allow accessing the master DB
url["user"] = Sitecore.Context.User.Name;
url["token"] = token.ToString();
// Call the url here
This code was cribbed from a similar situation where I needed a URL to feed to a PDF generation library, which behind the scenes fired up IE and hit the site as an anonymous user. This way we could pass a limited time security token via the query string.
You can setup a "preview" site that shows content from the master database as opposed to the public-facing published content. This article will help setting that up: How to Setup a Sitecore Preview Site to Review Content Before Publishing
Once you have this setup on a unique URL, you can then make a WebRequest to pages or use HtmlAgilityPack.