Login failed for User when using Database connection in Owin Startup class - sharepoint

I am using Hangfire in my sharepoint provider hosted app. I have Owin Startup class.
public class Startup
{
public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection");
RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring!"), Cron.Minutely);
app.UseHangfireDashboard();
app.UseHangfireServer();
}
}
I have initialised defaultConnection in my web.config file. Everytime i run, i get error saying Login failed for Domain\MachineName, I tried passing user id and password in connection string, but still is fails saying login failed for that user.
Can anyone help me to find the issue?

I resolved this issue by creating a sql authentication login credential in my SQL server. I passed the created user id and password in my connection string.
<add name="DefaultConnection" connectionString="Data Source=DEESS01CW0184CO\SPQ11CONTENT;Initial Catalog=HangfireTest;User ID='testuser';password='testuser123'" providerName="System.Data.SqlClient" />
The issue still persisted for windows authentication.

Related

Custom openid connect provider adb2c

I have created a custom identity provider in adb2c for my openid connect server but getting error while running it through User Flow -
Setps I did :
Created a new openId Connectprovider.
Created a new user flow for open-id connect provider :
I am not sure how to debug this through adb2c as that's a quite generic error and if I am missing any steps.
This issue may cause if your client ID is incorrect in the web.config file for the app
Try to Open Web.config file for the app
In Web.config file,try to find the app key ida:ClientId.
The client ID provided in the portal for your app should be used as the value of the app key.
The file's modified section looks like
<appSettings>
<add key="ida:ClientId" value="**xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx**">
</appSettings>
Credits to MsDoc

Requests to third party API from .NET Core app timeout in IIS

I have a .NET Core Web API app running in IIS that can receive and respond to requests, but it needs to make requests to a third party API (Twilio). Those requests succeed when hosted locally but they time out when hosted in IIS.
The .NET Core Web API app is targeting v2.1 and running on Windows Server and IIS 7. I setup a dedicated app pool for the site following guidelines in this article.
App pool settings:
I'm using Postman to make GET and POST requests to the app.
GET and POST requests to a test controller work fine. All I'm doing with these test endpoints is returning the parameters that are received.
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
public string Get(int id)
{
return $"response to GET; id:{id}";
}
[HttpPost]
public string Post([FromBody] int id)
{
return $"response to POST; foo:{id}";
}
}
The above endpoints work locally running debug mode in VS2019 using IISExpress, and they also work when deployed to the web server and hosted with IIS7.
The trouble starts when I try to call out to a third party API (Twilio). Again these calls succeed when the app runs locally. There's almost no delay. I post to the SMSController's post endpoint, the request is triggered, and I get a text message within seconds. However, GET and POST requests to these endpoints fails from the web server and IIS.
[Route("api/[controller]")]
[ApiController]
public class SMSController : ControllerBase
{
private string twilioSID = "xxxxxx";
private string twilioAuthToken = "xxxxxx";
private string twilioPhoneNumber = "+15555555555";
[HttpGet]
public string Get(string phoneNumber)
{
TwilioClient.Init(twilioSID, twilioAuthToken);
var message = MessageResource.Create(
body: $"TEST message via Twilio",
from: new Twilio.Types.PhoneNumber(twilioPhoneNumber),
to: new Twilio.Types.PhoneNumber(phoneNumber)
);
return message.Status.ToString();
}
[HttpPost]
public string Post([FromBody] GeoEvent geoEvent)
{
TwilioClient.Init(twilioSID, twilioAuthToken);
var message = MessageResource.Create(
body: $"TEST message via Twilio",
from: new Twilio.Types.PhoneNumber(twilioPhoneNumber),
to: new Twilio.Types.PhoneNumber(geoEvent.PhoneNumber)
);
return message.Status.ToString();
}
}
GET and POST requests to the above endpoints get a 500 response when hosted in IIS. The following exception is thrown:
System.Net.Http.HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Lastly, here is the web.config that the SDK generated for me when I published the app in VS2019.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\TwilioService.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</location>
</configuration>
Neither my local machine nor the web server running IIS are behind a corporate proxy.
Am I missing an IIS or web.config setting that will allow .NET Core to make requests through IIS to a third party?
UPDATE:
I have now reproduced the same issue on a different web server running Windows Server 2016. This machine is setup with .NET 5, IIS 10, and the hosting bundle for .NET 5. I also installed VS2019 and recreated the web api project to run locally on the server. Here are the results:
Running locally in IIS Express, the api controller can successfully
make a request to the Twilio api and gets a response. The SMS
message is sent successfully. No errors.
Running locally in IIS 10, the api controller calls Twilio but
fails to get a response. The following error occurs:
Twilio.Exceptions.ApiConnectionException: Connection Error: POSThttps://api.twilio.com/2010-04-01/Accounts//Messages.json
---> System.Net.Http.HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (api.twilio.com:443)
To reiterate, both of the above scenarios are running on the same machine. The only difference is IIS Express vs IIS 10. Is this an SSL cert issue? Because IIS 10 works as a reverse proxy for .NET core apps, could there be a problem with a cert getting recognized or forwarded from the .net core app through IIS?
Try to ping the third-party service URL from your machine command prompt.
Make sure the firewall port is set to allow. check the antivirus is now blocking the connection.
try to add the defaultProxy section to my web.config in order to get my website to connect to a web service.
https://learn.microsoft.com/en-US/troubleshoot/dotnet/framework/cannot-consume-web-service-via-http-proxy
Solved. It turned out to be a corporate proxy after all. I had bad information that the web server was not behind a proxy but it was. Twilio has a solution for this exact scenario in their documentation involving the use of a custom proxied rest client class. It's a wrapper around System.Net.HttpClient. The service can now make calls to Twilio through the proxy using this class with the proxy server url set.

