Client Server Facebook Registration / log in flow - c#

I have a problem implementing a Facebook Login on my ASP.NET website. I have both .NET Facebook SDK and the Javascript SDK installed in my site. I can't understand the flow that I need to implement in order to make it work.
In my app, I just need the email to register the user, give him the option to choose a username, and be able to login if he clicks the Facebook log in button (a custom one, it's not the official Facebook log in button).
I prefer a seamless login in which I get login the user via Ajax request to the server and set a cookie on the server instead of a redirect.
What is the registration and login flow that I need to implement to make it work using Ajax?
What I tried to do is to get the token on the client, but when I get the Token, I can't use it on the server, I need a code in order to get an active Token.
On my site I have both a custom Facebook signup and Facebook login buttons.
In my database I have the following columns for Facebook:
facebook_id
token
token_expiration
Here's the client code that I get the accessToken, userId and use it to get the user email:
function fb_login() {
FB.login(function (response) {
if (response.authResponse) {
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function (response) {
user_email = response.email; //get user email
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'email'
});
}

Related

Auth0 UWP client - don't show previously logged in user

I am using the Auth0 client for UWP as described here: https://auth0.com/docs/quickstart/native/windows-uwp-csharp/01-login.
Everything is working fine, but for my application it is a security risk to show the previously logged in user screen when the Auth0 window appears, and I am wondering if there is a way to change this.
Edit: I've tried
// Create an instance of the Auth0 client
Auth0Client client = new Auth0Client(new Auth0ClientOptions
{
Domain = resources.GetString("Auth0Domain"),
ClientId = resources.GetString("Auth0ClientID"),
LoadProfile = false
});
IdentityModel.OidcClient.LoginResult loginResult = await client.LoginAsync();
// Access the logged in user's data
if (!loginResult.IsError)
{
...
}
You have to customize login page on Auth0 Dashboard navigating to Hosted Pages and enabling Customize Login Page and set rememberLastLogin: false in content.
Related links:
Custom Login Page(login required)

accessing facebook private messages using access token using Facebook API

We have angularJs & C# web aplication.
We are planning to use our facebook page to handle our customer issues and complaints.
We will show facebook visitor posts in our website so our representative notice it and reply on same. (may be new comment or reply existing)
Our representative ask customer to send private message and then user initiate message to us and then we can see that message in our website and reply to that message through our website.
By this way we will able to sort out problems of our customer through our application.
public static FacebookClient GetClientApplicationAccessToken(FacebookClient client)
{
dynamic accessToken = client.Get("oauth/access_token", new
{
client_id = "my_ApplicationId",
client_secret = "my_AppSecretKey",
grant_type = "client_credentials"
});
client.AccessToken = accessToken.access_token;
return client;
}
public static dynamic GetFacebookPosts(string pageId)
{
var client = new FacebookClient();
GetClientApplicationAccessToken(client);
dynamic postObject = client.Get("/" + pageId + "/feed?fields=message,from,created_time,full_picture");
dynamic postJson = JsonConvert.DeserializeObject(posts);
return postJson;
}
By this access token we are able to fetch Facebook post, but not possible when we try to fetch conversation between Our Facebook page & our customers through private messages.
dynamic postdaObject = newclient.Get("me?fields=conversations{messages{created_time,message}}");
I think when we use access token from above method i.e.GetClientApplicationAccessToken() it is not working. but if I replace hard coded user access token then it's working. As our application end user will see Facebook messages and will reply to them, it does not require FaceBook Login button. We need some permanent access token by which we can fetch private messages from Facebook without any login button. Kindly help me to solve this issue.

How to convert bearer token into authentication cookie for MVC app

I have a 3 tier application structure. There is a cordova js application for end-users, an implementation of identityserver3 which serves as the OpenID authority, and an MVC app which will be access through an in-app browser in the cordova application.
The starting entry point for users is the cordova app. They login there via an in-app browser and can then access application features or click a link to open the in-app browser and visit the MVC app.
Our strategy for securing the MVC website was to use bearer token authentication, since we already logged in once from the app and didn't want to prompt the user to login again when they were directed to the MVC app:
app.Map("/account", account =>
{
account.UseIdentityServerBearerTokenAuthentication(new IdentityServer3.AccessTokenValidation.IdentityServerBearerTokenAuthenticationOptions()
{
Authority = "https://localhost:44333/core",
RequiredScopes = new string[] { "scope" },
DelayLoadMetadata = true,
TokenProvider = new QueryStringOAuthBearerProvider(),
ValidationMode = ValidationMode.ValidationEndpoint,
});
}
Since persisting the access_token on the query string is painful, I implemented a custom OAuthBearerAuthenticationProvider:
public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
private static ILog logger = LogManager.GetLogger(typeof(QueryStringOAuthBearerProvider));
public override Task RequestToken(OAuthRequestTokenContext context)
{
logger.Debug($"Searching for query-string bearer token for authorization on request {context.Request.Path}");
string value = GetAccessTokenFromQueryString(context.Request);
if (!string.IsNullOrEmpty(value))
{
context.Token = value;
//Save the token as a cookie so the URLs doesn't need to continue passing the access_token
SaveAccessTokenToCookie(context.Request, context.Response, value);
}
else
{
//Check for the cookie
value = GetAccessTokenFromCookie(context.Request);
if (!string.IsNullOrEmpty(value))
{
context.Token = value;
}
}
return Task.FromResult<object>(null);
}
[cookie access methods not very interesting]
}
This works, and allows the MVC application to not have to persist the access token into every request, but storing the access token as just a generic cookie seems wrong.
What I'd really like to do instead is use the access token to work with the OpenID endpoint and issue a forms-auth style cookie, which responds to logout. I found that I can add account.UseOpenIdConnectAuthentication(..) but if I authenticate via access_token, the OpenIdConnectAuthentication bits are simply skipped. Any ideas?
You don't -- access tokens are designed to be used to call web apis. You use the id_token from OIDC to authenticate the user and from the claims inside you issue your local authentication cookie. The Microsoft OpenIdConnect authentication middleware will do most of this heavy lifting for you.

need to pass a default emailid in azure active directory authentication

I am doing Azure Active Directory authentication and using openidconnect for authentication. My application has it own login page and I am trying to redirect the user as soon as they type user id in my login page.
But I am unable to pass userid from my login page to azure login page. I am using following code for
calling azure login page and it redirected correctly but I am not able to pass any default login id which should be displayed on the azure login page like "abc#microsoft.com".
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" });
You need to add a login_hint query string parameter in the redirect to the authorization server. Here is a post which describes this (in the context of Google login, which also uses OpenID Connect):
http://forums.asp.net/t/1999402.aspx?Owin+pass+custom+query+parameters+in+Authentication+Request
In your case, I suggest you try the following:
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties
{
RedirectUri = "/",
Dictionary =
{
{ "login_hint", "abc#microsoft.com" }
}
});

asp.net - Web API 2 Singe Page Application - Using built in Login form doesn't authorize?

I'm just working on my first Web API 2 Single Page Application in Visual Studio 2013. When I started with the project I chose Authentication: Individual Accounts. So when I build the solution, the login form appeared. I registered a user and I can successfully log in.
My controller is ready to use and I put the [authorize]-Attribute in front of my requests.
When I'm not logged in and navigate to my request, it shows me the error-message:
"Authorization has been denied for this request."
That's great, but when I'm logged in and navigate to the request again, it still shows me the same message.
The controller itself is working fine without the [authorize]-attribute.
I'm really new to this topic and I couldn't find anything about how to connect the built in Login with authorizing my requests. I hope, you can help me.
EDIT:
I just found out about the differences of Authentication and Authorization. First is for identifying the user, second is for giving him rights to do anything...
So I tried [Authorize(Users="Username")], but it doesn't work. (It should work with [Authorize] as well, because therefore you authorize all users??)
What's wrong with my application? :(
EDIT 2:
I'm still searching for how to get the access_token into the header! :(
When You are sending Request To your controller through ajax add your authorization claims token
For every request you need to send authorization token
In your login.viewmodel.js of SPA after user successfully logged in you are saving data.access_token,this token needs to send for every ajax request as below
If this answered your question, Please check right on left side.
$.ajax(url, {
type: "POST",
data: data,
headers: "Authorization": "Bearer " + accessToken
});
dataModel.login({
grant_type: "password",
username: self.userName(),
password: self.password()
}).done(function (data) {
self.loggingIn(false);
if (data.userName && data.access_token) {
app.navigateToLoggedIn(data.userName, data.access_token, self.rememberMe());
} else {
self.errors.push("An unknown error occurred.");
}
}).failJSON(function (data) {
self.loggingIn(false);
if (data && data.error_description) {
self.errors.push(data.error_description);
} else {
self.errors.push("An unknown error occurred.");
}
});

Categories