Can we use HTTPMethod in Zuul Route Configuration? - netflix

The POST request to /app/login should be redirected to http://abc:100/app/login and the DELETE reqeust to /app/login should be redirect to http://xyz:200/app/login. How can this be achieved in the Netflix Zuul route configuration ? Is there an option to mention the http method in the route configuration ?
Here is the entry that explains our scenario.
zuul:
routes:
Login:
path: /app/login
url: http://abc:100/app/login
Logout:
path: /app/login
url: http://xyz:200/app/login

UPDATE: spring-cloud-netflix won't do this out-of-the-box with easy configuration, but it's actually easy to add a custom ZuulFilter that does what you need. See How do you you create custom Zuul filters in Spring Cloud?
I think something like this should work for you:
#Component
public class MyCustomZuulFilter extends ZuulFilter {
private urlPathHelper = new UrlPathHelper();
#Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
final String requestURI =
this.urlPathHelper.getPathWithinApplication(ctx.getRequest());
if ("/app/login".equals(requestURI)
&& ctx.getRequest() != null
&& !StringUtils.isBlank(ctx.getRequest().getMethod())) {
if ("DELETE".equals(ctx.getRequest().getMethod().toUpperCase())) {
ctx.set("serviceId", "XYZ-SVC");
ctx.setRouteHost(null);
ctx.addOriginResponseHeader("X-Zuul-ServiceId", location);
} else if ("POST".equals(ctx.getRequest().getMethod().toUpperCase())) {
ctx.set("serviceId", "ABC-SVC");
ctx.setRouteHost(null);
ctx.addOriginResponseHeader("X-Zuul-ServiceId", location);
}
}
return null;
}
}
Note that you may still need a Zuul rule that maps /app/login to an existing service depending on your setup, as the bundled PreDecorationFilter automatically sets unrecognized routes as "forward.to".
I have exactly the same use case, but Zuul doesn't appear to be able to route based on HTTP method at the moment.
The code in question is in ProxyRouteLocator#getMatchingRoute method. It iterates through the defined ZuulRoute entries to find matching routes. The logic in #getMatchingRoute and the properties of ZuulRoute don't appear to match on HTTP method, unfortunately.

Related

Url.Action returning incorrect URL for webapi action with Route attrubute

I have a problem with the behaviour of Url.Action();
I have a webapi where all controllers require explicit route prefix attribute and all actions require a route attribute.
I register my routes in the WebApiConfig.cs
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap =
{
["apiVersion"] = typeof( ApiVersionRouteConstraint )
}
};
config.MapHttpAttributeRoutes(constraintResolver);
I have currently commented out the line below, but (because) it did not change the incorrect behaviour:
//config.Routes.MapHttpRoute(name: "DefaultApi",
//routeTemplate: "api/v{version:apiVersion}/{controller}/{action}/{id}", defaults: new {id = RouteParameter.Optional});
My controllers look as follows:
[RoutePrefix("api/v{version:apiVersion}/programs")]
public class ProgramsController : ApiController
{
[HttpGet, Route("{telemetryKey}/versions/latest")]
public async Task<LatestVersionResponse> GetLatestVersionInfo(Guid telemetryKey)
{
// serious business logic
}
}
I expect that '#Url.Action("GetLatestVersionInfo", "Programs", new { telemetryKey = Guid.Parse("43808405-afca-4abb-a92a-519489d62290") })'
should return /api/v1/programs/43808405-afca-4abb-a92a-519489d62290/versions/latest
however, I get /Programs/GetLatestVersionInfo?telemetryKey=43808405-afca-4abb-a92a-519489d62290 instead. So, my routeprefix and route attributes are ignored.
Swagger correctly discovers my routes and I can validate that requests to the expected routes work OK - it's only the Url.Action() that is confused.
What can be wrong...?
Well, it seems there were a few things wrong.
Wrong helper:
I should be using the Url.HttpRouteUrl for generating API links from a razor view (Url.Link is for generating link from within API controllers)
Conflict with aspnet-api-versioning library
For some reason (perhaps a bug?) the prefix that I have on the controller (apiVersion variable) breaks the URL helper mechanism.
For now, I have ditched the aspnet-api-versioning library, but created an issue on their github repo, in case its a bug.
Since I really hate the idea of creating and maintaing magic strings, so I took the following approach - each controller has a public static class which contains const values for the route names:
[RoutePrefix("api/v1/developers")]
public class DevelopersController : ApiController
{
[HttpGet, Route("{developerId}/programs", Name = Routes.GetPrograms)]
public async Task<IEnumerable<Program>> GetPrograms(Guid developerId){}
public static class Routes
{
public const string GetPrograms = nameof(DevelopersController) +"."+ nameof(DevelopersController.GetPrograms);
}
}
Now that can be used from a razor controller in a simple and relatively safe manner:
#Url.HttpRouteUrl(DevelopersController.Routes.GetPrograms, new { developerId = /* uniquest of guids */})
A bit better than magic strings. I've also added a bunch of unit tests for controllers where I validate that each route is unique and proper and that the routes class only contains routes for the action it contains.
Try the following:
Name your route:
[HttpGet, Route("{telemetryKey}/versions/latest", Name="LatestVersionInfoRoute")]
public async Task<LatestVersionResponse> GetLatestVersionInfo(Guid telemetryKey)
{
// serious business logic
}
Use Url.Link method:
#Url.Link("LatestVersionInfoRoute", new { telemetryKey = Guid.Parse("43808405-afca-4abb-a92a-519489d62290") })

