public HttpResponseMessage Get([FromUri] AuthorizationResponse authzResponse)
        {
            Log.Info("Great, just received the response from the Authorization Endpoint, lets look at it...");
            try
            {
                if (!string.IsNullOrEmpty(authzResponse.error))
                {
                    return Error("Unfortunately the request was not sucessfull. The returned error is {0}, ending",
                                 authzResponse.error);
                }
                Log.Info("Good, the request was sucessfull. Lets see if the returned state matches the sent state...");

                if (authzResponse.state != Db.State)
                {
                    return Error("Hum, the returned state does not match the send state. Ignoring the response, sorry.");
                }

                Log.Info(
                    "Nice, the state matches. Lets now exchange the code for an access token using the token endpoint ...");
                using (var client = new HttpClient())
                {
                    var tokenRequest = new TokenRequest
                                           {
                                               code = authzResponse.code,
                                               grant_type = "authorization_code",
                                               redirect_uri = Config.Client.redirect_uri,
                                           };

                    // Just because GitHub requires it (but the OAuth 2.0 RFC does not)
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    if (Config.AuthzServer.UseAuthorizationHeader)
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                            Convert.ToBase64String(
                                Encoding.ASCII.GetBytes(Config.Client.client_id + ":" + Config.Client.client_secret)));
                    }
                    else
                    {
                        tokenRequest.client_id = Config.Client.client_id;
                        tokenRequest.client_secret = Config.Client.client_secret;
                    }

                    var resp = client.PostAsync(Config.AuthzServer.TokenEndpoint,
                                                new FormUrlEncodedContent(tokenRequest.ToPairs())).Result;

                    if (resp.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        return Error("Apparently we broke the authorization server, ending.");
                    }
                    if (resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        return Error("Something is missing, ending.");
                    }
                    if (resp.StatusCode == HttpStatusCode.BadRequest)
                    {
                        return Error("The token endpoint refused to return an acess token, ending.");
                    }
                    if (resp.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        return Error("The token endpoint did't accepted our client credentials, ending.");
                    }
                    if (resp.Content.Headers.ContentType.MediaType != "application/json")
                    {
                        return
                            Error(
                                "Expection 'application/json' from the token endpoint, however it returned '{0}', ending.",
                                resp.Content.Headers.ContentType.MediaType);
                    }

                    var tokenResp = resp.Content.ReadAsAsync<TokenResponse>().Result;
                    if (!tokenResp.token_type.Equals("Bearer", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return Error("Unfortunately, the returned token type is unknown, ending");
                    }
                    var theAccessToken = tokenResp.access_token;
                    Log.Info("Great, we have an access token {0}. Lets use it to GET the resource representation",
                             theAccessToken);
                    using (var resourceClient = new HttpClient())
                    {
                        var request = new HttpRequestMessage(HttpMethod.Get, Config.ExampleResource.Uri);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", theAccessToken);
                        request.Headers.UserAgent.Add(new ProductInfoHeaderValue("OAuth2DemosAuthzCodeGrant","1.0"));
                        var resourceResp = resourceClient.SendAsync(request).Result;
                        Log.Info("Returning the resource server response, I hope you liked this demo ...");
                        return resourceResp;
                    }
                }
            }
            catch (Exception e)
            {
                return Error("An unexpected exception just happened, sorry: {0}", e.Message);
            }
        }
Beispiel #2
0
        public HttpResponseMessage Get([FromUri] AuthorizationResponse authzResponse)
        {
            Log.Info("Great, just received the response from the Authorization Endpoint, lets look at it...");
            try
            {
                if (!string.IsNullOrEmpty(authzResponse.error))
                {
                    return(Error("Unfortunately the request was not sucessfull. The returned error is {0}, ending",
                                 authzResponse.error));
                }
                Log.Info("Good, the request was sucessfull. Lets see if the returned state matches the sent state...");

                if (authzResponse.state != Db.State)
                {
                    return(Error("Hum, the returned state does not match the send state. Ignoring the response, sorry."));
                }

                Log.Info(
                    "Nice, the state matches. Lets now exchange the code for an access token using the token endpoint ...");
                using (var client = new HttpClient())
                {
                    var tokenRequest = new TokenRequest
                    {
                        code         = authzResponse.code,
                        grant_type   = "authorization_code",
                        redirect_uri = Config.Client.redirect_uri,
                    };

                    // Just because GitHub requires it (but the OAuth 2.0 RFC does not)
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    if (Config.AuthzServer.UseAuthorizationHeader)
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                                   Convert.ToBase64String(
                                                                                                       Encoding.ASCII.GetBytes(Config.Client.client_id + ":" + Config.Client.client_secret)));
                    }
                    else
                    {
                        tokenRequest.client_id     = Config.Client.client_id;
                        tokenRequest.client_secret = Config.Client.client_secret;
                    }

                    var resp = client.PostAsync(Config.AuthzServer.TokenEndpoint,
                                                new FormUrlEncodedContent(tokenRequest.ToPairs())).Result;

                    if (resp.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        return(Error("Apparently we broke the authorization server, ending."));
                    }
                    if (resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        return(Error("Something is missing, ending."));
                    }
                    if (resp.StatusCode == HttpStatusCode.BadRequest)
                    {
                        return(Error("The token endpoint refused to return an acess token, ending."));
                    }
                    if (resp.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        return(Error("The token endpoint did't accepted our client credentials, ending."));
                    }
                    if (resp.Content.Headers.ContentType.MediaType != "application/json")
                    {
                        return
                            (Error(
                                 "Expection 'application/json' from the token endpoint, however it returned '{0}', ending.",
                                 resp.Content.Headers.ContentType.MediaType));
                    }

                    var tokenResp = resp.Content.ReadAsAsync <TokenResponse>().Result;
                    if (!tokenResp.token_type.Equals("Bearer", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(Error("Unfortunately, the returned token type is unknown, ending"));
                    }
                    var theAccessToken = tokenResp.access_token;
                    Log.Info("Great, we have an access token {0}. Lets use it to GET the resource representation",
                             theAccessToken);
                    using (var resourceClient = new HttpClient())
                    {
                        var request = new HttpRequestMessage(HttpMethod.Get, Config.ExampleResource.Uri);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", theAccessToken);
                        request.Headers.UserAgent.Add(new ProductInfoHeaderValue("OAuth2DemosAuthzCodeGrant", "1.0"));
                        var resourceResp = resourceClient.SendAsync(request).Result;
                        Log.Info("Returning the resource server response, I hope you liked this demo ...");
                        return(resourceResp);
                    }
                }
            }
            catch (Exception e)
            {
                return(Error("An unexpected exception just happened, sorry: {0}", e.Message));
            }
        }