How to get without "default.aspx" url? - redirect

I implemented a following code in Global.asax file of my web application.
void Application_BeginRequest()
{
string rule = ConfigurationManager.AppSettings.Get("WwwRule");
HttpContext context = HttpContext.Current;
if (context.Request.HttpMethod != "GET" || context.Request.IsLocal)
{
return;
}
if (context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))
{
string url = context.Request.Url.ToString();
if (!url.Contains("://www.") && rule == "add")
{
string url = context.Request.Url.ToString().Replace("://", "://www.");
context.Response.Redirect(url);
}
}
}
When I am running above code it works as follows
example.com redirects to www.example.com/default.aspx
www.example.com redirects to www.example.com
http://www.example.com/ redirects to http://www.example.com/
last two conditions works very well. But the first condition did'nt works well because its adding "default.aspx" in the URL which I am not intrested in.
Can anyone please tell me how to make it as below
example.com should redirects to http://www.example.com
Thanks

Most likely the Request.Url is appending default.aspx because that's the page actually being served at the time (IIS makes this transparent to you because it's one of the default pages).
When you make your new URL that you're going to redirect, add another .Replace("/default.aspx", "") to the end of it. So...
string url = context.Request.Url.ToString().Replace("://", "://www.").Replace("/default.aspx", "");

Actually, the /default.aspx is added before the request reaches the BeginRequest event. If you want to remove it, you have to actually remove it:
void Application_BeginRequest() {
string rule = ConfigurationManager.AppSettings.Get("WwwRule");
HttpContext context = HttpContext.Current;
if (context.Request.HttpMethod != "GET" || context.Request.IsLocal) {
return;
}
if (context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) {
string url = context.Request.Url.ToString();
if (!url.Contains("://www.") && rule == "add") {
url = url.Replace("://", "://www.");
if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase) {
url = url.Substring(0, url.Length - 13);
}
context.Response.Redirect(url);
}
}
}

change your webconfig with below code:it solve my same problem.
<?xml version="1.0"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="default.aspx Redirect" stopProcessing="true">
<match url="^(.*\/)*default\.aspx$" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_METHOD}" negate="true" pattern="^POST$" />
</conditions>
<action type="Redirect" url="{R:1}" redirectType="Permanent"/>
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

Related

AZURE API management JWT-token validation (IDX10511: Signature validation failed)

I have created my own identity server, which issued/makes tokens based on username and code. It works locally between app service to app service, but when I try to validate the token on AZURE API management fails.
I think the error is in openid-config but can see what is wrong.
But gets this error:
IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.RsaSecurityKey, KeyId: 'AanrD1WcPkqMpK3p2S0JQ7ixqWkYBAL8hRnU6Dciiew', InternalId: 'b7aZZOAAhueurq_c62cqJcTBXL69skl6hu1a1oHLu1w'. , KeyId: AanrD1WcPkqMpK3p2S0JQ7ixqWkYBAL8hRnU6Dciiew
'.
kid: 'AanrD1WcPkqMpK3p2S0JQ7ixqWkYBAL8hRnU6Dciiew'.
Exceptions caught:
''.
token: '{"alg":"RS256","kid":"AanrD1WcPkqMpK3p2S0JQ7ixqWkYBAL8hRnU6Dciiew","typ":"JWT"}.{"nbf":1624878880,"exp":1627470880,"iss":"https://login.zenbi.dk","aud":"You"}'.
Token: eyJhbGciOiJSUzI1NiIsImtpZCI6IkFhbnJEMVdjUGtxTXBLM3AyUzBKUTdpeHFXa1lCQUw4aFJuVTZEY2lpZXciLCJ0eXAiOiJKV1QifQ.eyJuYmYiOjE2MjQ4Nzg4ODAsImV4cCI6MTYyNzQ3MDg4MCwiaXNzIjoiaHR0cHM6Ly9sb2dpbi56ZW5iaS5kayIsImF1ZCI6IllvdSJ9.Lm32InrGT5DfphZalI9oQPzm-jcNDsOTGGkhE0dpdhdL7xpcVuZ4go6-i1dDx_cri7Neh4cow9vv3JR_Q75qhmVEr9TVrbAXP1Spkz0uvJPa9pLsQIZxH6B5D1ICnC0ROjgr5PQFXbMJXAYPludai5GpJWtX7ufUvFjauW2p2l1ssuK1iB27YeuYw7IDpMbgQvzlgVvqD8E4dzFoWdq-kLF8ZP-A3qnAtEchXu5JVJg4d7o3gI--cqJ7RaF6ehzVvFHvgADw54j4Gniif-mjnLDCZU0CYDMfRGmt5kURSJSvJUXZtaJgKYa9eQ0jSib6At4LZUVGYlHxx_I5jtjd3w
<policies>
<inbound>
<base />
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="#((string)context.LastError.Message)" require-scheme="Bearer" require-signed-tokens="true">
<openid-config url="https://zenbicertificates.blob.core.windows.net/jwt/openid-configuration.json" />
</validate-jwt>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
</policies>
How about writing validate logic by yourself ?
<set-variable name="pass" value="#{
bool isAud = false;
bool isIss = false;
string pass = "false";
string authHeader = context.Request.Headers.GetValueOrDefault("Authorization", "");
if (authHeader?.Length > 0)
{
string[] authHeaderParts = authHeader.Split(' ');
if (authHeaderParts?.Length == 2 && authHeaderParts[0].Equals("Bearer", StringComparison.InvariantCultureIgnoreCase))
{
Jwt jwt;
if (authHeaderParts[1].TryParseJwt(out jwt))
{
string tempScp = jwt.Claims.GetValueOrDefault("scp", "null");
if(tempScp != "null"){
isAud = tempScp.Contains("YOU");
}
string tempIss = jwt.Claims.GetValueOrDefault("iss", "null");
if(tempIss != "null"){
isIss = tempIss.Contains("xxx");
}
}
}
}
if(isAud || isIss ){
pass = "true";
}
return pass;
}" />
<choose>
<when condition="#(context.Variables.GetValueOrDefault("pass") == "false")">
<return-response response-variable-name="existing response variable">
<set-status code="401" reason="Unauthorized hhh" />
</return-response>
</when>
<otherwise />
</choose>

Custom sitemap handler causing site to fail to load (Sitecore)

I'm trying to add a custom handler to my site to redirect to the appropriate Sitemap for the current language, i.e. mysite.com/sitemap.xml --> sitemap-en.xml, mysite.es/sitemap.xml --> sitemap-es.xml, etc.
This is my setup:
handler trigger patch:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<customHandlers>
<handler trigger="sitemap.xml" handler="sitemap.ashx" />
</customHandlers>
</sitecore>
</configuration>
web.config:
<add path="sitemap.ashx" verb="*" type="MySite.CustomSitecore.Handlers.SitemapHandler,MySite" name="SitemapXml" />
handler:
namespace MySite.CustomSitecore.Handlers
{
public class SitemapHandler : IHttpHandler
{
public bool IsReusable
{
get
{
throw new NotImplementedException();
}
}
public void ProcessRequest(HttpContext context)
{
try
{
var curSite = Sitecore.Context.Site;
var m_Sites = SitemapManagerConfiguration.GetSites();
foreach (DictionaryEntry site in m_Sites)
{
if (site.Key.ToString().Equals(curSite.Name))
{
var filepath = site.Value;
HttpContext.Current.Response.Redirect("/" + filepath, false);
return;
}
}
return;
}
catch (Exception ex)
{
Log.Info("Error in SitemapHandler: " + ex, this);
}
}
}
}
It's not working though, when I try to go to mysite.com/sitemap.xml and debug it steps through the redirect process as expected and looks as if it should be successfully redirecting to /sitemap-en.xml, but the page just spins and displays browser error saying that the page can't be loaded.
I have tried a couple different redirect methods, but nothing has worked. I tried this as well:
HttpContext.Current.Response.StatusCode = 200;
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.AddHeader("Location", "/" + filepath);
HttpContext.Current.Response.End();
return;
Not sure if this is the issue, But out of the box Sitecore don't allow .xml files. Security hardening.
You can use somethings like this in the config, to add the .xml extension
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<preprocessRequest help="Processors should derive from Sitecore.Pipelines.PreprocessRequest.PreprocessRequestProcessor">
<processor type="Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions, Sitecore.Kernel">
<param desc="Allowed extensions (comma separated)">aspx, ashx, asmx, xml</param>
</processor>
</preprocessRequest>
</pipelines>
</sitecore>
</configuration>
But I think a better solution, use the default and take security seriously.
Tell the search engine what the url of the sitemap is by using a robots.txt
User-agent: *
Sitemap: /sitemap.ashx

