How enable multiple domains for Access-Control-Allow-Origin?
I have one application (ASP .NET MVC) binded to example.com and www.example.com
Next code not valid.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://example.com,http://www.example.com" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
Valid or http://example.com or http://example.com
I need both
private void GlobalBeginRequest(object sender, EventArgs e)
{
var Origins = "domain1.com,domain2.com,domain3.com:8081";
if ((Request.Headers["Origin"] != null) && (Origins.Split(',').FirstOrDefault(x => Request.Headers["Origin"].Contains(x)) != null))
{
Response.Headers.Add("Access-Control-Allow-Origin", String.Format("{0}", Request.Headers["Origin"]));
}
}
Related
I can not upload large files. My page is base in ASP.NET.
In IIS I have 2 sites;
-1 for web service
-1 for web page
I try many ways that I found, but no work
Web service config;
////////////////////////////
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
...
</appSettings>
<connectionStrings>
...
</connectionStrings>
<system.web>
<httpRuntime maxRequestLength="50097151" />
<compilation debug="true" targetFramework="4.5.2" />
<authentication mode="Windows" />
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
</system.web>
</configuration>
////////////////////////////
////////////////////////////
Web page config;
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\....exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true">
<environmentVariables />
</aspNetCore>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="50741824" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
I expect upload large files, but the actual is that I only can upload small files.
[HttpPost]
[DisableRequestSizeLimit]
public ActionResult uplo(string filename, string base64)
{
if (base64 != null && filename != null)
{
Models.filemodel archmod = new Models.filemodel ();
var xxx= archmod .namefunction(filename, base64);
return new EmptyResult();
}
return new EmptyResult();
}
It works with [DisableRequestSizeLimit] tag !!!
I have done research on enabling gzpi compression on GoDaddy shared windoes hosting and here is the proposed solution:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
<dynamicTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>
But this is currently not working and I am not getting http response header, Content-Encoding gzip.
Can someone help me with this?
Thanks
Adding that to my Web.Config allowed my Godaddy site to compress aspx page responses. But to compress ASMX WebService responses, I had to additionally add this to Global.asax:
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
var app = sender as HttpApplication;
var acceptEncoding = app.Request.Headers["Accept-Encoding"];
var prevUncompressedStream = app.Response.Filter;
if (!string.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToLower();
if (acceptEncoding.Contains("gzip"))
{
app.Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
}
Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
}
I'm trying to implement a single-page app. I carried over some of my working code from another project (MVC4) to implement authentication. Right now I see cookies being set, but WebSecurity / User.Identity do not seem to be working for some reason. After logging in, subsequent requests never validate as authenticated, either via WebSecurity.IsAuthenticated, or User.Identity.IsAuthenticated. Does anyone know why this is happening?
Controller code:
public class AccountController : ApiController {
private readonly UserService _userService;
public AccountController() {}
public AccountController(UserService userService) {
_userService = userService;
}
[AllowAnonymous]
[HttpGet]
[Route("api/authpayload")]
// This gets called when the app loads. Always, User.Identity.IsAuthenticated is false.
public HttpResponseMessage AuthPayload() {
var payload = new AuthPayloadDto();
try {
var userId = WebSecurity.GetUserId(User.Identity.Name);
if (User.Identity.IsAuthenticated && userId > 0) {
payload.Username = User.Identity.Name;
} else {
LogOut();
payload.IsAuthenticated = false;
}
return Request.CreateResponse(HttpStatusCode.OK, payload);
} catch (Exception e) {
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
[HttpPost]
[Route("api/login")]
[AllowAnonymous]
public HttpResponseMessage LogIn(LoginModel model) {
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
try {
if (WebSecurity.IsAuthenticated)
return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in.");
if (!WebSecurity.UserExists(model.Username))
return Request.CreateResponse(HttpStatusCode.Conflict, "User does not exist.");
if (WebSecurity.Login(model.Username, model.Password, persistCookie: model.RememberMe)) {
// This code always gets hit when I log in, no problems. I see a new cookie get sent down as well, using Chrome debugger.
var payload = new AuthPayloadDto();
return Request.CreateResponse(HttpStatusCode.OK, payload);
}
LogOut();
return Request.CreateResponse(HttpStatusCode.Forbidden, "Login Failed.");
} catch (Exception e) {
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
Web.config:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880" />
</authentication>
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
The cookie that gets sent after login is not expired, and it does get sent back on subsequent requests, but IsAuthenticated is always false. What am I doing wrong?
Update:
I updated my web.config to the following to get everything working:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>
But I'd like to leave this open in case anyone has an explanation of why this works; I'm pretty lost.
In my current mvc 4 project with mssql,
its a simple one i so I just wanted very simple memmbership provider
I disabled
InitializeSimpleMembershipAttribute
by
[Authorize]
//[InitializeSimpleMembership]
public partial class AccountController : Controller
and added this code to global.asax under Application_Start
WebSecurity.InitializeDatabaseConnection(
connectionStringName: "DefaultConnection",
userTableName: "UserProfile",
userIdColumn: "UserID",
userNameColumn: "UserName",
autoCreateTables: true);
in my sql database the application created some tables on of them was Roles and UserInRoles just added the roles I needed like Admin, customer, etc...
and I restrict the access to some Controllers or Actions by adding this code
[Authorize(Roles = "Admin")]
public class MessagesController : Controller
I have an html page that requires "SuperAdmin" role in order to access it. Here is my web.config and all works well :
....
<handlers>
<add name="HTMLHandler" type="System.Web.StaticFileHandler" path="*.html" verb="GET" />
</handlers>
....
<location path="app/html/_superAdmin/Dashboards.html">
<system.web>
<authorization>
<allow roles="SuperAdmin" />
<deny users="*" />
</authorization>
</system.web>
</location>
The problem is the url string when the user is sent to login:
http://localhost:50138/Account/Login?ReturnUrl=%2Fapp%2Fhtml%2F_superAdmin%2FDashboards.html
I do not want the user to see "ReturnUrl=%2Fapp%2Fhtml%2F_superAdmin%2FDashboards.html".
How can I remove this querystring when the user is redirected to the login page.
Unless anyone can come up with something more elegant, this worked:
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
try
{
if (returnUrl.Contains("_superAdmin"))
{
return RedirectToAction("Login", "Account", new { area = "" });
}
}
catch (Exception)
{
}
return View();
}
ELMAH for MVC support following appsettings configurations
elmah.mvc.allowedRoles
elmah.mvc.allowedUsers
to secure the elmah route path using roles/users. Apparently, it works fine for windows or forms authentications. But I couldn't make it working for the claim based authentication.
Does anyone have experience with this?
I do this in web config
<elmah>
<security allowRemoteAccess="true" />
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sqlserver" applicationName="Eers.Web"/>
</elmah>
and further down
<location path="elmah">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="elmah.axd" inheritInChildApplications="false">
<system.web>
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
</handlers>
</system.webServer>
</location>
If you take note of the node it works just like any other security in MVC. It does not work with Claims though. for that You will have to write an Action filter
<authorization>
<allow users="*"/>
</authorization>
Here is my Actionfilter
public class ElmahRequestAuthorizationFilter : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.IsChildAction) return;
var controller = filterContext.RouteData.Values["controller"] as string;
if (controller != null && controller.ToLowerInvariant() != "elmah") return;
var authenticationComponent = GetAuthenticationInfo() // A method that will return us roles;
var goodRoles = new List<string> {
"TestRole",
"ThirdLevelSupport",
"Administrator"
};
var roles = authenticationComponent.Roles ?? new List<string>();
var thouShaltPass = roles.Intersect(goodRoles).Any();
if (!thouShaltPass)
{
throw new HttpException(404, "Not Found");
}
}
}