簡單設定CORS with Owin(C#) 及有關Request Origin限制

  • 422
  • 0
  • C#
  • 2019-03-25

跨來源資源共用(Cross-Origin Resource Sharing (CORS)) with Owin in C#

跨來源資源共用(Cross-Origin Resource Sharing (CORS))

首先要了解一下這兩者所需用到的Class等
OAuthValidateClientAuthenticationContext
The Client ID and Secret (OAuth2)

1. 透過OAuthValidateClientAuthenticationContext取得當前連線的Client Information
OAuthGrantResourceOwnerCredentialsContext OAuthContext;
​if (!OAuthContext.TryGetBasicCredentials(out clientId, out clientSecret)) {
  OAuthContext.TryGetFormCredentials(out clientId, out clientSecret);
}

此時我們將於Request的Header中取得我們所需的資料
if (OAuthContext.Parameters.Any(x => x.Key.Equals("name"))) {
  OAuthContext.OwinContext.Set("as:name", context.Parameters.Where(x =>      x.Key.Equals("name")).First().Value[0]);
}

同時將這些稍後需用到的資料用Set的方法存於OwinContext中

2. 對得到的ClientId及ClientSecret與你的程式所保有的ClientId及ClientSecret進行驗證
當中的ClientSecret需進行解密(如:SHA256)等
如果驗證失敗,調用OAuthValidateClientAuthenticationContext.SetError(),輸入有關的Error Description
如果驗證成功,調用OAuthValidateClientAuthenticationContext.Validated()

3. 從Request Header中取得Request來源的Origin
OAuthContext.OwinContext.Request.Headers.Get("Origin");

然後在Response Header中加上
OAuthContext.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { '許可的Origin' });
OAuthContext.OwinContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });

另外,在Context中也會包著SSL Cert的資訊
object SSLCert; OAuthContext.OwinContext.Environment.TryGetValue("ssl.ClientCertificate", out SSLCert));