Good day.
When I click sign in, it loads up, then redirects to my initial page without going to the Azure B2C page. This behaviour is weird since I had gotten Azure B2C working and it started recently
I am using the following packages to hook up Azure AD B2C
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.2" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="7.0.2" NoWarn="NU1605" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.26.0" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="1.26.0" />
</ItemGroup>
On Azure, I have set up the user flows and I am consuming them in a .NET MAUI application that is allowing authentication just fine. I have brushed over the debug, console, hot reload tabs but there is no error being logged.
appsettings.json
{
"AzureAdB2C": {
"Instance": "https://****.b2clogin.com/",
"Domain": "****.onmicrosoft.com",
"TenantId": "cb6**************685",
"ClientId": "592******d1a",
"CallbackPath": "/home",
"SignUpSignInPolicyId": "B2C_1_signupsignin",
"SignedOutCallbackPath": "/signout/B2C_1_susi",
"ResetPasswordPolicyId": "bB2C_1_passwordreset",
"EditProfilePolicyId": "B2C_1_edit_profile",
"EnablePiiLogging": true
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
What am I doing wrong?
Related
I have an asp.net azure web api site, say myapi.azuresites.net, and my custom domain is myapi.mycompany.net.
In my web api, I use owin middleware to validate incoming token
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
},
Provider = new OAuthBearerAuthenticationProviderEx()
});
I registered an app under azure AD and add some client secret in.
From postman, I can get an oauth2 token from Azure AD with the App id and the client secret.
I included this token in the header and sends to my azure web api.
My code uses owin middleware to validate the token
If I send the request to myapi.mycompany.net, the token validation works.
If I send the request to myapi.azuresites.net, the token validation fails.
I can't really figure out why the token validation fails when calling azure site directly. If I grab the azure site's web.config down to my local machine and it works there as well.
I suspected that my AD app didn't have the right redirect URLs, but verified that and can't see obvious issue.
So is there a way to log some information on why authentication fails? As it is a remote azure site, can I trap this failure as exception and throw some out?
Although not sure why my AD authentication works now, I did find a way to log owin failures for azure site.
Basically this will log owin information
<system.diagnostics>
<trace autoflush="true"/>
<sources>
<source name="Microsoft.Owin">
<listeners>
<add name="KatanaListener"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="KatanaListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="d:\home\logfiles\Katana.trace.log"
traceOutputOptions="ProcessId, DateTime"/>
</sharedListeners>
<switches>
<add name="Microsoft.Owin" value="Verbose"/>
</switches>
</system.diagnostics>
Azure log has the following error when I try to send a request to a WCF service
In the working case the validate user of the membershipprovider is called, then AfterReceiveRequest is called and finally the webservice is invoked.
But in the non-working case the validateuser is not called. It directly goes on to AfterReceiveRequest and then webservice throws an exception that it can't understand the header.
The azure application gateway routes the request to the VM. It somehow looks the header or membership provider is not being recognized. SSL is managed at the gateway level.
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled ="true" httpsGetEnabled ="true" />
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="IDServices.CustomMembershipProvider,IDServices"/>
</serviceCredentials>
<useRequestHeadersForMetadataAddress />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="endbehavior1">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
</behaviors>
{ "timeStamp": "2019-03-11T16:18:29+00:00",
"resourceId": "/SUBSCRIPTIONS/245CA15E-8C11-4F4C-B6D7-9F3E8EC5943F/RESOURCEGROUPS/JXCHANGERG/PROVIDERS/MICROSOFT.NETWORK/APPLICATIONGATEWAYS/JHAAPPGW",
"operationName": "ApplicationGatewayAccess", "category": "ApplicationGatewayAccessLog", "properties":
{"instanceId":"appgw_0","clientIP":"009.04.06.009","clientPort":"65374","httpMethod":"POST","requestUri":"/PImage.svc","requestQuery":"",
"userAgent":"Apache-HttpClient/4.1.1 (java 1.5)","httpStatus":"500","httpVersion":"HTTP/1.1","receivedBytes":"2638","sentBytes":"917","timeTaken":"0.018","sslEnabled":"on",
"sslCipher":"ECDHE-RSA-AES256-GCM-SHA384","sslProtocol":"TLSv1.2","serverRouted":"40.124.51.221:80","serverStatus":"500","serverResponseLatency":"0.016","host":"jt.inaresecure.com"},
"time": "2019-03-11T16:18:29.0000000Z"}
Can anyone help me with what could be the problem. Is the request failing on the server? All I get is a Security header fault. The code works on every other machine and server except this VM on azure. The request uses the application gateway to route to the VM where the WCF service is hosted on SSL
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode>s:MustUnderstand</faultcode>
<faultstring xml:lang="en-US">The header 'Security' from the namespace 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' was not understood by the recipient of this message, causing the message to not be processed. This error typically indicates that the sender of this message has enabled a communication protocol that the receiver cannot process. Please ensure that the configuration of the client's binding is consistent with the service's binding.</faultstring>
</s:Fault>
</s:Body>
</s:Envelope>
This is the IIS log for the same call probably a different time because of my request
The request is set up to Use SSL. Why does it have 80 in the log? Is it not doing a SSL request? This is a request from SOAP UI
2019-03-11 17:27:44 10.0.0.4 POST /PCServices/2019/MySerivce.svc - 80 - 20.45.4.43 Apache-HttpClient/4.1.1+(java+1.5) - 500 0 0 1468
it may be fails cause of HTTP request.
if you calls from and to HTTPS than authentication done automatically.
but you have to forcefully authenticate while in HTTP request.
if (HttpContext.Current.Request.Url.Scheme.ToUpper().Equals("HTTP"))
{
CustomMembershipProvider auth = new CustomMembershipProvider();
auth.Validate(Username,Pswd);
}
I have a client app and Web API app hosted on different domains and want to utilize ADAL.js in my client app to login in my Web API app, but still getting Unauthorized error.
In web api web.config I've specified my AAD details:
<add key="ida:AudienceUri" value="http://clientappurl/" />
<add key="ida:FederationMetadataLocation" value="https://login.windows.net/...3596365/federationmetadata/2007-06/federationmetadata.xml" />
<add key="ida:ClientId" value=".....388ffcc3" />
<add key="ida:ClientSecret" value="....gBsD7o=" />
<add key="ida:Tenant" value="........onmicrosoft.com" />
<add key="ida:TenantId" value="........96365" />
<add key="ida:Auth" value="https://login.windows.net/" />
<add key="ida:GraphUrl" value="https://graph.windows.net" />
And updated Startup.Auth.cs with following:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = "http://myclientapp",
Tenant = "developertenant.onmicrosoft.com",
AuthenticationType = "OAuth2Bearer",
});
On the client I've specified endpoints (my api url), tenant and clientId. ADALjs redirects user to microsoft login page and looks like after sucessfull login it writes some data to local storage. But API app still respondes with Unauthorized error.
Are there any tutorials on how properly configure wep api and client apps hosted on different domains to utilize AAD?
How can I read authorized user details like AAD user group from my Web API app?
Here is an example which shows how to read AAD group claims from a web app:
https://github.com/Azure-Samples/active-directory-dotnet-webapp-groupclaims
Once you have the tokens, you can then call a Web API, which is shown by this example:
https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect
There's a good list of AAD examples here:
https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/
SCENARIO:
I have two applications, one is "SPA web application" and the other one is "Web API 2.0" which is deployed on IIS 8.0 on Windows Server 2012.
ERROR:
Website is accessible and working fine on the same machine but not from outside, web page is loaded properly but on ajax call to the API generates the following error...
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . This can be fixed by moving the resource to the same domain or enabling CORS.
On controller level I have added the following attribute:
[EnableCors(origins: "", headers: "", methods: "*", SupportsCredentials = true)]
Also enabled it in WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, action = "DefaultAction" }
);
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
}
web.config server configuration is like this..
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
and following is the snippet of the ajax call..
$.ajax({
type: 'get',
url: webApiUrl,
success: function (response) {
// some logic here
},
error: function (response) {
// some logic here
},
xhrFields: {
withCredentials: true
},
crossDomain: true
});
FURTHER DETAILS:
I have deployed the same website on IIS 7.5 on a Windows Server 2008 R2 and it is working fine without any issue.
Secondly I have also tried by adding following response headers in IIS 8..
Access-Control-Allow-Headers - Content-Type
Access-Control-Allow-Methods - POST,GET,OPTIONS
Also tried to change following value in web.config
to
None of these have worked for me so far. Looking for further help...
FIXED :: That was just the firewall blocking the hosted web api port :(
just the firewall blocking the hosted web api port
Something is missing with my ASP .NET Web Site Administration Tool, I don't see the "Security Question" nor the "Security Answer".
According to "Walkthrough: Using Authentication Service with Silverlight Business Application" (http://msdn.microsoft.com/en-us/library/ee942449(v=vs.91).aspx), this is what I should see when creating a new user:
But this is what I see instead:
The "Security Question" and the "Security Answer" are missing. What could I have not installed?, I'm using Visual Studio 2012.
For those interested you have to make Custom Membership Provider Setting, like:
<membership
defaultProvider="SqlProvider"
userIsOnlineTimeWindow="20">
<providers>
<clear/>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="LocalSqlServer"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
passwordAttemptWindow="10"
passwordFormat="Hashed"
minRequiredPasswordLength="7"
enablePasswordRetrieval="false"
applicationName="/" />
</providers>
</membership>
in the web.config file. Notice the requiresQuestionAndAnswer="true" setting.