override default method route from plugin in nopcommerce in 3.8

I want to override search controller. When I try to install a plugin, I get an error exception what multiple type were found for the controller named Catalog.
Multiple types were found that match the controller named 'Catalog'. This can happen if the route that services this request ('AdvanceSearch') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.
And my route priority is most(100).
public void RegisterRoutes(RouteCollection routes)
{
// Product Search,
routes.MapRoute("Plugin.Misc.Twigoh.Search",
"Search",
new { controller = "Catalog", action = "Search" },
new[] { "Nop.Plugin.Misc.Twigoh.Search.Controllers" });
}
public int Priority
{
get
{
return 100;
}
}
You can override your route like this:
When you override route, then you should use MapLocalizedRoute(not MapRoute) which is override localized route. Here you are trying to define route which is already define.
Here do not use MapRoute use MapLocalizedRoute in this way.
routes.MapLocalizedRoute("Plugin.Misc.Twigoh.Search",
"search/",
new { controller = "Catalog", action = "Search" },
new[] { "Nop.Plugin.Misc.Twigoh.Search.Controllers" });
Edit:
I want same route and functionality but default controller can't have
"/" search feature little bit different
/search is default route of product search, you can see in Nop.Web > Infrastructure > RouteProvider.cs
Hope this helps!
May be you rename your project so that the file name of the assembly changes, it's possible for you to have two versions.
So remove old .dll from bin folder and build your project.

What happens after IRouteConstraint.Match returns false

