Correct way to validate query string parameters to authorize a ASP.NET CORE request - asp.net

Shopify allows to embed pages into the admin site, to do that I can create a page using ASP.NET MVC and get the page shown in the admin panel of Shopify.
To validate if the page request is valid and was request by Shopify there are some parameters sent in the query string that the page has to validate before processing the request and render the page.
Shopify sends a hmac parameter so I can calculate the same parameter and validate if both are equal.
I was using Asp.Net Mvc 5 and used the AuthorizeAttribute class but now I am using Asp.Net Core and it seems authorization filters have changed.
I have read some articles about how is the new authorization system in Asp.Net Core but I can't determine what is the best way to do it.
So in the end I need:
Crete a custom attribute so I can add it to my controllers. When Shopify calls my pages I need to verify the query string parameters before the controller action starts to process the request, in the case the request is not valid the controller action is not called but if the request is valid it authorizes and lets the controller action to execute and render the page.
My current filter in Asp.Net MVC 5 is something like this:
namespace MyShopifyApp.Filters
{
public class EmbeddedAppAuthAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//Validates if the nonce/state from the query string is correct
var stateParameter = httpContext.Request.QueryString["state"];
var nonce = ShopifyHelper.AuthorizationNonceManager.GetNonce(ProjectSettings.ShopifyShopUrl);
if (!string.IsNullOrEmpty(stateParameter))
{
if (string.IsNullOrEmpty(nonce) || stateParameter != nonce)
{
return false;
}
}
//Validates if the shop parameter from the query string is valid
var shopParameter = httpContext.Request.QueryString["shop"];
if (!ProjectSettings.IsValidShop(shopParameter))
return false;
//Calculates a HMAC signature and validates if the request is really from Shopify
if (!ShopifyAuthorizationService.IsAuthenticRequest(httpContext.Request.QueryString, ProjectSettings.ShopifyAdminAppApiSecret))
return false;
//Everything is correct so allow the request to continue
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
}
}
}
This is an example controller:
namespace MyShopifyApp.Controllers
{
[EmbeddedAppAuth]
public class MyController : Controller
{
public async Task<ActionResult> Index(string hmac, string shop, string signature, string timeStamp, string protocol)
{
//Do something here only if the request is authentic and sent by Shopify
}
}
}

Related

MVC 6 Areas and multiple login pages redirect