How to exclude a controller of being redirect to https in ASP.NET Core 1.1

Following this nice article https://long2know.com/2016/07/asp-net-core-enforcing-https/ i try to enforce HTTPS but with the exception of one single web-api controller that have to response to an embedded system not capable of SSL. The problem exist in the following Configure section of startup.cs.
var options = new RewriteOptions()
.AddRewrite("^api/&", "/api/", skipRemainingRules: true)
.AddRedirectToHttps(302, sslPort);
app.UseRewriter(options);
With the AddRewrite line (that doesn't replace anything) i try to trigger skipRemainingRules in order to avert the redirection. This is working at development in IIS express (trough localhost) but not at the production enviroment behind IIS. Apperently the SkipRemainingRules does not prevent the AddRedirectToHttps of enter into force.
Many thanks for any clue the may solve this.
I'm aware that my response is quite late, but maybe it will help someone.
var options = new RewriteOptions()
.AddRewrite(#"^api/(.*)", "api/$1", true)
.AddRedirectToHttps(302, sslPort);
app.UseRewriter(options);
With this solution one can call /api/... on http, every other request will be redirected to https.
I've testes this solution with .Net Core 2.1.
I eventually fix it with a custom redirect:
public class CustomRedirect : Microsoft.AspNetCore.Rewrite.IRule
{
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
var host = request.Host;
// Exclude localhost
if ( string.Equals(host.Host, "localhost", StringComparison.OrdinalIgnoreCase))
{
context.Result = RuleResult.ContinueRules;
return;
}
// Exclude api
if (request.Path.Value.Contains("/api/"))
{
context.Result = RuleResult.ContinueRules;
return;
}
// force other traffic to https
if (string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
{
string path = "https://" + host.Value + request.PathBase + request.Path + request.QueryString;
context.HttpContext.Response.Redirect(path,true);
context.Result = RuleResult.EndResponse;
}
}
}
And register in the Configure section of startup.cs:
app.UseRewriter(new RewriteOptions().Add(new CustomRedirect()));
I think there was an issue working with IIS even in Azure web apps regarding http/https redirect.
So one way to acheive this is to enforce it via web.config like this:
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
<match url="^((?!api).)*$" />
<conditions logicalGrouping="MatchAny">
<add input="{SERVER_PORT_SECURE}" pattern="^0$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:0}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
By this convention you are enforcing https for every url except those with api keyword inside.

Magento rest api getting error Request does not match any route

I have created a rest api web service but I am getting error on hitting the url
http://localhost:81/magento/api/rest/category/2
<magento_api>
<messages>
<error>
<data_item>
<code>404</code>
<message>Request does not match any route.</message>
</data_item>
</error>
</messages>
</magento_api>
My api2.xml is:-
<?xml version="1.0"?>
<config>
<api2>
<resource_groups>
<esoft_rescategories translate="title" module="Esoft_Restcategories">
<title>Esoft Restcategories API</title>
<sort_order>11</sort_order>
</esoft_rescategories>
</resource_groups>
<resources>
<esoft_restcategories translate="title" module="Esoft_Restcategories">
<group>esoft_rescategories</group>
<model>esoft_restcategories/api2_restapi</model>
<title>Categories</title>
<sort_order>11</sort_order>
<privileges>
<admin>
<create>1</create>
<!--<retrieve>1</retrieve>
<update>1</update>
<delete>1</delete>-->
</admin>
<guest>
<retrieve>1</retrieve>
<!--<create>1</create>
<update>1</update>
<delete>1</delete>-->
</guest>
</privileges>
<attributes>
<category_id>Category ID</category_id>
<name>Name</name>
<parent_id>Category Parent ID</parent_id>
<child_id>Category Child List</child_id>
<active>Active</active>
<level>Level</level>
<position>Position</position>
</attributes>
<routes>
<route_entity>
<route>/categories/:cat_id</route>
<action_type>entity</action_type>
</route_entity>
<route_collection>
<route>/categories</route>
<action_type>collection</action_type>
</route_collection>
</routes>
<versions>1</versions>
</esoft_restcategories>
</resources>
</api2>
</config>
My version file for guest is:-
<?php
class Esoft_Restcategories_Model_Api2_Restapi_Rest_Guest_V1 extends Esoft_Restapi_Model_Api2_Restapi {
/**
* Retrieve list of category list.
*
* #return array
*/
protected function _retrieveCollection()
{
$ruleId = $this->getRequest()->getParam('cat_id');
// $cat_mod = Mage::getModel('catalog/category')->load($ruleId)->toArray();
$cats = Mage::getModel('catalog/category')->load($ruleId);
$subcats = Mage::getModel('catalog/category')->load($ruleId)->getChildren();
$cur_category = array();
$node['category_id'] = $ruleId;
$node['name'] = $cats->getName();
$node['parent_id'] = $cats->getParentId();
$node['child_id'] = $subcats;
if($cats->getIsActive()){
$node['active'] = 1;
}else{
$node['active'] = 0;
}
$node['level'] = $cats->getLevel();
$node['position'] = $cats->getPosition();
$cur_category[] = $node;
// $subcats = Mage::getModel('catalog/category')->load($ruleId)->getAllChildren();
// $subcats = Mage::getModel('catalog/category')->load($ruleId)->getChildren();
if($subcats != '')
{
foreach(explode(',',$subcats) as $subCatid)
{
$_category = Mage::getModel('catalog/category')->load($subCatid);
$childcats = Mage::getModel('catalog/category')->load($subCatid)->getChildren();
$node['category_id'] = $subCatid;
$node['name'] = $_category->getName();
$node['parent_id'] = $_category->getParentId();
$node['child_id'] = $childcats;
if($_category->getIsActive()){
$node['active'] = 1;
}else{
$node['active'] = 0;
}
$node['level'] = $_category->getLevel();
$node['position'] = $_category->getPosition();
$cur_category[] = $node;
}
}
return $cur_category;
}
}
Please let me know how to fix this error.
Also let me know on what basis we define routes.
Simple answer for those searching for cause of this error:
Request does not match any route
Is that you are posting the wrong METHOD such as GET/POST/PUT/DELETE.
It could also be the path of the API url itself is wrong.
As per your description your url format is wrong (route miss matching in given url).
<route>/categories/:cat_id</route>
^^^^^^^^^
So you need to change the url like below
http://localhost:81/magento/api/rest/categories/2

How to do Mapnik <ElseFilter /> in TileMill CartoCSS

I'm trying to realize mapnik-XML block in TileMill CartoCSS like this (!!! symbolizers in rules aren't overlaping !!!):
<Rule>
<Filter>[attr_1]=value_1 and [attr_2]=value_2</Filter>
<LineSymbolizer ... />
</Rule>
.
.
<Rule>
<Filter>[attr_1]=value_3 and [attr_2]=value_4</Filter>
<PolygonSymbolizer .../>
</Rule>
<Rule>
<ElseFilter/>
<TextSymbolizer .../>
</Rule>
And I didn't find in documentation how to make the else-filter.
[attr_1 = value_1] [attr_2 = value_2] {
::line-symb {
line-color: #color;
}
}
.
.
[attr_1 = value_3] [attr_2 = value_4] {
::polygon-symb {
polygon-fill: #color;
}
}
// <ElseFilter/> ...
Any advice?
There's no equivalent to else: think of CartoCSS as CSS, which also doesn't have an 'else': you would just write a rule that applies to the general case. So, if you're styling a layer by its attributes, the else is expressed by making a rule that just applies to the layer, with no attribute filters.