owin active directory token validation random slowness and error - asp.net

I am facing some random authorisation problem when using following code to authenticate against ad active directory (I have a web api).
I believe this code will send a validation request to our azure active directory, but randomly we got validation error and some times it can take a while to get validation result back.
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = Constants.AzureActiveDirectoryTenant,
TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
// These values will be checked against what is received in the access token.
ValidAudiences = Constants.AzureActiveDirectoryValidAudiences
}
});
Is it possible to understand why validation failed? Also about the speed, is it possible to create some custom method to cache a token on my web site? So I don't need to validate every request to AD all the time.

You can try the Microsoft.Owin.Diagnostics nuget package to check the logs.
Alternatively, for a remote debug:
In Cloud Explorer in visual studio, find you web app and select "Remote Debugging."
Then publish your site in Debug mode.
In the portal, enable it by going to Application settings > Debugging > Remote Debugging > On

Related

Firebase Authentication unable to enable Google auth method - "Error updating Google"

I am trying to enable the Firebase authentication with the Google Auth sign-in method, but enabling it and clicking "save" shows the error "Error updating Google".
In the Google Cloud Console activity logs, it shows:
Failed:google.internal.firebase.v1.FirebaseInternalProductService.EnableGoogleSignIn
With the error message "Not found (HTTP 404): Operation failed with error code NOT_FOUND."
However, when I tried this in a new Google Cloud project, it worked perfectly. I have tried removing and recreating the Firebase Admin SDK, removing and creating a new app, and removing the OAuth credentials.
I cannot seem to find any solution to this problem other than creating a new project, but I would prefer to keep my existing project ID.
Alternatively, if there is any way to reset my GCP project or remake it with the same ID, that would also be fine.
This issue is caused by deleting the OAuth client autogenerated by Firebase by default.
To solve it, you need to first create a new OAuth 2 client ID, and set the necessary redirect URIs for your Firebase app (they should default to something like https://{PROJECT_ID}.web.app/__/auth/handler).
Then, call this API - the request should look something like this, using the client ID and client secret from the credentials generated above:
PATCH https://identitytoolkit.googleapis.com/admin/v2/projects/{PROJECT_ID}/defaultSupportedIdpConfigs/google.com
{
"name": "projects/{PROJECT_ID}/defaultSupportedIdpConfigs/google.com",
"enabled": true,
"clientId": "{YOUR_CLIENT_ID}",
"clientSecret": "{YOUR_CLIENT_SECRET}"
}
After making this API call, the Google authentication provider should be enabled.
Before to begin, you must have created a new oaut-credentian gcp console, because is tha main problem here.
You nee create a new oauth provider, you can use the next link to authenticate a try the request using data like next:
Parent: projects/**put here your project number**
idpId (identity provider): google.com
Request Body
{
"name": "projects/**put here your project number**/defaultSupportedIdpConfigs/google.com",
"enabled": true,
"clientId": "**put here your client id**",
"clientSecret": "**put here your client secret**"
}

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.

How can I authenticate via Firebase Google Auth on localhost

I'm building a site with emberfire and using firebase. Everything seems to be set up fine regarding credentials, and I can read/write to the firebase database while developing locally, but every time I try to authenticate via the Google Popup it pops up fine with my Google accounts listed, and when I select my account it errors with this error object:
code: "auth/network-request-failed", message: "A network error (such as timeout, interrupted connection or unreachable host) has occurred."
I assume I'm simply missing a setting somewhere but for the life of me I cannot find it. Here's the code to get the popup and response:
const provider = new firebase.auth.GoogleAuthProvider();
this.firebaseApp.auth().then(auth => {
/* Firebase SDK calls */
auth.signInWithPopup(provider).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
});
});
I am using EmberJS with emberfire.
In my environment I had host: 'api', and when removing that authentication works, so it must be one of the adapters that is used.

The remote server returned an error: (401) Unauthorized. Using CSOM in ASP.NET

