Update asp.net mvc project from Oauth to Oauth2 - asp.net

I have a relatively old Asp.net mvc web project (created around 2012) which used Facebook connect using the AuthConfig.cs file and registered a client as so.
OAuthWebSecurity.RegisterFacebookClient(
appId: WebConfigurationManager.AppSettings["facebookOAuthAppID"],
appSecret: WebConfigurationManager.AppSettings["facebookOAuthAppSecret"]
);
Up until a few days ago when Facebook changed to v2 of their API, all was good but now all is dead when I try to connect. This is where it fails in the account controller.
DotNetOpenAuth.AspNet.AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
Result always returns false, so never continues.
I have found a few examples which inherit IAuthenticationClient and allow you to setup additional scopes etc, and these expose the endpoints that facbook uses. I tried to update these urls to use the new API (v2.3) but still the same error.
Has anyone encountered this and what steps did you do to resolve this?

Related

Missing initial state in WebAuthenticator login attempt

working on a .NET MAUI app and am trying to implement Firebase Authentication with the help of WebAuthenticator in MAUI. I get to the login form in a browser, but after logging in get the error
Unable to process request due to missing initial state. This may happen if browser sessionStorage is inaccessible or accidentally cleared.
This is the code that calls the authenticator
await client.SignInWithRedirectAsync(FirebaseProviderType.Google, async uri =>
{
var options = new WebAuthenticatorOptions
{
Url = new Uri(uri),
CallbackUrl = new Uri("com.companyname.myappname://callback/"),
PrefersEphemeralWebBrowserSession= true
};
var res = await WebAuthenticator.Default.AuthenticateAsync(options);
});
I think the problem could be the callback URL, but I'm not sure how to write it differently since I'm not using a backend API. Does anyone have any suggestions?
Thanks!
P.S. This happens with bost Firebase Google auth and Facebook login
You can try to clear the chrome browser data and reload the page to see if it works. This is a known problem of firebase. You can continue to follow up this github iissue: Unableto process request due to missing initial state.

How to troubleshoot oAuth authentication in asp.net core Blazor App