For a multi tenant application in ASP.NET MVC 5, I have created a custom IRouteConstraint to check if a subdomain exists in the base url, like client1.myapplication.com or client2.application.com.
public class TenantRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string appSetting = ConfigurationManager.AppSettings[AppSettings.IsMultiTenancyEnabled];
bool isMultiTenancyEnabled = false;
bool isParsedCorrectly = bool.TryParse(appSetting, out isMultiTenancyEnabled);
if (isMultiTenancyEnabled)
{
string subdomain = httpContext.GetSubdomain();
if (subdomain != null && !values.ContainsKey("subdomain"))
{
values.Add("subdomain", subdomain);
}
return string.IsNullOrEmpty(subdomain) ? false : true;
}
else
{
return true;
}
}
}
Here is the route config setup:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreWindowsLoginRoute();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "Dime.Scheduler.WebUI.Controllers" },
constraints: new { TenantAccess = new TenantRouteConstraint() }
);
}
}
The route constraint works very well but I need to understand this process better. I want to know what happens exactly when this method below returns FALSE. The end result is a HTTP Error 403.14 - Forbidden page, but is there some way I can intercept this to present my own custom page? I usually capture these errors in the Global Asax file but in this case, it never gets there.
Could this have something to do with the fact that there won't be any routes that match the request? Is there any way to redirect to a custom page if no matches are found?
After any route constraint that is associated with the route returns false, the route is considered a non-match and the .NET routing framework will check the next route registered in the collection (the matching is performed in order from the first route down to the last route that is registered in the collection).
The end result is a HTTP Error 403.14 - Forbidden page, but is there some way I can intercept this to present my own custom page?
You can get more precise control over routing by inheriting RouteBase (or inheriting Route). There is a pretty good example of domain-based routing here.
The key to doing this is to make sure you implement both methods. GetRouteData is where you analyze the request to determine if it matches and return a dictionary of route values if it does (and null if it doesn't). GetVirtualPath is where you get a list of route values, and if they match you should (typically) return the same URL that was input in the GetRouteData method that matched. GetVirtualPath is called whenever you use ActionLink or RouteLink within MVC, so it is usually important that an implementation be provided.
You can determine the page that the route will direct to by simply returning the correct set of route values in GetRouteData.

In ASP.NET 5, how do I get the chosen route in middleware?

I am building an ASP.NET 5 (vNext) site that will host dynamic pages, static content, and a REST Web API. I have found examples of how to create middleware using the new ASP.NET way of doing things but I hit a snag.
I am trying write my own authentication middleware. I would like to create a custom attribute to attach to the controller actions (or whole controllers) that specifies that it requires authentication. Then during a request, in my middleware, I would like to cross reference the list of actions that require authentication with the action that applies to this current request. It is my understanding that I configure my middleware before the MVC middleware so that it is called first in the pipeline. I need to do this so the authentication is done before the request is handled by the MVC controller so that I can't prevent the controller from ever being called if necessary. But doesn't this also mean that the MVC router hasn't determined my route yet? It appears to me the determination of the route and the execution of that routes action happen at one step in the pipeline right?
If I want to be able to determine if a request matches a controller's action in a middleware pipeline step that happens before the request is handled by the controller, am I going to have to write my own url parser to figure that out? Is there some way to get at the routing data for the request before it is actually handled by the controller?
Edit: I'm beginning to think that the RouterMiddleware might be the answer I'm looking for. I'm assuming I can figure out how to have my router pick up the same routes that the standard MVC router is using (I use attribute routing) and have my router (really authenticator) mark the request as not handled when it succeeds authentication so that the default mvc router does the actual request handling. I really don't want to fully implement all of what the MVC middleware is doing. Working on trying to figure it out. RouterMiddleware kind of shows me what I need to do I think.
Edit 2: Here is a template for the middleware in ASP.NET 5
public class TokenAuthentication
{
private readonly RequestDelegate _next;
public TokenAuthentication(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
//do stuff here
//let next thing in the pipeline go
await _next(context);
//do exit code
}
}
I ended up looking through the ASP.NET source code (because it is open source now!) and found that I could copy the UseMvc extension method from this class and swap out the default handler for my own.
public static class TokenAuthenticationExtensions
{
public static IApplicationBuilder UseTokenAuthentication(this IApplicationBuilder app, Action<IRouteBuilder> configureRoutes)
{
var routes = new RouteBuilder
{
DefaultHandler = new TokenRouteHandler(),
ServiceProvider = app.ApplicationServices
};
configureRoutes(routes);
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
routes.DefaultHandler,
app.ApplicationServices));
return app.UseRouter(routes.Build());
}
}
Then you create your own version of this class. In my case I don't actually want to invoke the actions. I will let the typical Mvc middleware do that. Since that is the case I gut all the related code and kept just what I needed to get the route data which is in actionDescriptor variable. I probably can remove the code dealing with backing up the route data since I dont think what I will be doing will affect the data, but I have kept it in the example. This is the skeleton of what I will start with based on the mvc route handler.
public class TokenRouteHandler : IRouter
{
private IActionSelector _actionSelector;
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
EnsureServices(context.Context);
context.IsBound = _actionSelector.HasValidAction(context);
return null;
}
public async Task RouteAsync(RouteContext context)
{
var services = context.HttpContext.RequestServices;
EnsureServices(context.HttpContext);
var actionDescriptor = await _actionSelector.SelectAsync(context);
if (actionDescriptor == null)
{
return;
}
var oldRouteData = context.RouteData;
var newRouteData = new RouteData(oldRouteData);
if (actionDescriptor.RouteValueDefaults != null)
{
foreach (var kvp in actionDescriptor.RouteValueDefaults)
{
if (!newRouteData.Values.ContainsKey(kvp.Key))
{
newRouteData.Values.Add(kvp.Key, kvp.Value);
}
}
}
try
{
context.RouteData = newRouteData;
//Authentication code will go here <-----------
var authenticated = true;
if (!authenticated)
{
context.IsHandled = true;
}
}
finally
{
if (!context.IsHandled)
{
context.RouteData = oldRouteData;
}
}
}
private void EnsureServices(HttpContext context)
{
if (_actionSelector == null)
{
_actionSelector = context.RequestServices.GetRequiredService<IActionSelector>();
}
}
}
And finally, in the Startup.cs file's Configure method at the end of the pipeline I have it setup so that I use the same routing setup (I use attribute routing) for the both my token authentication and mvc router.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//Other middleware delcartions here <----------------
Action<IRouteBuilder> routeBuilder = routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
};
app.UseTokenAuthentication(routeBuilder);
//Middleware after this point will be blocked if authentication fails by having the TokenRouteHandler setting context.IsHandled to true
app.UseMvc(routeBuilder);
}
Edit 1:
I should also note that at the moment I am not concerned about the extra time required to select the route twice which is what I think would happen here since both my middleware and the Mvc middleware will be doing that. If that becomes a performance problem then I will build the mvc and authentication in to one handler. That would be best idea performance-wise, but what I have shown here is the most modular approach I think.
Edit 2:
In the end to get the information I needed I had to cast the ActionDescriptor to a ControllerActionDescriptor. I am not sure what other types of actions you can have in ASP.NET but I am pretty sure all my action descriptors should be ControllerActionDescriptors. Maybe the old legacy Web Api stuff needs another type of ActionDescriptor.

