繁体   English   中英

Xamarin使用WEB API(CORS)

[英]Xamarin consuming WEB API (CORS)

我有一个受令牌保护的安全Web api,已启用了CORS,并且我们希望确保该API仅由有角度的APP和Xamarin App(android,ios,uwp)使用。

通常,使用CORS时,您会明确地说出哪个来源可以使用WEB API。 但是,xamarin应用程序不是来源(域名),因此如何在此处检查CORS?

如果您使用的是异步Web API,则可以在覆盖SendAsync时添加一个检查,这将强制API在允许请求通过您的实际代码之前验证请求。 这是一个模拟示例,展示了如何通过检查Xamarin移动应用程序中的自定义用户代理字符串来做到这一点。 您显然可以轻松地更改此设置,以检查请求中所有Xamarin应用程序专有的内容,例如另一个自定义标头等。

public class SecureMyApi : DelegatingHandler {
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
            // Extra security stop to verify mobile app should have access to API
            var httpRequest = HttpContext.Current.Request;

            if (!string.IsNullOrWhiteSpace(httpRequest.UserAgent) && (httpRequest.UserAgent.StartsWith(ConfigurationManager.AppSettings["MyCustomUserAgentString"])))
            {
                // Allow user to pass through
            }
            else
            {
                if (request.Method != HttpMethod.Get)
                {
                    return request.CreateErrorResponse(HttpStatusCode.BadRequest, "You do not have permission to access the requested endpoint.");
                }
            }

        return await base.SendAsync(request, cancellationToken);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM