"Access-Control-Allow-Origin" not working while requested URL makes another request (Cross Domain Rquest) - cross-domain

I added AllowOrigin custom attribue with requested controller action. Refer below function:
public class **AllowCrossSiteJsonAttribute** : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);<br>
}
}
[**AllowCrossSiteJson**]
public partial class OneBillSummaryController : UXPControllerBase
{
public OneBillSummaryController()
: base(ApplicationType.Home,
new QueryParameters() { appliesTo="Index", parameters=
new Dictionary<string, QueryParameter>() {
{ "BAN", new QueryParameter() },
{ "SeqNo", new QueryParameter() },
{ "CID", new QueryParameter() {values="cc,ss,r"} },
{ "Lang", new QueryParameter() {values="fr,en"}},
{ "TID", new QueryParameter(){isOptional=true} }
}})
{
}
Till here, I was able to get result, but this action will do form authentication (already cookie exist in browser) and another URL/Controller-Action is going to call (Another URL request internally).
And I am stucking with below error. Refer below SS:
XMLHttpRequest cannot load
http://local-mybell-b.ids.int.bell.ca/UXP/Bill/OneBill/?BAN=101465254&SeqNo=0&CID=r&TID=&Lang=en.
The request was redirected to
'http://local-mybell-b.ids.int.bell.ca/sso/ssoauth.aspx?ReturnUrl=%2fUXP%2fB…d0%26CID%3dr%26TID%3d%26Lang%3den&BAN=101465254&SeqNo=0&CID=r&TID=&Lang=en',
which is disallowed for cross-origin requests that require
preflight.
Added same CROS for that authentication action as well, but no luck.

Yes, I got the answer Self, and posting the same.
Use "Access-Control-Allow-Origin" in web-config or controller level as per requirement and Change the authentication mode of web, As I disabled windows auth mode.
Above code will work perfect, just while changing the Auth mode from configuration file.
Refer below SS.

Related

struggling with an ASP.NET MVC5 routing issue

So, I have an MVC5 site that uses the default routing template {controller}/{action}/{id} and this works fine. Most everything in the site requires a login (i.e. [Authorize] attribute is used almost everywhere), and this works fine.
Well, now I have a need to allow anonymous access to select pages when a certain kind of link pattern is used: App/{token}/{action}. The {token} is a random string associated with something in my database. I can issue and deactivate these tokens at will.
I got this new App/{token}/{action} routing working by implementing a custom RouteBase that parses the incoming URL for these tokens, and, crucially, adds the the token value to the RouteData.DataTokens so that my App controller can make use of it without needing an explicit action argument for it. So, I added this new route to the route table ahead of the default routing like this:
// new route here
routes.Add("AppToken", new AnonAppAccessRoute());
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Here is the problem/question: adding this now route has now made my default route stop working -- everything is now going through AnonAppAccessRoute which of course is meant to work only for a few things. I don't understand how to make my AnonAppAccessRoute apply only to URLs with a certain pattern. The MapRoute method accepts a URL pattern, but Adding a route doesn't seem to let you put a filter on it. What am I missing? I've looked around quite a bit at various blogs and documentation about routing, but I've not found good info about using the DataTokens collection (which I feel is important to my approach), and I'm not seeing a good explanation of the difference between Adding a route explicitly vs calling MapRoute.
Here's the code of my custom RouteBase:
public class AnonAppAccessRoute : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData result = null;
string[] pathElements = httpContext.Request.Path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (pathElements.Length > 0)
{
string token = TryGetArrayElement(pathElements, 1);
if (!string.IsNullOrEmpty(token))
{
result = new RouteData(this, new MvcRouteHandler());
result.DataTokens.Add("appToken", token);
result.Values.Add("controller", "App");
result.Values.Add("action", TryGetArrayElement(pathElements, 2, "Index"));
}
}
return result;
}
private string TryGetArrayElement(string[] array, int index, string defaultValue = null)
{
try
{
return array[index];
}
catch
{
return defaultValue;
}
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return null;
}
}
I got this to work by dropping the custom RouteBase and instead used this MapRoute call like this:
routes.MapRoute(
name: "AppAnon",
url: "App/{token}/{action}",
defaults: new { controller = "App", action = "Index" }
);
Then, in my App controller, I did this in the Initialize override:
protected AppToken _appToken = null;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
string token = requestContext.RouteData.Values["token"]?.ToString();
_appToken = Db.FindWhere<AppToken>("[Token]=#token", new { token });
if (!_appToken?.IsActive ?? false) throw new Exception("The token is not found or inactive.");
}
This way, my "token" is available to all controller actions via the _appToken variable, and already validated. I did not need to use RouteData.DataTokens. Note that my Db.FindWhere statement is ORM-specific and not really related to the question -- it's just how I look up a database record.

