Asp.Net Core Scaffolded 'Register' and 'Login' redirect not working in Azure AppService - asp.net-mvc-routing

Asp.Net Core 3.0 app. I am using Entity Framework Identity individual authentication and have scaffolded in a Login page and a Register page. I have an SQL database in Azure.
When I run on localhost, the registration & login work fine. I have confirmed the new user is stored in the DB Users table.
But when I deploy to Azure AppService, I get a 404 page not found error when I click the register or login button.
I have tried:
Scaled up to a paid plan and implemented CNAME Using GoDaddy & Azure for my app service to remove the .azurewebsites.net from the url
Added asp-area and asp-page to the <button> elements in my cshtml.
Turned on Azure Authentication & Authorization in App Service and added http://www.myapp.com as a redirect url.
Whitelisted all my AppService Outbound IPs in my Azure DB server firewall settings.
I have tried using the dev console in Chrome to see whats happening but I couldnt see anything useful.
Pulled some of my hair out...
Any ideas where I should look?
Additional info:
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=tcp:**-*****.database.windows.net,1433;Initial Catalog=****;Persist Security Info=False;User ID=****;Password=****;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
DbContext:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace MyApp.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
}
Register cshtml:
<button type="submit" class="btn btn-primary" asp-area="Identity" asp-page="Register" id="RegisterButton">#_loc[Model.RegisterButtonName]</button>
Login cshtml:
<div class="form-group">
<button type="submit" class="btn btn-primary" asp-area="Identity" asp-page="Login" id="LoginButton">#_loc[Model.LoginButtonName]</button>
</div>
Error:
If I navigate to https://www.myapp.com/en/Identity/Account/Login from my homepage, the page loads fine. But when I click the Login/Register button, the redirect fails and shows the error below.
Middleware:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseRequestLocalization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default", pattern: "
{culture=en}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "Features", pattern: "
{culture=en}/{controller=Features}/{action=Features}/{id?}");
endpoints.MapControllerRoute(
name: "About", pattern: "
{culture=en}/{controller=About}/{action=About}/{id?}");
endpoints.MapControllerRoute(
name: "Help", pattern: "
{culture=en}/{controller=Help}/{action=Help}/{id?}");
endpoints.MapRazorPages();
});
Database:
There is no user record being created in the DB when register is clicked, just the error page
Update:
I searched my entire codebase for 'localhost' but did not find it anywhere other than the IIS settings.
Update:
I added the server and virtual inbound IP addresses from the nslookup to the DB server firewall whitelist.
Update:
On Firefox I do not get an error. Simply a blank white page.
On Edge I get the same 404 error that the page cannot be found.
Update:
In my startup.cs services I tried both true and false for RequireConfirmedAccount
services.AddDefaultIdentity<ApplicationUser>( options => { options.SignIn.RequireConfirmedAccount = true; }).AddEntityFrameworkStores<ApplicationDbContext>();
Update:
Confirmed that Build Action is set to Content for my cshtml properties.
Update:
Added TXT | asuid | app verification id to my DNS settings in GoDaddy.
Added TXT | # | mywebsite.azurewebsites.net to my DNS settings in GoDaddy.
Added mywebsite.com as an assigned custom domain & verified it in the azure portal.
Update:
I was told on the MSDN forums that this may be because the http POST for the submit button wont work and I should change it to a anchor <a> tag or Input type button.
Changing the html is fine, but I am trying to figure out what this will mean for my Razor page redirect code? If anyone can point me in the right direction it would be great. Existing redirect code for the register page shown below.
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
I'm guessing from a little research that my new cshtml will be something like below:
<input id="RegisterButton" runat="server" onserverclick="RegisterButtonClick" type="submit" class="btn btn-primary" asp-area="Identity" asp-page="Register" >#_loc[Model.RegisterButtonName]</input>
Update:
I commented out Use.Hsts for prod in the Configure method of my startup.cs
Update:
I tried hardcoding a returnUrl in the OnPostAsync method of my login.cshtml.cs instead of using returnUrl ??= Url.Content("~/");Same 404 error...so I'm not sure where the redirect is actually being triggered by the identity service that redirects to the same login page. Obviously not in my OnPostAsync, because it should have tried to reach the url I hardcoded instead, which was ~/myapp.com/en/Features/Features. Ugh. This is giving me serious headaches.
Update:
I tried replacing return LocalRedirect(returnUrl); with
return LocalRedirect(Url.Action("Login", "Identity/Account"));but it is not working on localhost so I have not tried it in prod. It is saying
No webpage was found for the web address: https://localhost:44305/en/Identity%2FAccount/Login
Update:
I replaced the null coalescing operators for returnUrl ??= Url.Content("~/"); with the = operator for returnUrl = Url.Content("~/");
Update:
Confirmed that my AddControllersWithViews and AddRazorPages do NOT implement authorization globally by default, and my Login and Register page models have [AllowAnonymous] specified.
Update:
I have made changes to my OnPostAsync method and my ConfigureServices<IdentityOptions>. I think the default IdentityOptions password requirements were masking the true issue.
I can still log in fine on localhost using the user I created prior to scaffolding, and I can not log in on App Service with that user. But now on AppService I am getting an, 'Invalid Login Attempt' error on the UI for that pre-scaffolding user. There is no error in the console.
So basically I still cant register or login on AppService, but somehow after 2 weeks an error message on the UI that I can try to diagnose feels like progress!
I will investigate this because it is happening with new users I register in localhost also, so it needs to be resolved first anyway. If it doesn't help, I will look into CORS as the next stop to find an AppService resolution. I also reached out to Microsoft, fingers crossed. Thanks folks.
UPDATE:
This is now resolved. I honestly have no idea how. I made so many changes over the past few weeks, to undo all my commits one by one to find out what fixed it would just be too painful. When the painful memory subsides in a few weeks I will come back and try to break it again to find out what it was. I'll post an update then.