I am trying to set up Strava authentication (which is plain oAuth2) in Asp.Net Core Blazor App.
I am rather new to Blazor & Web dev (more of a backend background), and I don't seem to find out how to troubleshoot the reason why the Authentication does not work.
When I click the oAuth login button on the Login page in the (default) Blazor Server App, I get redirected to the correct oAuth login screen (of Strava in my case), but after I successfully enter the credentials for that App, the login page shows an error Error loading external login information.
While I would obviously appreciate any help or tips that could point out what is wrong in my code, I'm mostly searching for a way to get better error information and troubleshooting capabilities here. Setting a breakpoint in the EventHandler delegates does not show much.
This is the Startup.cs extract where I have configured the authentication setup :
services.AddAuthentication().AddOAuth("Strava",
oAuthOptions =>
{
oAuthOptions.ClientId = "myappid";
oAuthOptions.ClientSecret = "myclientsecret";
oAuthOptions.Scope.Clear();
oAuthOptions.Scope.Add("read");
oAuthOptions.CallbackPath = "/profile";
oAuthOptions.AuthorizationEndpoint = "https://www.strava.com/oauth/authorize";
oAuthOptions.TokenEndpoint = "https://www.strava.com/api/v3/oauth/token";
oAuthOptions.SignInScheme = IdentityConstants.ExternalScheme;
oAuthOptions.Events = new OAuthEvents()
{
OnRemoteFailure = loginFailureHandler =>
{
Console.WriteLine("Remote Error");
Console.WriteLine(loginFailureHandler.Failure.Message);
return Task.FromResult(0);
},
OnAccessDenied = handler =>
{
Console.WriteLine(handler.Response.StatusCode);
return Task.FromResult(0);
}
};
});
An update that made things work for me, so maybe it can help other people.
I performed the following actions, in order to gain more control on the entire authentication process.
I scaffolded two pages, in which I then could debug & step through (and obviously also update and change things). More information was found in this post:
Account.Login, which enables the customization of the actual login page dotnet aspnet-codegenerator identity -dc CotacolApp.Data.ApplicationDbContext --files "Account.Login"
Account.ExternalLogin, which enables the customization of the actual strava page dotnet aspnet-codegenerator identity -dc CotacolApp.Data.ApplicationDbContext --files "Account.ExternalLogin"
I then found out that the var info = await _signInManager.GetExternalLoginInfoAsync(); always resulted in a null value. And that was because I had to set the IdentityScheme to external. ```
And after that, I had to run some custom logic to do the claim mapping. Most of those details were written down in this stackoverflow post by #Morgeh.
Hope this can help people in the future.

Securing ASP.NET Core Web API with Azure AD

I am trying to start a new project that uses Azure AD for authentication. It is set up so that I have a SPA on the front end that gets information from an ASP.NET core web API, both of which I am creating. I am having trouble getting the front end token to authorize in the API. Every time I send a request to the API I get the error: Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException: IDX10231: Audience validation failed.
I have set up the project as following.
In Azure AD I have set up two applications: One for the front end and one for the API. The API application has an API exposed called access_as_user. The front end application then has access to this. I have also made a client secret for both and added redirect URL's for the front end.
In my ASP.NET core API I am using I'm using Microsoft.Identity.Web and calling it like so:
// startup.cs
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddProtectedWebApi(Configuration, subscribeToJwtBearerMiddlewareDiagnosticsEvents: true);
...
}
...
In my config the values are as follows:
"AzureAD": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "mydomain.onmicrosoft.com",
"TenantId": "*MY TENANT ID*",
"ClientId": "*Client ID of API",
"ClientSecret": "Client Secret for API",
"Audience": "Client ID of Front End"
}
To get auth I followed this tutorial -> here <- to set up PostMan to use OAuth 2.0 and get the tokens for me automatically. The magic happens at the end of step 3 in the tutorial.
Any help would be greatly appreciated.
Edit: After following the tutorial like alphaz18 suggested, I found my issue. I had forgotten to add the Authentication middle ware in the Configure part of Startup.cs.
app.UseRouting();
app.UseAuthentication(); // This line was missing.
app.UseAuthorization();
I would highly recommend you follow the Microsoft sample tutorials first as they are all working. they give you all steps to get these samples working and is a great place to start:
https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi
in that tutorial you posted, I don't see anything about audience either. So where did you get that from?

HTTP 500 error with Simple.OData.Client when authenticating

I keep getting a 500 error when trying to create the ODataClient and passing in ODataSettings with new NetworkCredentials(username, password). Anyone have any examples of creating this service with Basic Authentication?
I enabled basic authentication for a sample OData Web site, and then I was able to access it using Simple.OData.Client and the following code:
var settings = new ODataClientSettings();
settings.UrlBase = "http://localhost/ProductService/odata";
settings.Credentials = new NetworkCredential("Tester", "tester123");
var client = new ODataClient(settings);
If it doesn't work for you I suggest you check if it works when you disable basic authentication and open the site for anonymous access. If it still doesn't work, then the problem is with something else. Otherwise let me know what platform and Simple.OData.Client version you are using (I tested on .NET 4.0, .NET 4.5 and Simple.OData.Client v.2.0.0).

Can't get SPAppWebUrl - SharePoint 2013

I'm developing an auto-hosted asp.net app for Sharepoint 2013. I have to use the SPAppWebUrl token value for my requests. So I tried this :
AppManifest.xml : <StartPage>~remoteAppUrl/Pages/Index.aspx?{StandardTokens}</StartPage>
javascript :
var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
C# code-behind : Application["SPAppWebUrl"] = Request.QueryString["SPAppWebUrl"];
Nothing worked. Sharepoint sends values for SPHostUrl, SPLanguage, SPClientTag and SPProductNumber only. I read topics about tokens and noted this :
If there is no app web, the portion &SPAppWebUrl={AppWebUrl} is not present.
But I dont understand how I could not have an app web...
If anybody can help please. Thanks.
I had a similar problem when I was using Provider Hosted. The App Web for me wasn't coming over because I tried to use a certificate that would not work (wild card). Went through the certificate setup a second time using a self-signed certificate - then setup a dummy list and when I looked at:
string spAppUrl = Request["SPAppWebUrl"];
I'm getting back the proper value. I then use the URL to get your App web via:
System.Security.Principal.WindowsIdentity currentUser = Request.LogonUserIdentity;
using (var appContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(appUri, currentUser))
{
if (appContext != null)
{
Web appWeb = appContext.Web;
appContext.Load(appWeb, w => w.Title);
appContext.ExecuteQuery();
string title = appWeb.Title;
ViewBag.SiteTitle = title;
}
}
Had exactly the same issue. The following blog post tells you how to resolve it:
SP Rest Services with Provider hosted app
Basically, since a provider-hosted app doesn't have and app web, you have to tell sharepoint to create it. You do this by adding a dummy object (site column, list, etc) to your SharePoint project. It will then create the app web and add SPAppWebUrl to the standard tokens (in the app manifest).

Resources