简体   繁体   English

Xamarin使用WEB API(CORS)

[英]Xamarin consuming WEB API (CORS)

I have a secure web api protected with token, we have it CORS enabled, and we want to be sure that the API is only consumed by an angular APP and also by the Xamarin App (android, ios, uwp). 我有一个受令牌保护的安全Web api,已启用了CORS,并且我们希望确保该API仅由有角度的APP和Xamarin App(android,ios,uwp)使用。

Normally with CORS you explicitly say which origin can consume the WEB API. 通常,使用CORS时,您会明确地说出哪个来源可以使用WEB API。 However the xamarin apps are not an origin(domain name), so how can I check CORS here? 但是,xamarin应用程序不是来源(域名),因此如何在此处检查CORS?

If you are using Async Web API then you could just add a check when overriding SendAsync which will force the API to validate the request before allowing it through to your actual code. 如果您使用的是异步Web API,则可以在覆盖SendAsync时添加一个检查,这将强制API在允许请求通过您的实际代码之前验证请求。 Here is a mock example of how, showing how to do this by checking for a custom user agent string coming form your Xamarin mobile app. 这是一个模拟示例,展示了如何通过检查Xamarin移动应用程序中的自定义用户代理字符串来做到这一点。 You could obviously easily change this to check something else proprietary about your Xamarin app all that comes in the request such as another custom header etc. 您显然可以轻松地更改此设置,以检查请求中所有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