Try to generate the Urls with #Url.Action("Login","Account")

As it was pointed out already in a comment, it could be a CORS issue.
I'd suggest, use fiddler and look at the requests your browser sends to the server.
I had a similar CORS issue just recently where the browser sent an OPTIONS request to the server before the actual POST. What worked for me except including CORS middleware and RequireCors on your endpoints was to add the HttpOptions attribute on the controller actions.
Good luck!

I have a similar problem.
When i run the project in VS is Ok. But when it is in IIS or web hosting, when on click register o login (request) show error 404. About Identity/Account/Login.
Error 404
My solution was remove "Trusted_Connection=True" from the connection string. I think it was an exception into login page and register page related with sql.
You can test your app in local IIS, add and page that make queries in sql
And after in web hosting. (SmarterASP.NET https://www.smarterasp.net)

Maybe late but i hope my answer will help someone save their time.
I face the same issue because i don't allow resources access my server on Azure, lol. I just allow Azure services and resources to access this server and everything are working fine.
Image
And after, I don't know why Azure return 404 not found page instead of show me an error message about like 'can't connect to SQl server ...'.

Related

POST to Salesforce API using Google Tag Manager and JSforce not working?

I want to use Google Tag Manager to send data to our Salesforce org for certain events on our website (user signup, conversion etc). After some research, I realized JSforce would be the easiest way to achieve this. I created a new connected app in Salesforce, tried out the Salesforce API using Postman and successfully managed to create a new user account via the API. Then I moved on to try and achieve the same thing in Google Tag Manager. I read JSforce's docs and attempted to implement everything. But, after multiple hours of troubleshooting and Google searching, I can't seem to make it work.
Here is my current code, which is in a 'tag' in Google Tag Manager that triggers on all pages (just for testing):
https://jsforce.github.io/start/#web-browser
<script src="//cdnjs.cloudflare.com/ajax/libs/jsforce/1.9.1/jsforce.min.js"></script>
<script>
jsforce.browser.init({
clientId: '<MYCLIENTID>',
redirectUri: 'https://cuttersclub.com'
});
https://jsforce.github.io/document/#access-token
var jsforce = require('jsforce');
var conn = new jsforce.Connection({
instanceUrl : 'https://um5.salesforce.com',
accessToken : '<MYACCESSTOKEN>',
});
https://jsforce.github.io/document/#create
conn.sobject("Account").create({ Name : 'My Account #1' }, function(err, ret) {
if (err || !ret.success) { return console.error(err, ret); }
console.log("Created record id : " + ret.id);
});
</script>
I'm getting this error in the browser console:
Uncaught ReferenceError: require is not defined
EDIT: Removing var jsforce = require('jsforce'); solved this problem and accounts are being created in Salesforce. But, now I am getting the following error in the browser console:
Access to XMLHttpRequest at '<URL>' from origin '<CALLBACKURL>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
As mentioned in the JSforce docs, I think it may be something to do with proxy servers: https://github.com/jsforce/jsforce-ajax-proxy
I don't know that much about salesforce, but "require" is something from node.js, not a function that is implemented in the browser.
If I understand the documentation correctly, then for a browser project it should be enough to call the jsforce script via a script tag. You should not need any way to "require" files after that, since the jsforce script already contains everything you need. So you should be fine if you just remove the offending lines (i.e. all references to "require('jsforce');").

Actions on Google implicit account linking works in simulator/browser, but not on device (via Google Home app)

I've implemented the implicit flow for Actions on Google account linking, and am using Dialogflow (previously API.AI) to define intents.
The full flow works in the device simulator (from AOG). The first intent gets a "It looks like your account isn't linked yet..." response, and the debug pane includes a URL to initiate linking:
https://assistant.google.com/services/auth/handoffs/auth/start?account_name=[account]#gmail.com&provider=[project_id]_dev&scopes=email&return_url=https://www.google.com/
If I follow this URI in a cache-less window:
I'm redirected to my app's authentication page
I choose to sign in with my Google account (same as [account] above)
I'm redirected to google.com with a success message in the URI bar
The simulator now accepts actions via my app and responds correctly
However, if I follow the same flow using a physical Google Home & the gH app for Android.
Device tells me account not yet linked
Open Google home and follow 'Link to [my app]' link
Browser opens to authentication page
Sign in as user
Redirected to a white page with a single link "Return to app", which has an href: about:invalid#zClosurez
Linking was unsuccessful, so additional attempts to run intents on the Google Home get the same "Account not yet linked" response.
I've inspected the intermediate access_token and state variables at length, and they all match and look to be correctly formatted:
Authentication URL (app sign in page): https://flowdash.co/auth/google?response_type=token&client_id=[client_id]&redirect_uri=https://oauth-redirect.googleusercontent.com/r/[project_id]&scope=email&state=[state]
After authenticating, redirected to (this is the white screen with 'return to app' broken link): https://oauth-redirect.googleusercontent.com/r/genzai-app#access_token=[token]&token_type=bearer&state=[state]
So, it seems there's something non-parallel about the way the simulator and physical devices work in terms of implicit flow account linking.
I've been struggling with this, and with the AOG support team for a very long time to no avail. Anyone else see a similar issue?
Updated with response redirect code:
Login handled by react-google-login component with profile & email scopes. On success we call:
finish_auth(id_token) {
let provider = {
uri: '/api/auth/google_auth',
params: ['client_id', 'redirect_uri', 'state', 'response_type'],
name: "Google Assistant"
}
if (provider) {
let data = {};
provider.params.forEach((p) => {
data[p] = this.props.location.query[p];
});
if (id_token) data.id_token = id_token;
api.post(provider.uri, data, (res) => {
if (res.redirect) window.location = res.redirect;
else if (res.error) toastr.error(res.error);
});
} else {
toastr.error("Provider not found");
}
}
provider.uri hits this API endpoint:
def google_auth(self):
client_id = self.request.get('client_id')
redirect_uri = self.request.get('redirect_uri')
state = self.request.get('state')
id_token = self.request.get('id_token')
redir_url = user = None
if client_id == DF_CLIENT_ID:
# Part of Google Home / API.AI auth flow
if redirect_uri == "https://oauth-redirect.googleusercontent.com/r/%s" % secrets.GOOGLE_PROJECT_ID:
if not user:
ok, _email, name = self.validate_google_id_token(id_token)
if ok:
user = User.GetByEmail(_email, create_if_missing=True, name=name)
if user:
access_token = user.aes_access_token(client_id=DF_CLIENT_ID)
redir_url = 'https://oauth-redirect.googleusercontent.com/r/%s#' % secrets.GOOGLE_PROJECT_ID
redir_url += urllib.urlencode({
'access_token': access_token,
'token_type': 'bearer',
'state': state
})
self.success = True
else:
self.message = "Malformed"
else:
self.message = "Malformed"
self.set_response({'redirect': redir_url}, debug=True)
I am able to make it work after a long time. We have to enable the webhook first and we can see how to enable the webhook in the dialog flow fulfillment docs If we are going to use Google Assistant, then we have to enable the Google Assistant Integration in the integrations first. Then follow the steps mentioned below for the Account Linking in actions on google:-
Go to google cloud console -> APIsand Services -> Credentials -> OAuth 2.0 client IDs -> Web client -> Note the client ID, client secret from there -> Download JSON - from json note down the project id, auth_uri, token_uri -> Authorised Redirect URIs -> White list our app's URL -> in this URL fixed part is https://oauth-redirect.googleusercontent.com/r/ and append the project id in the URL -> Save the changes
Actions on Google -> Account linking setup 1. Grant type = Authorisation code 2. Client info 1. Fill up client id,client secrtet, auth_uri, token_uri 2. Enter the auth uri as https://www.googleapis.com/auth and token_uri as https://www.googleapis.com/token 3. Save and run 4. It will show an error while running on the google assistant, but dont worry 5. Come back to the account linking section in the assistant settings and enter auth_uri as https://accounts.google.com/o/oauth2/auth and token_uri as https://accounts.google.com/o/oauth2/token 6. Put the scopes as https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email and weare good to go. 7. Save the changes.
In the hosting server(heroku)logs, we can see the access token value and through access token, we can get the details regarding the email address.
Append the access token to this link "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" and we can get the required details in the resulting json page.
`accessToken = req.get("originalRequest").get("data").get("user").get("accessToken")
r = requests.get(link)
print("Email Id= " + r.json()["email"])
print("Name= " + r.json()["name"])`
Not sure which python middleware or modules you are using but
self.set_response({'redirect': redir_url}, debug=True)
seems to be setting parameters for a returning a response which isn't correct. Instead you should redirect your response to the redirect_url. For example importing the redirect module in Flask or Django like:
from flask import redirect or from django.shortcuts import redirect
then redirect like:
return redirect(redirect_url)
It appears Google has made a change that has partially solved this problem in that it is now possible to complete the implicit account linking flow outside of the simulator, in the way outlined in my question.
It seems the problem stemmed from an odd handling (on the AOG side) of the client-side redirect case used after sign in with the Google sign-in button.
From Jeff Craig in this thread:
The current workaround, where we provide the "Return to app" link
currently what we're able to provide. The issue is with the way that
redirecting to custom-scheme URIs is handled in Chrome, specifically,
with regard to the redirect happening in the context of a user action.
XHR will break that context, so what is happening is that you click
the Google Sign-In Button, which triggers an XHR to Google's servers,
and then you (most likely) do a client-side redirect back to the
redirect_url we supply, our handler executes, and isn't able to do a
JS redirect to the custom scheme URI of the app, because were outside
of the context of a direct user click.
This is more of a problem with the Implicit (response_type=token) flow
than with the authorization code (response_type=code) flow, and the
"Return to app" link is the best fallback case we currently have,
though we are always looking for better solutions here as well.
The current behavior shows the 'Return to app' link, but as of last week, this link's href is no longer about:invalid#zClosurez, but instead successfully completes the sign-in and linking process. It's an odd and confusing UX that I hope Google will improve in the future, but it was sufficient to get my app approved by the AOG team without any changes to my flow.

Google Sign-In with Passportjs not getting authenticated

I'm using Sails with Passport for authentication. I'm using passport-google-oauth(OAuth2Strategy) and passport-facebook for enabling Google Sign-in.
I'm not too well-versed with Passport, so pardon me if this is a rookie question. I've set up login via Facebook and it works just fine. With Google, I do receive an authorization code after allowing access to the app, but the I'm eventually not authenticated. I'm guessing the same code should work for both Facebook and Google since the strategies are both based on oauth2.
I'm not even sure what code to share, since I'm using the auto-generated code from sails-generate-auth, but do let me know if there's anything else I can share.
Any ideas on why this might be happening? The app is locally hosted but that's unlikely to be the problem since I am getting to the authorization stage anyway.
I faced the same problem and it was located here in in api/services/passport.js:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
The Google service was not returning a profile.username property.
Because of it, the user is not saved in the database and cannot be authenticated. Then the passport callback receives an empty user, so the function that handles errors is fired and the user is redirected to the login page.
This change allows to use the displayName property as the username:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
/** Content not generated BEGIN */
// If the username property was empty and the profile object
// contains a property "displayName", add it to the user.
if (!user.username && profile.hasOwnProperty('displayName')) {
console.log(profile); // <= Use it to check the content given by Google about the user
user.username = profile.displayName;
}
/** Content not generated END */
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
You could also use the profile.id property because profile.displayName is not necessarily unique (ie: two Google accounts can have an identical displayName). But it is also true accross different services: a Twitter account could also have the same username than a Facebook account. If both register on your application, you will have a bug. This is a problem from the code generated by sails-generate-auth and you should adapt it with the behavior that you want.
I will propose a PR if this solution works for you too.
Alright, so this ultimately turned out to be a known issue with the API.
TL;DR: Enable the Google+ API and the Contacts API as mentioned here. (The Contacts API isn't required, as #AlexisN-o pointed out in the comments. My setup worked as desired with Contacts API disabled. This obviously depends on what scope you're using.)
I believe it's not a nice way of failing since this was an API error that was prevented from bubbling up. Anyway, I dug into passport.authenticate to figure out what was going wrong. This eventually calls the authenticate method defined in the package corresponding to the strategy (oauth2 in this case). In here (passport-google-oauth/lib/passport-google-oauth/oauth2.js) I found that the accessToken was indeed being fetched from Google, so things should be working. This indicated that there was a problem with the requests being made to the token urls. So I ventured a little further into passport-oauth2/lib/strategy.js and finally managed to log this error:
{ [InternalOAuthError: failed to fetch user profile]
name: 'InternalOAuthError',
message: 'failed to fetch user profile',
oauthError:
{ statusCode: 403,
data: '{
"error": {
"errors": [{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. The API (Google+ API) is not enabled for your project. Please use the Google Developers Console to update your configuration.",
"extendedHelp": "https://console.developers.google.com"
}],
"code": 403,
"message": "Access Not Configured. The API (Google+ API) is not enabled for your project. Please use the Google Developers Console to update your configuration."
}
}'
} }
This was the end of the hunt for me and the first result for the error search led to the correct answer. Weird fix though.