Broadleaf APIs not working

I'm trying to consume Broadleaf APIs to Create Cart, Add Item and Checkout on a consumer application.
Cloned Demo application and modified the configuration as per the link:
https://www.broadleafcommerce.com/docs/core/current/broadleaf-concepts/rest/rest-tutorials
Problems:
1. Create new Cart->
POST: http://localhost:8080/api/v1/cart
Exception: HttpRequestMethodNotSupportedException: Request method 'POST' not supported
With GET request: worked
Add Product ID:
POST: http://localhost:8080/api/v1/cart/1?categoryId=1&customerId=100
Exception:HttpRequestMethodNotSupportedException: Request method 'POST' not supported
GET Request worked but the product is not added.
3.Add a Payment to the Order
POST: http://localhost:8080/api/v1/cart/checkout/payment?customerId=100
Added the OrderPaymentWrapper in the body as mentioned in the above URL
Exception:
messageKey": "queryParameterNotPresent",
"message": "com.broadleafcommerce.rest.api.exception.BroadleafWebServicesException.queryParameterNotPresent"
Alternatively, referred https://demo.broadleafcommerce.org/api/v2/swagger-ui.html#/ to invoke the API as per the swagger documentation.
Same issue, unable to create a order flow.
I've tried to debug by running on localhost https://github.com/BroadleafCommerce/DemoSite
Same issue.
Please advise.
This looks like an outstanding issue with our #FrameworkController annotation. I opened an issue in Broadleaf at https://github.com/BroadleafCommerce/Issues/issues/3 with more information as to why it is currently failing.
The workaround is to modify CustomCartEndpoint in the API project that you have to add in the createNewCartForCustomer() method. The final implementation of CustomCartEndpoint should look like this:
#RestController
#RequestMapping(value = "/cart",
produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public class CustomCartEndpoint extends CartEndpoint {
#Override
#RequestMapping(value = "", method = RequestMethod.GET)
public OrderWrapper findCartForCustomer(HttpServletRequest request) {
try {
return super.findCartForCustomer(request);
} catch (Exception e) {
// if we failed to find the cart, create a new one
return createNewCartForCustomer(request);
}
}
#Override
#RequestMapping(value = "", method = RequestMethod.POST)
public OrderWrapper createNewCartForCustomer(HttpServletRequest request) {
return super.createNewCartForCustomer(request);
}
}

How to redirect to an action method of another area within OnActionExecuting