I'm tried to pull some SharePoint 2013 list data I created which works fine when running locally on my machine and when run locally one the server. I'm user the same credentials when running both locally and locally on the server. The issue is when I publish and navigate to my ASP.NET app on the server I get the "The remote server returned an error: (401) Unauthorized." Error...
I've looked at a bunch of the posts on stackoverflow and some other articles on the web
This points out that the context seems to be using IUSR:
http://blogs.msdn.com/b/sridhara/archive/2014/02/06/sharepoint-2013-csom-call-from-web-part-fails-with-401-for-all-users.aspx
This one mentions to try setting the default network credentials:
https://sharepoint.stackexchange.com/questions/10364/http-401-unauthorized-using-the-managed-client-object-model
I've tried using the fixes mentioned in the article as well as trying to force the context to use DefaultNetworkCredentials but no luck. I would like for the app to use the credentials of the logged in user and not the machine...
Here is the code I'm using:
SP.ClientContext context = new SP.ClientContext("MySPDevInstance");
context.Credentials = CredentialCache.DefaultNetworkCredentials;
Entity entity = context.Web.GetEntity(collectionNamespace, collectionName);
LobSystem lobSystem = entity.GetLobSystem();
LobSystemInstanceCollection lobSystemInstanceCollection = lobSystem.GetLobSystemInstances();
context.Load(lobSystemInstanceCollection);
context.ExecuteQuery();
LobSystemInstance lobSystemInstance = lobSystemInstanceCollection[0];
FilterCollection filterCollection = entity.GetFilters(filter);
filterCollection.SetFilterValue("LimitFilter", 0, 1000);
EntityInstanceCollection items = entity.FindFiltered(filterCollection, filter, lobSystemInstance);
The server is running IIS 6.0
Any advice would be much appreciated!
Thank you
I presume your ASP.NET web site is using Windows Integrated (NTLM) authentication. A user authenticated this way cannot authenticate to a second location from the server side (the web server.) You are experiencing what is known as the "double-hop" (1) limitation of NTLM. You must use a dedicated account on the server side, or if you really do want to use the logged-in user's identity, you must use an authentication scheme that permits delegation, such as Kerberos.
If you really need the user's identity to access SharePoint data and you cannot change the authentication scheme, then the best way to do this is to use the JavaScript CSOM. This means the user is authenticating directly to the SharePoint server (a single hop, not double) and your ASP.NET site serves the page containing this script to the user.
(1) http://blogs.msdn.com/b/knowledgecast/archive/2007/01/31/the-double-hop-problem.aspx
Use Default Credentials worked for me:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.UseDefaultCredentials = true;
Setup the crendentials by code:
SP.ClientContext context = new SP.ClientContext("MySPDevInstance");
context.Credentials = new NetworkCredential("username", "password");
You should put this at the configuration file to change it without publishing or recompiling the application.
Just to add one more setting that I encountered. If the account is restricted to access only certain servers than add the client machine to that account as well. For example if a web application is hosted on Server A and trying to connect to SharePoint 2010 on Server B with account ABC then make sure that account has access to Server A in Active Directory. Normally the AD account doesn't have restrictions to connect to machines but in my case the account was restricted to only certain machines. I added my web application hosted server to the account and it worked.

Directory.CreateDirectory failed on Remote Server

I am working on a small project, in asp.net mvc3, that would copy the deployment files from a local drive to a share drive on a window server 2008 R2 server. I am connected using WMI, and the connection is successful. However, I tried to create a folder, and I receive the message "Logon failure: unknown user name or bad password." Here is a sample code:
bool isConnected = false;
options.Username = user.Name.Trim();
options.Password = user.password.Trim();
mScope = new ManagementScope("\\\\xxx.xxx.xxx.xxx\\root\\cimv2", options);
mScope.Connect();
if (mScope.IsConnected == true)
{
//I've gotten to this point. Then, the code below throw the exception
Directory.CreateDirectory(#"\\\\xxx.xxx.xxx.xxx\Tester\shareFile.txt");
isConnected = true;
}
I'd like to know what am I doing? Is that the right way of doing it?
it is the correct way however it will be the current user you are trying to access that gets passed to the remote computer to create the directory. The management scope at this point has nothing to do with Directory.CreateDirectory. These are 2 different "worlds". you do give the creds to ManagementScope but this has no affect on Directory.CreateDirectory. you could use impersonation to do what you are wanting to:
How do you do Impersonation in .NET?
it is unclear though if you are doing this in ASP.NET/MVC or a different platform. your tags indicate ASP.NET MVC but not your main question.
remember, if you are using ASP.NET/MVC, the credentials of the app pool are being used to perform such actions.

Resources