Thinktecture IdentityServer3 Facebook Login Button Issue

I am using "IdentityServer3 - IdentityManager - MembershipReboot" in my project for User Management, Authentication & Resources Authorization.
I started from below sample and have gone good for creating users, authenticating them via /connect/token api and authorizing resources.
https://github.com/thinktecture/Thinktecture.IdentityServer.v3.Samples/tree/master/source/MembershipReboot
A brief architecture for my solution is
MySql as database. Communication via MembershipReboot.EF to MembershipReboot.
The client project is developed using html + angularjs.
Resources APIs are developed using Nancy & hosted on Owin+Katana in a seperate project.
Authentication Services(IdSvr+IdMgr+MR) are hosted in a seperate project.
Now I want to create a simple button/link clicking on which leads me to facebook login. The functionality of this button should be same as defined in IDSvr default login page's(https://localhost:44333/core/login?signin=4f909a877cc465afd26d72f60ec08f51) "Facebook button".
I have tried googled internet a lot but none of cases are matching my scenario.
I even tried to replicate the request-response behaviour of default IdSvr facebook login but that does not work as cookies are not being saved on end client.
Also i tried to hit "https://localhost:44333/core/signin-facebook" and getting response as HTTP/1.1 500 Internal Server Error from server. So i think might be I am somewhere wrong in setting facebook options in IdSrv project.
So if someone can just provide me a single IdSvr API to connect or tell me how to config Id Svr so that mapping a url can redirect it to facebook login. Or can tell me that where I am wrong in setting facebook authentication options in IdSrv.
A short and simple answer for my question is that I was looking for url.
https://localhost:44333/connect/authorize?client_id=implicitclient&response_type=token&scope=read&redirect_uri=http://localhost:8088/login/auth&nonce=random_nonce&acr_values=idp%3AFacebook&response_mode=form_post
Read further if you want to get better idea about this url
After lots of Hit&Trial & Study efforts, I have got solution for this. Well I think root cause for this problem was that sudden new technical things(Owin, Katana, OAuth, IdentityServer, IdentityManagement, MembershipReboot, Owin Facebook) and a meager time to understand them all.
I would advice folks that whoever is in same situation as me then first get an idea about OAuth. I found below link as a short and good one.
http://tutorials.jenkov.com/oauth2/index.html
After this I learnt that in our scenario we are dealing with two applications and hence two authentication.
For connecting User to Facebook. We created an app on developers.facebook.com
For connecting User to IdentityServer. We created a client in Clients.cs file on AuthenticationServices project.
So now here is the final solution.
localhost:44333 where AuthenticationService is running
locahost:8088 where FrontEnd services are running which iscalling AuthenticationService .
1. Create client app in AuthenticationServices as below
new Client
{
ClientName = "Implicit Clients",
Enabled = true,
ClientId = "implicitclient",
ClientSecrets = new List<ClientSecret>{
new ClientSecret("secret".Sha256())
},
Flow = Flows.Implicit,
RequireConsent = true,
AllowRememberConsent = true,
RedirectUris = new List<string>
{
"http://localhost:8088/login/auth" //This should be redirect url you want to hit after your app(not facebook app) redirects.
},
ScopeRestrictions = new List<string>
{
Constants.StandardScopes.OpenId,
Constants.StandardScopes.Profile,
Constants.StandardScopes.Email,
"read",
"write",
},
//SubjectType = SubjectTypes.Global,
AccessTokenType = AccessTokenType.Jwt,
IdentityTokenLifetime = 360,
AccessTokenLifetime = 360,
},
2 Create Authorize URL as below
var client = new OAuth2Client(new Uri("https://localhost:44333/core/connect/authorize"));
var startUrl = client.CreateAuthorizeUrl(
clientId: "implicitclient",
responseType: "token",
scope: "read",
redirectUri: "http://localhost:8088/login/auth",
nonce: "random_nonce",
responseMode: "form_post",
acrValues: "idp:Facebook");
The facebook app after successful authorization will redirect default to http://localhost:44333/signin-facebook. So no need to do any changes there.
Finally on http://localhost:8088/login/auth you will get access_token(+ few other parameters) after successful authentication. Here onwards you can use this token to access resources from Resources server.