In My MVC5 application I have 3 areas. My project structure as following
I have implemented an ActionFilter class to validate whether user has granted the permission for particular action methods. My ActionFilter class stay out of areas folder. I want to check user permission within the OnActionExecuting method and redirect to PermissionDenied action method which has implemented on ErrorControl. However it does not recognize within areas and gives an error message mentioning "No controller and action method found within the area"
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(!GrantPermission(filterContext))
{
Controller contr = (BaseController)filterContext.Controller;
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "area", "" },
{ "controller", "Error" },
{ "action", "PermissionDenied" }
});
filterContext.Result.ExecuteResult(contr.ControllerContext);
}
base.OnActionExecuting(filterContext);
}
Can anyone help me to get this solved. this one already has ruined my day.
Area is not a route value. It is put into the RouteData.DataTokens dictionary instead. But there is no way to set it from RedirectToRouteResult.
Instead, you could use the UrlHelper to generate the URL much as you would in an ActionLink. The UrlHelper will work out what the virtual path of your Area is. Then, you can just use RedirectResult to get to that URL.
if (!GrantPermission(filterContext))
{
Controller contr = (BaseController)filterContext.Controller;
var urlHelper = new UrlHelper(filterContext.RequestContext);
var redirectUrl = urlHelper.Action("PermissionDenied", "Error", new { area = "" });
filterContext.Result = new RedirectResult(redirectUrl);
filterContext.Result.ExecuteResult(contr.ControllerContext);
}
base.OnActionExecuting(filterContext);
NOTE: The correct way to authorize an action is to use either IAuthorizationFilter or better yet, inherit AuthorizeAttribute. Authorization filters run before action filters do. Also, they will execute the result handler automatically for you.

mvc custom route gives 404

I am trying to make a custom route but I cannot get it working and even though everything seems okay it always returns 404.
So here are the route defined.
It is defined first before the default and according to route debugger this is the route that gets hit.(Matched Route: Game/{id}/{title})
routes.Add(
"GamesDefault",
new Route("Game/{id}/{title}",
new RouteValueDictionary(new { controller = "Games", action = "ShowGame" }),
new DefaultMvcRouteHandler(urlTranslator, urlFoundAction)));
Here is the path Im trying to reach: /Game/5/test
And this is the Controller declaration. The GamesController is placed in the Controllers folder and its view are in Views/Games/showGames.cshtml.
public GamesController()
{
}
public ActionResult ShowGames(int id, string title)
{
return View(title);
}
The DefaultMvcRouteHandler doesnt do anything fancy.
public class DefaultMvcRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MvcHandler(requestContext);
}
}
The default route works without problems, and I have tried everything I can find like changing the name of the route so it doesnt match any folders or anything like that.
If anyone have any ideas on what more to try I would be most grateful.
As per my comment you are passing incorrect default route values for the controller and action values.
Update your route like so:
routes.Add(
"GamesDefault",
new Route("Game/{id}/{title}",
new RouteValueDictionary(new { controller = "GamesController", action = "ShowGames" }),
new DefaultMvcRouteHandler(urlTranslator, urlFoundAction)));

ServiceStack Basic Authentication HtmlRedirect is not respected by MVC ServiceStackController

I'm probably not understanding something but I have the issue below:
AppHost.cs
Plugins.Add(new AuthFeature(
() => new AuthUserSession(),
new IAuthProvider[] { new BasicAuthProvider() }) { HtmlRedirect = null });
HomeController.cs
[Authenticate]
public class HomeController : ServiceStackController
The issue
The issue is that when I try to access the HomeController, I am redirected to ~/login?redirect=.....
I would assume that by setting HtmlRedirect to null, would also affect the MVC controllers too, but it doesn't seem to.
Is this expected behaviour? or is am I doing something wrong?
My end goal is to have the browser prompt with a challenge / response basic auth box.
Since this commit you are able to override the default behavior when authentication failed:
[Authenticate]
public class HomeController : ServiceStackController
{
public override ActionResult AuthenticationErrorResult
{
get
{
//return 401 Unauthorized for example
return new HttpStatusCodeResult(401);
}
}
}
ServiceStackController.AuthorizationErrorResult can be modified in the same way.
Setting HtmlRedirect to null doesn't work in this case, because the behavior of the [Authenticate] attribute (and all other ServiceStack attributes) is slightly different when used with ASP.net MVC controllers instead of ServiceStack services.
I have been on the ServiceStack Jabbr chat page and was told that this is a bug and a fix will be put on today!
https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.FluentValidation.Mvc3/Mvc/ExecuteServiceStackFiltersAttribute.cs#L25

Resources