How to get redirection to /Account/Login working with specific route configuration

I have a scenario where I have my routes all prefixed with a country code, e.g. http://www.example.com/US/Home - the country code is used to store country-specific information in session. This is all working fine except for unauthenticated requests (e.g. polling AJAX requests the fire after a session has expired, or a user leaves their browser open for long periods of time during and after deployments), at which point the system will try and redirect to /Account/Login, instead of the country specific URL, e.g. /US/Account/Login. Because /Account/Login is not a valid route the system throws a The controller for path '/Account/Login' could not be found or it does not implement IController. exception.
First prize would be to able at to redirect to a country-specific e.g. /US/Account/Login, but that is not possible I could work with /Account/Login. If I add in a route for /Account/Login it gets superseded by the DefaultCountryCode route (if placed below in the route configuration), or it supersedes the DefaultCountryCode route (if placed below in the route configuration).
Route Configuration
// if placed here this supersedes DefaultCountryCode route
//routes.MapRoute("Account", "/Account/Login");
// e.g. http://www.example.com/US/Home
routes.MapRoute("DefaultCountryCode", "{countrycode}/{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
// if placed here this gets superseded by DefaultCountryCode route
//routes.MapRoute("Account", "/Account/Login");
Create custom authorize attribute and add it to your controllers or register globally:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Cancel && filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "controller", "Account" },
{ "action", "Login" },
{ "countrycode", /* extract it from: filterContext.HttpContext.Request.RawUrl or somewhere from context */ }
});
}
}
}
Have you looked into attribute routing instead? You can create your controller and have two actions -
One that will be called when you have "US/Accounts/Login/{id}" and the other one can have the attribute for "Accounts/Login."

Resources