I'd been searching for a solution to this problem for quite a long time but unfortunately haven't found any nice and elegant way to handle it.
Here are the details:
My MVC 6 application use Areas. Each area has separate directories for the Controllers, Views etc.
Authentication is based on the standard out of the box web application template with user accounts stored in sql server
What I want to achieve is:
When user enters /AreaA/Restricted/Page then he is redirected into /AreaA/Account/Login
When user enters /AreaB/Restricted/Page then he is redirected into /AreaB/Account/Login etc...
Even though I can change the stanard login page redirect from "/Account/Login" into something different like this:
services.Configure<IdentityOptions>(options=> {
options.Cookies.ApplicationCookie.LoginPath =
new Microsoft.AspNet.Http.PathString("/HardcodedAreaName/Account/Login");
});
I am not able to redirect into different actions/login pages for each area.
Prior to MVC 6 I was able to use AuthorizeAttribute with url parameter:
public class CustomAuthorization : AuthorizeAttribute
{
public string Url { get; set; }
// redirect to login page with the original url as parameter.
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery);
}
}
and then passing the area dependent url by decorating each controller:
[CustomAuthorization(Url = "/Admin/Account/Login"]
public class AdminAreaController : Controller
{ ...
But it does not work anymore :(
Try the following and see if it works (I did try this and it works fine, but not sure If I have covered all scenarios):
The place where you register you CookieAuthentication middleware, you can do something like
app.UseCookieAuthentication(o =>
{
o.LoginPath = "/area1/login1";
o.AuthenticationScheme = "scheme1";
//TODO: set other interesting properties if you want to
});
app.UseCookieAuthentication(o =>
{
o.LoginPath = "/area2/login2";
o.AuthenticationScheme = "scheme2";
//TODO: set other interesting properties if you want to
});
On you controller/action, specify the authentication scheme..example:
[Authorize(ActiveAuthenticationSchemes = "scheme1")]
public IActionResult Test1()
{
return Content("Test1");
}
[Authorize(ActiveAuthenticationSchemes = "scheme2")]
public IActionResult Test2()
{
return Content("Test2");
}

Using a Custom Authentication/Authorization attribute for an action

We have a website that uses ASP Identity and works great with the [Authorize] attribute sprinkled on all the appropriate classes.
What i'm looking to do is create a separate authentication system for a specific set of actions. It's a page that isn't exactly anonymous, but can be viewed if a PIN is entered correctly.
I started looking into Authentication/Authorization attributes and got to a point where it redirects to my PIN entry page if not authenticated.
So I guess what i'm asking is how do I authenticate a virtual user (aka: not in the database) to be able to access those pages after entering in the correct PIN?
You could create your own version of the AuthorizeAttribute by inheriting from it and overriding the AuthorizeCore method.
public class PinAuthorizeAttribute : AuthorizeAttribute
{
private readonly string _password;
public PinAuthorizeAttribute(string password)
{
_password = password;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//Check if user has entered the correct PIN, perhaps
//by keeping the PIN in the Session
if(Session["PIN") == _password)
return true;
return false;
}
}
Now add it to your action method:
[PinAuthorize("1234")]
public ActionResult ProtectedIndex()
{
//snip
}

Asp.Net MVC5 How to ensure that a cookie exists?

I'm new to MVC (5). In order to add localization support to my website I added a "Language" field to my ApplicationUser : IdentityUser
What's the best approach to now store this information in the browser and ensure that it gets re-created even if the user manually deletes it?
TL; but I've got time
What I've tried until now:
I started creating a cookie in my method private async Task SignInAsync(ApplicationUser user, bool isPersistent) but I notice that:
This method is not used if the user is already authenticated and automatically logs in using the .Aspnet.Applicationcookie and my language cookie could be meanwhile expired (or been deleted).
A user could manually delete the cookie, just for fun.
I thought about checking its existence in the controller (querying the logged user and getting it from the db) and it works but I'd need to do it in EVERY controller. I'm not sure is the correct way to do this.
Any suggestion about how to approach this problem and guarantee that the application has a valid "language cookie" on every request?
It sounds to me like what you want here is a Custom Action Filter. You can override the OnActionExecuting method which means the logic is run before any action is called
public class EnsureLanguagePreferenceAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var langCookie = filterContext.HttpContext.Request.Cookies["LanguagePref"];
if (langCookie == null)
{
// cookie doesn't exist, either pull preferred lang from user profile
// or just setup a cookie with the default language
langCookie = new HttpCookie("LanguagePref", "en-gb");
filterContext.HttpContext.Request.Cookies.Add(langCookie);
}
// do something with langCookie
base.OnActionExecuting(filterContext);
}
}
Then register your attribute globally so it just becomes the default behaviour on every controller action
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new EnsureLanguagePreferenceAttribute());
}
To me, the easiest way would be to create your own Authorize attribute (since your language options are tied to an authenticated user account). Inside of your new authorize attribute, simply perform the check if the cookie exists. If it does, then life is good. Else, query the user's database profile and reissue the cookie with the stored value
public class MyAuthorization : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//no point in cookie checking if they are not authorized
if(!base.AuthorizeCore(httpContext)) return false;
var cookie = httpContext.Request.Cookies["LanguageCookie"];
if (cookie == null) {
CreateNewCookieMethod();
}
return true;
}
}
To use, replace [Authorize] with [MyAuthorization] in your project.
If you don't want to mess with the [Authorize] attribute, you could create your own attribute that does the cookie checking and decorate your controller with that one as well.
One last alternative is to create your own Controller class that does the checking on the OnActionExecuting.
public class MyBaseController : Controller
{
public string Language {get;set;}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var cookie = filterContext.HttpContext.Request.Cookies["LanguageCookie"];
if(cookie == null){
cookie = CreateNewCookieMethod();
filterContext.HttpContext.Request.Cookies.Add(cookie);
}
Language = cookie.Value;
base.OnActionExecuting(filterContext);
}
How to use (note that we inherit from MybaseController now)
public class HomeController : MyBaseController{
public ActionResult Index(){
//Language comes from the base controller class
ViewBag.Language = Language;
Return View();
}
}
This method is neat because now that Language variable will be available in any controller that inherits from this new class.
Either of these will give you a single, cookie checking point. Additionally, you are only going back to the database only in the instance that the cookie does not exist.

Add token parameter to all urls inside an asp.net mvc 2 site

I've integrated some pages written in ASP.NET MVC 2, into a classic webform app.
Everything works well except the authentication system.
The authentication system is using some token added to the url like :
/Account/Profil/Details.aspx?AUTHID=2ddc098a-cf0b-fd81-afb7-d41f35010b9f
When i reach my asp.net mvc pages (all these pages must be secured), they must include that AUTHID parameter.
I'm using the core Webform control to secure the pages, and this control check for the AUTHID token in the url. So basicly my route must include the
?AUTHID=2ddc098a-cf0b-fd81-afb7-d41f35010b9f
What the best and clever way to do this ?
I don't want to pass the AUTHID parameter manually in all controller actions.
Thanks for your help.
You can solve your problem by extending the ASP.NET routing mechanism. Just create a custom route and override the GetVirtualPath function.
public class TokenizedRoute : Route
{
public TokenizedRoute(string url, IRouteHandler routeHandler) : base(url, routeHandler)
{
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
string tokenValue = "your token value";
values.Add("AUTHID", tokenValue);
return base.GetVirtualPath(requestContext, values);
}
}
See my blog post for more details.
You could use a jQuery solution to append a token to the query string of all links:
$("a").each(function (index, link)
{
$(link).attr("href", $(link).attr("href") + "?AUTHID=" + token);
});
But I agree with dknaack, I would say you should reconsider your authentication logic if at all possible.
You can save the AuthId in the Session object and create a custom Authorize Attribute.
Attribute
public class CustomAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// your custom logic depending on Session["AuthId"]
return httpContext.Session["AuthId"] != null;
}
}
Controller
public class MyController : Controller
{
[CustomAuthorize]
public ActionResult MyActionMethod()
{
return View();
}
}
hope this helps

