Beispiel #1
0
        private IHttpResult RequestAccessToken(IServiceBase authService, IAuthSession session, string code, IAuthTokens tokens)
        {
            try
            {
                var formData = "client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code&resource={4}"
                               .Fmt(ClientId.UrlEncode(), CallbackUrl.UrlEncode(), ClientSecret.UrlEncode(), code, ResourceId.UrlEncode());
                // Endpoint only accepts posts requests
                var contents = AccessTokenUrl.PostToUrl(formData);

                // 4. The Azure AD token issuance endpoint returns an access token
                //    and a refresh token. The refresh token can be used to request
                //    additional access tokens.

                // Response is JSON
                var authInfo    = JsonObject.Parse(contents);
                var authInfoNvc = authInfo.ToNameValueCollection();
                if (HasError(authInfoNvc))
                {
                    return(RedirectDueToFailure(authService, session, authInfoNvc));
                }
                tokens.AccessTokenSecret = authInfo["access_token"];
                tokens.RefreshToken      = authInfo["refresh_token"];
                return(OnAuthenticated(authService, session, tokens, authInfo.ToDictionary())
                       ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access!
            }
            catch (WebException webException)
            {
                if (webException.Response == null)
                {
                    // This could happen e.g. due to a timeout
                    return(RedirectDueToFailure(authService, session, new NameValueCollection
                    {
                        { "error", webException.GetType().ToString() },
                        { "error_description", webException.Message }
                    }));
                }
                Log.Error("Auth Failure", webException);
                var response     = ((HttpWebResponse)webException.Response);
                var responseText = Encoding.UTF8.GetString(
                    response.GetResponseStream().ReadFully());
                var errorInfo = JsonObject.Parse(responseText).ToNameValueCollection();
                return(RedirectDueToFailure(authService, session, errorInfo));
            }
            //return RedirectDueToFailure(authService, session, new NameValueCollection());
        }