Can not connect to Azure SQL Server using Active directory integrated authentication in AppService

We have web application deploy on Azure App Service. Our database is also on Azure which is configured to use AAD authentication (We have assigned AAD Admin).
We are using below connection string in web app to connect to this server and database using below connections string.
Data Source=xxxxxxx.database.windows.net;Initial
Catalog=xxxxxxx;Persist Security Info=False;Authentication=Active
Directory Integrated
Please note: This connection string is working fine when using thru local system. But getting below error when we use this conn string in Azure App Service:
Failed to authenticate the user NT Authority\Anonymous Logon in Active
Directory (Authentication=ActiveDirectoryIntegrated). Error code
0x4BC; state 10 The format of the specified domain name is invalid
According to your description, I found you used the Active Directory integrated authentication.
To use integrated Windows authentication, your domain’s Active Directory must be federated with Azure Active Directory. Your client application (or a service) connecting to the database must be running on a domain-joined machine under a user’s domain credentials
If you published the web app to Azure, Azure's web app server will not be in your domain’s Active Directory. So the SQL server will not pass the auth.
I suggest you could try to use Active Directory password authentication instead of the Active Directory integrated authentication.
Replace the connection string as below use azure AD user name and password. It will work well.
Server=tcp:brandotest.database.windows.net,1433;Initial Catalog=bradnotestsql;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication="Active Directory Password";
Since the accepted answers are a bit dated, if you are out here in 2020 or later, the correct way for setting up integrated authentication is as follows:
(excerpted from here, the asp.net standard implementation)
https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi
add the Microsoft.Azure.Services.AppAuthentication nuget package.
modify your web.config by adding: (in configSections)
<section name="SqlAuthenticationProviders" type="System.Data.SqlClient.SqlAuthenticationProviderConfigurationSection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
(and then)
<SqlAuthenticationProviders>
<providers>
<add name="Active Directory Interactive" type="Microsoft.Azure.Services.AppAuthentication.SqlAppAuthenticationProvider, Microsoft.Azure.Services.AppAuthentication" />
</providers>
</SqlAuthenticationProviders>
It's important to pay attention to the name you use there. Then... your connection string will look like:
<add name="MyEntities" connectionString="metadata=res://*/Data.MyDB.csdl|res://*/Data.MyDB.ssdl|res://*/Data.MyDB.msl;provider=System.Data.SqlClient;provider connection string="server=tcp:MyDB.database.windows.net;database=MyDB;UID=AnyString;Authentication=Active Directory Interactive;"" providerName="System.Data.EntityClient" />
The important notes are that the name you specify in the SqlAuthenticationProviders section must be the exact same name you use in the connection string for Authentication.
The other important note is that, coming from your old connection strings, you have to change Data Source to be Server, and Initial Catalog to be Database. UID=AnyString is necessary, or an exception is thrown.
Failure to follow these steps exactly will net you a lovely error:
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> AdalException: The format of the specified domain name is invalid.\r\n at ADALNativeWrapper.ADALGetAccessToken(String username, IntPtr password, String stsURL, String servicePrincipalName, ValueType correlationId, String clientId, Boolean* fWindowsIntegrated, Int64& fileTime)\r\n at System.Data.SqlClient.ActiveDirectoryNativeAuthenticationProvider.<>c__DisplayClass2_0.b__0()\r\n at System.Threading.Tasks.Task`1.InnerInvoke()\r\n at System.Threading.Tasks.Task.Execute()\r\n --- End of inner exception stack trace
At the first the error doesn't make sense, but once you see that the parameters were renamed from Data Source to Server, it does make sense.
Maybe all you need to use is token (certificate) authentication as explained on below resource:
https://github.com/Microsoft/sql-server-samples/tree/master/samples/features/security/azure-active-directory-auth/token
Try to register your application with Azure Active Directory as explained on that resource.
Hope this helps.

Multi-tenant Azure Mobile App service calls failing with 401.71

To preface this, I'm new to Azure programming and Azure AD authentication and I've been following tutorials I've found at various sites (including MS) to get me this far. I'm using Xcode v7.2, ADAL for iOS v1.2.4, Visual Studio 2015 Update 1, and the Azure App Service Tools v2.8.1.
I have an existing native iOS app that I need to be able to authenticate multiple Azure Active Directory instance users through. These users are internal and external (customers who sign up for our services). To that end, I've experimentally implemented the following high level architecture:
Native Client App (iOS / obj-c) -> ADAL iOS library -> (Azure AD authentication) -> Azure Mobile App (service layer)
The iOS app utilizes the ADAL iOS library to acquire an access token which it uses to call authorized Web API services in the Azure Mobile App project.
I'm able to authenticate users from two tenants (an internal Azure AD and an external Azure AD), but only users in the same tenant as the service (internal) are able to call the authenticated APIs. The test user account I used from the external tenant is set up as a Global Admin and I am presented with the appropriate consent view in the native app when authenticating. I can then click through the consent and I receive an access token. When using that token to call a test API however, I get a 401 back. The verbose logs for the Azure Mobile App on the server show the following messages (all URLs below are https, I just don't have the rep to post them as such):
2016-01-12T13:00:55 PID[7972] Verbose Received request: GET MyAzureMobileApp.azurewebsites.net/api/values
2016-01-12T13:00:55 PID[7972] Verbose Downloading OpenID configuration from sts.windows.net/<internal AD GUID>/.well-known/openid-configuration
2016-01-12T13:00:55 PID[7972] Verbose Downloading OpenID issuer keys from login.windows.net/common/discovery/keys
2016-01-12T13:00:56 PID[7972] Warning JWT validation failed: IDX10205: Issuer validation failed. Issuer: 'sts.windows.net/<external AD GUID>/'. Did not match: validationParameters.ValidIssuer: 'sts.windows.net/<internal ad guid>/' or validationParameters.ValidIssuers: 'null'..
2016-01-12T13:00:56 PID[7972] Information Sending response: 401.71 Unauthorized
I've read in several posts that you can disable the token issuer validation in your service by setting the ValidateIssuer parameter in TokenValidationParameters to false. I've tried to do this, but it doesn't seem to have any effect. Here is the code from my Azure Mobile App project:
The startup code:
// Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(MyAzureMobileApp.Startup))]
namespace MyAzureMobileApp
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureMobileApp(app);
ConfigureAuth(app);
}
}
}
The code for the MobileApp -- this should be stock, as generated by the Azure Mobile App project template:
// Startup.MobileApp.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Web.Http;
using Microsoft.Azure.Mobile.Server;
using Microsoft.Azure.Mobile.Server.Authentication;
using Microsoft.Azure.Mobile.Server.Config;
using MyAzureMobileApp.DataObjects;
using MyAzureMobileApp.Models;
using Owin;
namespace MyAzureMobileApp
{
public partial class Startup
{
public static void ConfigureMobileApp(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
new MobileAppConfiguration()
.UseDefaultConfiguration()
.ApplyTo(config);
// Use Entity Framework Code First to create database tables based on your DbContext
Database.SetInitializer(new MobileServiceInitializer());
MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
if (string.IsNullOrEmpty(settings.HostName))
{
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
{
// This middleware is intended to be used locally for debugging. By default, HostName will
// only have a value when running in an App Service application.
SigningKey = ConfigurationManager.AppSettings["SigningKey"],
ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
TokenHandler = config.GetAppServiceTokenHandler()
});
}
app.UseWebApi(config);
}
}
public class MobileServiceInitializer : CreateDatabaseIfNotExists<MobileServiceContext>
{
protected override void Seed(MobileServiceContext context)
{
List<TodoItem> todoItems = new List<TodoItem>
{
new TodoItem { Id = Guid.NewGuid().ToString(), Text = "First item", Complete = false },
new TodoItem { Id = Guid.NewGuid().ToString(), Text = "Second item", Complete = false }
};
foreach (TodoItem todoItem in todoItems)
{
context.Set<TodoItem>().Add(todoItem);
}
base.Seed(context);
}
}
}
The authentication startup code:
// Startup.Auth.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens;
using System.Linq;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
namespace MyAzureMobileApp
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
ValidateIssuer = false
}
});
}
}
}
The service implementation:
using System.Web.Http;
using Microsoft.Azure.Mobile.Server.Config;
namespace MyAzureMobileApp.Controllers
{
// Use the MobileAppController attribute for each ApiController you want to use
// from your mobile clients
[MobileAppController]
// Use the MobileAppController attribute for each ApiController you want to use
// from your mobile clients
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public string Get()
{
return "GET returned: Hello World!";
}
// POST api/values
public string Post()
{
return "POST returned: Hello World!";
}
}
}
And my appSettings section in web.config:
<appSettings>
<add key="PreserveLoginUrl" value="true" />
<!-- Use these settings for local development. After publishing to your
Mobile App, these settings will be overridden by the values specified
in the portal. -->
<add key="MS_SigningKey" value="Overridden by portal settings" />
<add key="EMA_RuntimeUrl" value="Overridden by portal settings" />
<!-- When using this setting, be sure to add matching Notification Hubs connection
string in the connectionStrings section with the name "MS_NotificationHubConnectionString". -->
<add key="MS_NotificationHubName" value="Overridden by portal settings" />
<add key="ida:ClientId" value="-- MyAzureMobileApp App ID from Azure AD --" />
<add key="ida:Tenant" value="InternalTestAD.onmicrosoft.com" />
<add key="ida:Audience" value="https://InternalTestAD.onmicrosoft.com/MyAzureMobileApp" />
<add key="ida:Password" value="-- password value removed --" />
</appSettings>
I don't see a place to specify valid token issuers except as a property of the TokenValidationParameters collection in WindowsAzureActiveDirectoryBearerAuthenticationOptions.
According to my understanding of the code, I should have issuer validation disabled, but I have tried adding the external Azure AD STS URL here. Unfortunately, it doesn't seem to have any effect.
Does anybody know if this code is getting ignored or overridden for some reason? Is there some other setting I've missed to either disable issuer validation altogether, or specify a list of valid issuers?
I can certainly provide more information as requested, I'm just not sure what else might be relevant.
Thanks!
I believe I have found the cause of my validation logic being ignored. In the setup of my web api site in Azure App Services, I specified the primary tenant issuer URL by populating the Issuer URL textbox in the "Authentication/Authorization" > "Azure Active Directory Settings" blade. It turns out that when you're going to have more than one issuer (as in my multi-tenant scenario) you should leave this field blank.
It makes perfect sense that the JWT will validate against the issuer you provide in that textbox. What is not so intuitive to me is that you should leave it blank when you have more then one issuer. Maybe MS could add that in to the information bubble above it? Either that or provide some mechanism for allowing multiple issuer URLs.
Hopefully this saves someone else some time with this issue.
Just want to point out that if you have configured the authentication, and you had set the primary tenant issuer URL, and then you turned off this type of authentication, the API still reads from it. Clearing this field worked for me, though I never would have thought so, since I was no longer using AD authentication.

MVC 5 SQL Network Interfaces, error: 26 - Error, with [Authorize]

I'm having trouble setting up Authorization in MVC 5. I have a brand new MVC 5 website with Individual User Accounts and an SQL Server database with the five aspNet... tables.
I can login locally, it all works fine on my local server and I can even login the production database from my local website when I point my local connection string at the production server but I can't login from the website on the production server,
I get the following error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
The error only happens when I use [Authorize] on an Action where I then have to login, if I remove [Authorize] the Action and database work fine.
Any ideas
Edit
Just for clarity, the SQL Server is on one of Arvixe servers, and the website is at Godaddy here is my connection string
<add name="mysiteEntities"
connectionString="metadata =
res://*/Models.mysite.csdl|res://*/Models.mysite.ssdl|res://*/Models.mysite.msl;
provider = System.Data.SqlClient;
provider connection string ='
data source = xxxxx.arvixe.com;
Initial Catalog = mysite;
User ID = xxxxxx;
Password = xxxxxxx'"
providerName="System.Data.EntityClient" />
I am unable to login from Godaddy with this string but if I use this string on my local computer I can login.
I also have a number of websites set up with the same configuration in MVC 4 which work fine.
I had a similar issue; however, I wrongly assumed it to be that I was not using EF and SQL Server, but Telerik Data Access around Oracle 11g. What fixed it for me was to remove the RoleManager module in the config file, as per this article (http://blog.luppes.com/2013/12/08/mvc5-authentication-roles-failure/)
So, to paraphrase that link for posterity, it was:
<system.webServer>
<modules>
<remove name="RoleManager" />
</modules>
</system.webServer>
I worked this out but it let me to a new question that I wave a work around for. For this question I had the wrong base connection referenced in here.
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
The problem now is I need two connection strings to connect. One for Authorisation as MVC5 wants a Code First connection string but the rest of my code is Database First

Resources