I have deployed a Web API project to Azure Web app. And from a angularjs app I am trying a $http.get request to the API. but it gives a CORS(cross-origin) exception though I have enabled it in my Web API startup config
app.UseCors(CorsOptions.AllowAll);
I want to Enable CORS for Azure Web App, that would solve the problem I believe
EDIT
http://nearestbuyweb.azurewebsites.net/ this is the URL of the Web app. It is trying to access http://nearestbuyapi.azurewebsites.net/api/MenuBar where the exception occurs.
I think it is not possible with Azure Web App. MSDN Question
Please help!
Note: You use CORS settings to let other websites access your site's API. Not to access other site's APIs.
Based on your comments it sounds like you're getting the CORS error when you try to make external requests from your site. That's exactly the behavior CORS is supposed to block.
For the errors to go away you would have to apply the CORS config settings on the site who's API you're trying to access.
In your case you want to make sure you're applying the config changes on the http://nearestbuyapi.azurewebsites.net site. NOT on http://nearestbuyweb.azurewebsites.net/
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
I have CORS in Azure working using this:
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "PublicApi",
routeTemplate: "api/v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Web.config:
<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>
You need to remove the options handler in IIS using web.config.
http://eugeneagafonov.com/post/38312919044/iis-options-cors-aspnet-webapi-en
Sorry Guys,
The issue happens only at my corporate network. Having googled I found that corporate network can be disable CORS requests . Found this here link
Related
We have a .net Core 3.1 MVC web application running with ServiceStack Ormlite 5.12. Currently we have a 'public' Open API for users who wish to access data programmatically. We use the following in our AppHost:
public class AppHost : AppHostBase
{
public AppHost(IServiceProvider services, IWebHostEnvironment env)
: base("My API", typeof(MyAPIService).Assembly)
{
_appServices = services;
_env = env;
}
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
...
HandlerFactoryPath = "/myapipath"
});
Plugins.Add(new OpenApiFeature
{
...
});
}
}
And in our Web.config:
<configuration>
<location path="myapipath">
<system.web>
<httpHandlers>
<add path="servicestack*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
</system.web>
<!-- Required for IIS7 -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="servicestack*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>
</location>
</configuration>
We have MyApp.ServiceModel and MyApp.ServiceInterface projects that are accessed from the https://{baseurl}/myapipath endpoint. This all works well so far.
We wish to keep the existing OpenAPI unchanged so that users don't need to change anything when updating to a new version. But we also want to add another API for use with an angular application, either by adding a separate endpoint for a 2nd API, or by filtering out what is visible in swagger with our existing API. Is it possible to add a 2nd API plugin with a different path that is separate from the existing API?
There can be only one ServiceStack Open API Plugin registered which lists all publicly accessible APIs within an AppHost.
If you want to visually differentiate APIs you can Group related APIs with Tags:
[Tag("angular")]
public class MyRequest { ... }
Alternatively you can choose to Exclude Services from Metadata Pages with:
[ExcludeMetadata]
public class MyRequestDto { ... }
I have one application deployed on Microsoft Azure Web App. In that I have created web.config file.
I have 2 custom domain linked to my web app
api-stage.example.com
api-prev.example.com
I want to set 1 environment variable named PLATFORM when my API is accessed.
Eg. When I access api using api-stage.example.com I want to set value of PLATFORM to stage and when I access api using api-prev.example.com, I want to set value of PLATFORM to prev.
I access this env variable in code like below
$platform = getenv('PLATFORM');
Content of my web.config file looks like below.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpProtocol allowKeepAlive="true">
</httpProtocol>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
<rewrite>
<rules>
<rule name="ABC" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
<handlers>
<remove name="OPTIONSVerbHandler" />
<remove name="PHP56_via_FastCGI" />
<add name="PHP56_via_FastCGI" path="*.php" verb="GET, HEAD, POST, OPTION, DELETE, PUT, TRACE" modules="FastCgiModule" scriptProcessor="D:\Program Files (x86)\PHP\v5.6\php-cgi.exe" resourceType="Either" requireAccess="Script" />
</handlers>
</system.webServer>
</configuration>
Can anybody help me how to do this? Which block I need to add in web.config file. I cannot do this using Azure Portal via Application Setting, because it allows me to set only one value for PLATFORM varaible. But I want to set and access it using hostname which i am using to call an API.
If you don't want to set variables in the portal, you could refer to this doc: Configure app settings.
For ASP.NET and ASP.NET Core developers, setting app settings in App Service are like setting them in in Web.config or appsettings.json
Note:values in App Service override the ones in Web.config or appsettings.json. For other languages, the doc also provide the link.
And the below is my test. Trying to use System.Configuration.ConfigurationManager.AppSettings["testkey"] to get the value.
Hope this could help you. And from your description, you deploy two environment webs into one app service,one is stage and one is prev. So why not try the staging slots if you are using Standard, Premium, or Isolated App Service plan tier.
I am trying to verify my domain through Azure using this Article. However, it keeps saying it cannot verify. I think maybe it's because I am assuming just putting it in my wwwroot is sufficient, but I don't know what else I need to do to have https://{YOUR-DOMAIN-HERE}.com/.well-known/microsoft-identity-association.json open the file itself for verification.
Verification of publisher domain failed. Unable to connect to https://mydomain/.well-known/microsoft-identity-association. [uFNK6]
Many people have faced this issue, you could have a look at this1 and this2 on Github. You may get one-time free support ticket for this issue via
You could send an email to AzCommunity[at]microsoft[dot]com with a
reference to this thread and also your Azure Subscription GUID.
As a workaround, you could add your custom domain to Azure AD. Then verify your custom domain name. After verifying your domain, you could directly select a verified domain or verify a new domain in the Publisher Domain panel without host the file at https://{YOUR-DOMAIN-HERE}.com/.well-known/microsoft-identity-association.json.
Hope this could help you.
I solved this problem by adding a web.config file to the .well-known folder to remove charset=utf8 from the Content-Type response. This appears to be necessary.
Beofre you start you can check with Curl from a PowerShell instance to see if the Content-Type being returned includes the charset and therefore is the source of your problem.
C:> curl https://www.whateveryourdomainis.org/.well-known/microsoft-identity-association.json
The web.config file contents is as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<clear />
<add name="MicrosoftIdentityAssociation" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
</handlers>
<staticContent>
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</configuration>
You need to be aware that this will modify the child folders too and so if you have other sub-folders you may have to take remedial action ie another web.config file putting it back. However, it may be that once you have verified the site, the verification code can be deleted. See [https://learn.microsoft.com/en-us/answers/questions/37272/should-we-continue-to-host-microsoft-identity-asso.html][2]
would you help me?
i've created a web api on azure and chose not to allow anonymous requests but to use azure active directory to authenticate the requests. the app beneath has "sign-in and read user profile" permissions set.
if the controller behind the web api accepts GET requests it works, while it gives me the error : "You do not have permission to view this directory or page."
before i call the web api i open a iframe on the page (sharepoint page) to implicitly get the token from the web api, which calls the basic GET action below:
[ActionName("Connect")]
[HttpGet]
public IHttpActionResult Connect()
{
return base.Content(HttpStatusCode.OK, "OK", new JsonMediaTypeFormatter(), "text/plain");
}
later on i call via jquery another action (POST)...
public IHttpActionResult PostPromote([FromBody] string request)
but at this point i receive the 403 (Forbidden) message.
the CORS for my webapi is set in the web.config file:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https://mytenant.sharepoint.com" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true"/>
</customHeaders>
</httpProtocol>
if i switch the method to GET it works, as well as (of course) if i permit anonymous requests.
thank you a lot, that's making me crazy.
We have following technical stack in our application
AngularJS2
Asp.Net Core API
SQL Server
Now we need to store User Name for the Logged in User in table during Create/Edit for given item i.e. in Core API.
We have tried with
WindowsIdentity.GetCurrent().Name, it gives IIS APPPOOL\Asp.netCore
HttpContext.User.Identity gives null value
I get User Name with WindowsIdentity while working with Visual Studio, but with IIS, it gives value as Asp.Netcore i.e. pool name
Windows Authentication is enabled and Anonymous Authentication is disabled
Using IIS Version 6.1
Am I missing anything?
Do you have the forwardWindowsAuthToken set to true in the web.config?
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true"/>
I looked around and it was suggested to create Asp.Net Core WebApi application using Windows Authentication.
So when i created Asp.Net Core WebApi using Windows Authentication it worked and i got values in User.Identity objects.
So i created 2 applications i.e. one with Windows Authentication and one without, and then compared all files and found changes in following files
forwardWindowsAuthToken - true, this was tried before but issue was not solved and same was suggested by Daboul
launchSettings.json, Set windowsAuthentication: true & anonymousAuthentication: false
After doing this, I was able to values in User.Identity object.
The launchSettings.json file:
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false
}
}
The Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore forwardWindowsAuthToken="true" processPath="C:\Program Files\dotnet\dotnet.exe" arguments=".\YourWebsite.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
</configuration>
On Windows Server 2012 R2/IIS 8.0, even after setting forwardWindowsAuthToken=true in web.config, User.Identity.Name was not returning the user name but IIS APPPOOL so to resolve the issue I made below change;
Go to the web application in IIS
Open Configuration Editor
Change Section to system.webServer/serverRuntime
Change authenticatedUserOverride to UseAuthenticatedUser (for me it was set to UseWorkerProcessUser)
For further details refer to below link;
https://blogs.iis.net/jaroslad/what-does-the-authenticateduseroverrideuser-do