Пример #1
0
        public async Task<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,
                    };

                    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 = await client.PostAsync(Config.AuthzServer.TokenEndpoint,
                                                new FormUrlEncodedContent(tokenRequest.ToPairs()));

                    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 = await resp.Content.ReadAsAsync<TokenResponse>();
                    if (!tokenResp.token_type.Equals("Bearer", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return Error("Unfortunately, the returned token type is unknown, ending");
                    }

                    if (string.IsNullOrEmpty(tokenResp.id_token))
                    {
                        return Error("Unfortunately, the token response does not contain an id_token, ending");
                    }

                    Log.Info("Excelent, we have an id_token {0}. Lets show it ...", tokenResp.id_token);

                    var idToken = new JwtSecurityToken(tokenResp.id_token);
                    Log.Info("--- BEGIN ID TOKEN JWT PAYLOAD ---");
                    foreach (var pair in idToken.Payload)
                    {
                        Log.Info("{0}:{1}",pair.Key, pair.Value);
                    }
                    Log.Info("--- END ID TOKEN JWT PAYLOAD ---");

                    Log.Warn("We really should validate the id token");

                    var theAccessToken = tokenResp.access_token;

                    Log.Info("Great, we have an access token {0}. Lets use it ...",
                             theAccessToken);
                    var resourceClient = new HttpClient();
                    Log.Info("First, get the UserInfo...");
                    var request = new HttpRequestMessage(HttpMethod.Get, Config.AuthzServer.UserInfo);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", theAccessToken);
                    var userInfoResp = await resourceClient.SendAsync(request);
                    if (userInfoResp.StatusCode != HttpStatusCode.OK)
                    {
                        return Error("Unfortunately, the UserInfo return should be OK but is {0}, ending", userInfoResp.StatusCode);
                    }
                    if (userInfoResp.Content.Headers.ContentType.MediaType != "application/json")
                    {
                        return Error("Unfortunately, the UserInfo representation should be 'application/json' but is {0}, ending", userInfoResp.Content.Headers.ContentType.MediaType);
                    }
                    var userInfo = await userInfoResp.Content.ReadAsAsync<JObject>();
                    Log.Info("--- BEGIN UserInfo ---");
                    Log.Info("{0}",userInfo);
                    Log.Info("--- END UserInfo ---");
                            
                    //Log.Info("Returning the resource server response, I hope you liked this demo ...");
                    //return Request.CreateResponse(HttpStatusCode.OK, userInfo);
                    
                    
                    Log.Info("Great, lets use the access token to GET the protected resource representation",
                             theAccessToken);
                    request = new HttpRequestMessage(HttpMethod.Get, Config.ExampleResource.Uri);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", theAccessToken);
                    var resourceResp = resourceClient.SendAsync(request).Result;
                    var resourceRespCont = resourceResp.Content.ReadAsAsync<JObject>();
                    Log.Info("Returning the resource server response, I hope you liked this demo ...");
                    return Request.CreateResponse(HttpStatusCode.OK, resourceRespCont);
                }
            }
            catch (Exception e)
            {
                return Error("An expected exception just happened, sorry: {0}", e.Message);
            }
        }