AS3 FacebookDesktop Login fail with OAuthException - #2500 An active access token must be used to query information about the current user

I think this is because Facebook just made some changes to their login process.
A few days ago, my air app was working with the FacebookDesktop class from the facebook-actionscript-api. Today I opened the project, and noticed that the Facebook login screens are a little different than when I started building my app. After I type my userID and password in, I grant the app access to my public profile, friend list and photos. Then another screen comes up where I grant the app permission to post to my friends on my behalf.
Then the window closes, and I get 'OAuthException 2500 An active access token must be used to query information about the current user.'
When I sign into Facebook through a browser, I see that my app shows up under "Your Apps" but I can't log in and do anything through my app.
I'm using Adobe Flash with GraphAPI_Desktop_1_8_1.swc on OSX Lion.
Here is my code:
public function MyApp(){
FacebookDesktop.init(APP_ID, onInit);
}
protected function onInit(result:Object, fail:Object):void {
if (result) {
trace("onInit, Logged In\n");
} else {
trace("onInit, Not Logged In\n");
var permissions:Array = ["publish_stream", "user_photos"];
FacebookDesktop.login(onLogin, permissions);
}
}
protected function onLogin(result:Object, fail:Object):void {
if (result) {
trace("Logged In as:");
trace(FacebookDesktop.getSession().user.name);
} else {
trace("Login Failed");
trace('code: '+fail.error.code); //code: 2500
trace('message: '+fail.error.message); //message: An active access token must be used to query information about the current user.
trace('type: '+fail.error.type); //type: OAuthException
}
}
I get the same results when I use the FlashDesktopExample provided in the SDK (modified with my app ID of course).
Any help would be great! Thanks in advance!
I ran into this problem, too: the success URL did not have any parameters.
Cadderly82 is correct; it's a problem with secure navigation. Turning off my Facebook account's "Secure Browsing" option fixed the problem, but I didn't want to have to require users to do that.
I was able to solve this by setting ALL of the FacebookURLDefaults values to use "https://".
Now I get a valid user-access-token in the success URL; and I get valid values regardless of my facebook account's secure-browsing setting.
I have figured out the problem:
The LoginWindow class sets the token based on the uri.
This worked fine until the LOGIN_SUCCESS_URL (http://www.facebook.com/connect/login_success.html) and the LOGIN_SUCCESS_SECUREURL (https://www.facebook.com/connect/login_success.html) pages stopped including the access token in the uri.
Hence, the token is never set. Even though my app shows up under the 'Your Apps' section in Facebook after I login, my app still can't do anything without a token.
I have two solutions:
The easiest is to change the LOGIN_SUCCESS_URL and/or the LOGIN_SUCCESS_SECUREURL properties in com.facebook.graph.core.FacebookURLDefaults like the following.
beginning on line 82:
public static var LOGIN_SUCCESS_URL:String = 'http://www.facebook.com/connect/login_success.html';
public static var LOGIN_SUCCESS_SECUREURL:String = 'https://www.facebook.com/connect/login_success.html';
Change to:
public static var LOGIN_SUCCESS_URL:String = 'http://www.yourwebsite.com/';
public static var LOGIN_SUCCESS_SECUREURL:String = 'https://www.yoursecurewebsite.com/';
of course you would use your own website - not 'http://www.yourwebsite.com/'. I tried it using http://localhost/ and it worked great.
Another solution is:
Change com.facebook.graph.windows.LoginWindow with the following code. I have made some changes to my files, so please forgive me if the line numbers are different than what they are in a fresh copy of the SDK.
around line 143:
change:
vars.redirect_uri = FacebookURLDefaults.LOGIN_SUCCESS_URL;
to:
vars.redirect_uri = 'http://localhost/';
In production code, you probably want to use your own website address instead of localhost, but I used localhost for testing purposes.
Then, in the handleLocationChange function (should be around line 168) add this to the else if statements:
}else if (html.location.indexOf ('http://localhost/') == 0) {
loginCallback(getURLVariables(), null);
userClosedWindow = false;
html.stage.nativeWindow.close();
html.removeEventListener(Event.LOCATION_CHANGE, handleLocationChange);
}
As I said before, change localhost to your website address.
I hope this helps!
I was having the same problem for random users and I don't really know if it is a Facebook problem with secure navigation:
Check user properties in Facebook: Security Settings > Secure Browsing
(www.facebook.com/settings?tab=security)
For users with "disabled" state it works fine.
For users with "migration" state it gives the error.
For users with previously "enabled" state it works fine.
When I tried with users in "migration" state and changed to "disabled", it worked fine.
Then if I turned it "enabled", the "migration" state is gone and marked as "enabled", but the error it's still there.
So I guess this is the problem, but don't know how to fix it.
alot has change in a year this is what i think the answer is now
you need a token to login FacebookDesktop.getSession().accessToken
public function MyApp(){FacebookDesktop.init(APP_ID, onInit, FacebookDesktop.getSession().accessToken); }