1: private static bool CheckAuthentication( NameValueCollection query )
2: {
3:
4: //### get data required for check_authentication
5: string mode = "check_authentication";
6: string handle = query["openid.assoc_handle"];
7: string signature = query["openid.sig"];
8: string signed = query["openid.signed"];
9: string extra = string.Empty;
10:
11: //### loop through fields required by "openid.signed" and retrieve that data
12: if( !string.IsNullOrEmpty(signed) )
13: {
14: string[] exemptions = { "mode", "assoc_handle", "sig", "signed" };
15: string[] fields = signed.Split(',');
16: foreach( string field in fields )
17: {
18: if( exemptions.Contains(field) ) continue;
19: extra += string.Format( "openid.{0}={1}&", field, HttpUtility.UrlEncode( query[ "openid." + field ] ) );
20: }
21: extra = "&" + extra.Substring( 0, extra.Length - 1 );
22: }
23:
24: //### combine all the data together to form the request
25: string post = string.Format( "openid.mode={0}&openid.assoc_handle={1}&openid.sig={2}&openid.signed={3}{4}",
26: mode,
27: HttpUtility.UrlEncode( handle ),
28: HttpUtility.UrlEncode( signature ),
29: HttpUtility.UrlEncode( signed ),
30: extra
31: );
32:
33: //### begin sending request
34: HttpWebRequest request = (HttpWebRequest)WebRequest.Create( query["openid.op_endpoint"] );
35: request.Method = "POST";
36: request.ContentType = "application/x-www-form-urlencoded";
37: request.ContentLength = post.Length;
38:
39: //### transmit POST data
40: using( StreamWriter sw = new StreamWriter(request.GetRequestStream()) )
41: sw.Write(post);
42:
43: //### get response
44: string html = "";
45: using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() )
46: using( StreamReader sr = new StreamReader( response.GetResponseStream() ) )
47: html = sr.ReadToEnd();
48:
49: //### determine if check_authentication passed or not
50: if( string.IsNullOrEmpty(html) || !html.StartsWith( "is_valid:" ) || html.StartsWith( "is_valid:false" ) )
51: return false;
52: else if( html.StartsWith( "is_valid:true" ) )
53: return true;
54: else
55: throw new InvalidOperationException( "Unexpected return from OpenID check_authentication." );
56:
57: }