验证查询字符串参数以授权ASP.NET核心请求的正确方法
Shopify允许将页面嵌入管理站点,为此,我可以使用ASP.NET MVC创建一个页面,并在Shopify的管理面板中显示该页面 要验证页面请求是否有效以及是否是Shopify请求的,在处理请求和呈现页面之前,页面必须验证查询字符串中发送的一些参数 Shopify发送一个hmac参数,以便我可以计算相同的参数并验证两者是否相等 我以前使用的是Asp.Net Mvc 5并使用了验证查询字符串参数以授权ASP.NET核心请求的正确方法,asp.net,asp.net-mvc,asp.net-core,shopify,asp.net-authorization,Asp.net,Asp.net Mvc,Asp.net Core,Shopify,Asp.net Authorization,Shopify允许将页面嵌入管理站点,为此,我可以使用ASP.NET MVC创建一个页面,并在Shopify的管理面板中显示该页面 要验证页面请求是否有效以及是否是Shopify请求的,在处理请求和呈现页面之前,页面必须验证查询字符串中发送的一些参数 Shopify发送一个hmac参数,以便我可以计算相同的参数并验证两者是否相等 我以前使用的是Asp.Net Mvc 5并使用了AuthorizeAttribute类,但现在我使用的是Asp.Net Core,似乎授权过滤器已经更改 我读过一些关于
AuthorizeAttribute
类,但现在我使用的是Asp.Net Core,似乎授权过滤器已经更改
我读过一些关于Asp.NETCore中新授权系统的文章,但我不能确定最好的方法是什么
所以最后我需要:
创建自定义属性,以便将其添加到控制器中。当Shopify调用我的页面时,我需要在控制器操作开始处理请求之前验证查询字符串参数,如果请求无效,则不会调用控制器操作,但如果请求有效,则会授权并让控制器操作执行和呈现页面
我当前在Asp.Net MVC 5中使用的过滤器如下所示:
这是一个示例控制器:
namespace myshoppifyapp.Controllers
{
[嵌入式AppAuth]
公共类MyController:Controller
{
公共异步任务索引(字符串hmac、字符串商店、字符串签名、字符串时间戳、字符串协议)
{
//仅当请求是真实的且由Shopify发送时,才在此处执行操作
}
}
}
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)
{
}
}
}
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
}
}
}