Can I use HttpHandler to fake the existence of aspx pages?

I am building a web site with ASP.NET 3.5, and most of the site structure is static enough to create a folder structure and aspx pages. However, the site administrators want the ability to add new pages to different sections of the site through a web interface and using a WYSIWYG editor. I am using nested master pages to give the different sections of the site their own menus. What I would like to do is have a generic page under each section of the site that uses the appropriate master page and has a place holder for content that could be loaded from a database. I would also like these "fake" pages to have a url like any other aspx page, as if they had corresponding files on the server. So rather than have my url be:
http://mysite.com/subsection/gerenicconent.aspx?contentid=1234
it would be something like:
http://mysite.com/subsection/somethingmeaningful.aspx
The problem is that somethingmeaningful.aspx does not exist, because the administrator created it through the web UI, and the content is stored in the database. What I'm thinking is that I'll implement an HTTP handler that handles requests for aspx files. In that handler, I'll check to see if the URL that was requested is an actual file or one of my "fake pages". If it is a request for a fake page, I'll re-route the request to the generic content page for the appropriate section, change the query string to request the appropriate data from the database, and rewrite the URL so that it looks to the user as if the fake page really exists. The problem I'm having right now is that I can't figure out how to route the request to the default handler for aspx pages. I tried to instantiate a PageHandlerFactory, but the constuctor is protected internal. Is there any way for me to tell my HttpHandler to call the HttpHandler that would normal be used to process a request? My handler code currently looks like this:
using System.Web;
using System.Web.UI;
namespace HandlerTest
{
public class FakePageHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
if(RequestIsForFakedPage(context))
{
// reroute the request to the generic page and rewrite the URL
PageHandlerFactory factory = new PageHandlerFactory(); // this won't compile because the constructor is protected internal
factory.GetHandler(context, context.Request.RequestType, GetGenericContentPath(context), GetPhysicalApplicationPath(context)).ProcessRequest(context);
}
else
{
// route the request to the default handler for aspx pages
PageHandlerFactory factory = new PageHandlerFactory();
factory.GetHandler(context, context.Request.RequestType, context.Request.Path, context.Request.PhysicalPath).ProcessRequest(context);
}
}
public string RequestForPageIsFaked(HttpContext context)
{
// TODO
}
public string GetGenericContentPath(HttpContext context)
{
// TODO
}
public string GetPhysicalApplicationPath(HttpContext context)
{
// TODO
}
}
}
I still have some work to do to determine if the request is for a real page, and I haven't rewritten any URLs yet, but is something like this possible? Is there another way to create a PageHandlerFactory other than calling its constructor? Is there any way I can route the request up to the "normal" HttpHandler for an aspx page? I'd basically be saying "process this ASPX request as you normally would."
If you are using 3.5, look into using asp.net routing.
http://msdn.microsoft.com/en-us/library/cc668201.aspx
You would be better off using an http module for this, as in this case you can use the RewritePath method to route the request for fake pages, and do nothing for actual pages which will allow them to be processed as normal.
There is a good explanation of this here which also covers the benefits of using IIS 7.0 if that is an option for you.
I've just pulled this off a similar system we've just written.
This method takes care of physical pages and "fake" pages. You'll be able to ascertan how this fits with your fake page schema, I'm sure.
public class AspxHttpHandler : IHttpHandlerFactory
{
#region ~ from IHttpHandlerFactory ~
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
string url=context.Request.Url.AbsolutePath;
string[] portions = url.Split(new char[] { '/', '\\' });
// gives you the path, i presume this will help you identify the section and page
string serverSidePage=Path.Combine(context.Server.MapPath("~"),url);
if (File.Exists(serverSidePage))
{
// page is real
string virtualPath = context.Request.Url.AbsolutePath;
string inputFile = context.Server.MapPath(virtualPath);
try
{
// if it's real, send in the details to the ASPX compiler
return PageParser.GetCompiledPageInstance(virtualPath, inputFile, context);
}
catch (Exception ex)
{
throw new ApplicationException("Failed to render physical page", ex);
}
}
else
{
// page is fake
// need to identify a page that exists which you can use to compile against
// here, it is CMSTaregtPage - it can use a Master
string inputFile = context.Server.MapPath("~/CMSTargetPage.aspx");
string virtualPath = "~/CMSTargetPage.aspx";
// you can also add things that the page can access vai the Context.Items collection
context.Items.Add("DataItem","123");
return PageParser.GetCompiledPageInstance(virtualPath, inputFile, context);
}
public void ReleaseHandler(IHttpHandler handler)
{
}

Resources