コード例 #1
0
        public void BuildJsonTest()
        {
            var message = new ErrorResponseBuilder()
                          .SetErrorCode(ErrorCode.InvalidClient)
                          .SetErrorDescription("Bad Client")
                          .SetErrorUri("http://error.com")
                          .SetLocation("http://mydomain.com")
                          .SetState("mystate")
                          .BuildJsonMessage();

            Assert.AreEqual(400, message.StatusCode);
            Assert.AreEqual("http://mydomain.com", message.LocationUri);
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.State + "\":\"mystate\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.Error + "\":\"" + ErrorCode.InvalidClient + "\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.ErrorUri + "\":\"http://error.com\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.ErrorDescription + "\":\"Bad Client\""));
            Assert.AreEqual(ContentType.Json, message.ContentType);

            var ex = new OAuthException(ErrorCode.InvalidClient, "Bad Client", "http://error.com", "mystate");

            message = new ErrorResponseBuilder(ex).SetLocation("http://mydomain.com").BuildJsonMessage();

            Assert.AreEqual(400, message.StatusCode);
            Assert.AreEqual("http://mydomain.com", message.LocationUri);
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.State + "\":\"mystate\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.Error + "\":\"" + ErrorCode.InvalidClient + "\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.ErrorUri + "\":\"http://error.com\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.ErrorDescription + "\":\"Bad Client\""));
            Assert.AreEqual(ContentType.Json, message.ContentType);
        }
コード例 #2
0
        /// <summary>
        /// Will attempt to wrap the exception, returning true if the exception was wrapped, or returning false if it was not (in which case
        /// the original exception should be thrown).
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="webException"></param>
        /// <param name="wrappedException">The wrapped exception (will be set to the webException, if this method returns <c>false</c></param>
        /// <returns><c>true</c>, if the authException should be throw, <c>false</c> if the wrapped web exception should be thrown</returns>
        public static bool TryWrapException(IOAuthContext requestContext, WebException webException, out Exception wrappedException)
        {
            try
            {
                string content = webException.Response.ReadToEnd();

                if (content.Contains(Parameters.OAuth_Problem))
                {
                    var report = new OAuthProblemReport(content);
                    wrappedException = new OAuthException(report.ProblemAdvice ?? report.Problem, webException)
                    {
                        Context = requestContext, Report = report
                    };
                }
                else
                {
                    wrappedException = new ParsedWebException(content, webException.Message, webException.GetBaseException(), webException.Status, webException.Response);
                }

                return(true);
            }
            catch
            {
                wrappedException = webException;
                return(false);
            }
        }
コード例 #3
0
        public void BuildBodyTest()
        {
            var message = new ErrorResponseBuilder()
                          .SetErrorCode(ErrorCode.InvalidClient)
                          .SetErrorDescription("Bad Client")
                          .SetErrorUri("http://error.com")
                          .SetLocation("http://mydomain.com")
                          .SetState("mystate")
                          .BuildBodyMessage();

            var expected = string.Format("{0}={1}&{2}={3}&{4}={5}&{6}={7}",
                                         OAuthTokens.Error, ErrorCode.InvalidClient,
                                         OAuthTokens.ErrorDescription, HttpUtility.UrlEncode("Bad Client"),
                                         OAuthTokens.ErrorUri, HttpUtility.UrlEncode("http://error.com"),
                                         OAuthTokens.State, "mystate");

            Assert.AreEqual(400, message.StatusCode);
            Assert.AreEqual(expected, message.Body);
            Assert.AreEqual(ContentType.FormEncoded, message.ContentType);

            var ex = new OAuthException(ErrorCode.InvalidClient, "Bad Client", "http://error.com", "mystate");

            message = new ErrorResponseBuilder(ex).SetLocation("http://mydomain.com").BuildBodyMessage();

            expected = string.Format("{0}={1}&{2}={3}&{4}={5}&{6}={7}",
                                     OAuthTokens.Error, ErrorCode.InvalidClient,
                                     OAuthTokens.ErrorDescription, HttpUtility.UrlEncode("Bad Client"),
                                     OAuthTokens.ErrorUri, HttpUtility.UrlEncode("http://error.com"),
                                     OAuthTokens.State, "mystate");
            Assert.AreEqual(400, message.StatusCode);
            Assert.AreEqual(expected, message.Body);
            Assert.AreEqual(ContentType.FormEncoded, message.ContentType);
        }
コード例 #4
0
        /// <summary>
        /// Will attempt to wrap the exception, returning true if the exception was wrapped, or returning false if it was not (in which case
        /// the original exception should be thrown).
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="webEx"></param>
        /// <param name="authException"></param>
        /// <returns><c>true</c>, if the authException should be throw, <c>false</c> if the original web exception should be thrown</returns>
        public static bool TryWrapException(IOAuthContext requestContext, WebException webEx, out OAuthException authException, Action <string> responseBodyAction)
        {
            try
            {
                string content = webEx.Response.ReadToEnd();

                if (responseBodyAction != null)
                {
                    responseBodyAction(content);
                }

                if (content.Contains(Parameters.OAuth_Problem))
                {
                    var report = new OAuthProblemReport(content);
                    authException = new OAuthException(report.ProblemAdvice ?? report.Problem, webEx)
                    {
                        Context = requestContext, Report = report
                    };
                    return(true);
                }
            }
            catch
            {
            }
            authException = new OAuthException();
            return(false);
        }
コード例 #5
0
        public void BuildJsonTest()
        {
            var message = new ErrorResponseBuilder()
                .SetErrorCode(ErrorCode.InvalidClient)
                .SetErrorDescription("Bad Client")
                .SetErrorUri("http://error.com")
                .SetLocation("http://mydomain.com")
                .SetState("mystate")
                .BuildJsonMessage();

            Assert.AreEqual(400, message.StatusCode);
            Assert.AreEqual("http://mydomain.com", message.LocationUri);
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.State + "\":\"mystate\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.Error + "\":\"" + ErrorCode.InvalidClient + "\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.ErrorUri + "\":\"http://error.com\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.ErrorDescription + "\":\"Bad Client\""));
            Assert.AreEqual(ContentType.Json, message.ContentType);

            var ex = new OAuthException(ErrorCode.InvalidClient, "Bad Client", "http://error.com", "mystate");
            message = new ErrorResponseBuilder(ex).SetLocation("http://mydomain.com").BuildJsonMessage();

            Assert.AreEqual(400, message.StatusCode);
            Assert.AreEqual("http://mydomain.com", message.LocationUri);
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.State + "\":\"mystate\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.Error + "\":\"" + ErrorCode.InvalidClient + "\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.ErrorUri + "\":\"http://error.com\""));
            Assert.IsTrue(message.Body.Contains("\"" + OAuthTokens.ErrorDescription + "\":\"Bad Client\""));
            Assert.AreEqual(ContentType.Json, message.ContentType);
        }
コード例 #6
0
 private static void ShowOAuthErrorDialog(OAuthException ex)
 {
     Debug.WriteLine($"Failed to fetch oauth credentials: {ex.Message}");
     UserPromptUtils.OkPrompt(
         String.Format(Resources.CloudExplorerGceFailedToGetOauthCredentialsMessage, CredentialsStore.Default.CurrentAccount.AccountName),
         Resources.CloudExplorerGceFailedToGetOauthCredentialsCaption);
 }
コード例 #7
0
        public void BuildBodyTest()
        {
            var message = new ErrorResponseBuilder()
                .SetErrorCode(ErrorCode.InvalidClient)
                .SetErrorDescription("Bad Client")
                .SetErrorUri("http://error.com")
                .SetLocation("http://mydomain.com")
                .SetState("mystate")
                .BuildBodyMessage();

            var expected = string.Format("{0}={1}&{2}={3}&{4}={5}&{6}={7}",
                OAuthTokens.Error, ErrorCode.InvalidClient,
                OAuthTokens.ErrorDescription, HttpUtility.UrlEncode("Bad Client"),
                OAuthTokens.ErrorUri, HttpUtility.UrlEncode("http://error.com"),
                OAuthTokens.State, "mystate");
            Assert.AreEqual(400, message.StatusCode);
            Assert.AreEqual(expected, message.Body);
            Assert.AreEqual(ContentType.FormEncoded, message.ContentType);

            var ex = new OAuthException(ErrorCode.InvalidClient, "Bad Client", "http://error.com", "mystate");
            message = new ErrorResponseBuilder(ex).SetLocation("http://mydomain.com").BuildBodyMessage();

            expected = string.Format("{0}={1}&{2}={3}&{4}={5}&{6}={7}",
                OAuthTokens.Error, ErrorCode.InvalidClient,
                OAuthTokens.ErrorDescription, HttpUtility.UrlEncode("Bad Client"),
                OAuthTokens.ErrorUri, HttpUtility.UrlEncode("http://error.com"),
                OAuthTokens.State, "mystate");
            Assert.AreEqual(400, message.StatusCode);
            Assert.AreEqual(expected, message.Body);
            Assert.AreEqual(ContentType.FormEncoded, message.ContentType);
        }
コード例 #8
0
        private async Task BuildErrorResponse(HandlerContext context, OAuthException ex, bool returnsJSON = false)
        {
            var redirectUri = context.Request.RequestData.GetRedirectUriFromAuthorizationRequest();
            var state       = context.Request.RequestData.GetStateFromAuthorizationRequest();
            var jObj        = new JObject
            {
                { ErrorResponseParameters.Error, ex.Code },
                { ErrorResponseParameters.ErrorDescription, ex.Message }
            };

            if (!string.IsNullOrWhiteSpace(state))
            {
                jObj.Add(ErrorResponseParameters.State, state);
            }
            if ((string.IsNullOrWhiteSpace(redirectUri) || !Uri.TryCreate(redirectUri, UriKind.Absolute, out Uri r)) || returnsJSON)
            {
                var payload = Encoding.UTF8.GetBytes(jObj.ToString());
                HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await HttpContext.Response.Body.WriteAsync(payload, 0, payload.Length);

                return;
            }

            var dic = jObj.ToEnumerable().ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            var redirectUrlAuthorizationResponse = new RedirectURLAuthorizationResponse(redirectUri, dic);

            _responseModeHandler.Handle(context.Request.RequestData, redirectUrlAuthorizationResponse, HttpContext);
        }
コード例 #9
0
        public RequestTokenModelValidator(IValidationResultProvider validationResultProvider,
                                          IStringLocalizer <RequestTokenModelValidator> localizer) : base(validationResultProvider, localizer)
        {
            CascadeMode = CascadeMode.Stop;

            var invalidRequest = OAuthException.InvalidRequest();

            RuleFor(request => request.GrantType).NotEmpty()
            .WithState(request => invalidRequest);

            When(request => request.GrantType == SecurityConsts.GrantTypes.Password, () =>
            {
                RuleFor(request => request.Username).NotEmpty()
                .WithState(request => invalidRequest);

                RuleFor(request => request.Password).NotEmpty()
                .WithState(request => invalidRequest);
            });

            When(request => request.GrantType == SecurityConsts.GrantTypes.RefreshToken, () =>
            {
                RuleFor(request => request.RefreshToken).NotEmpty()
                .WithState(request => invalidRequest);
            });
        }
コード例 #10
0
        public void Should_set_properties_when_creating_oauth_exception()
        {
            var dummyResponse = new Response(HttpStatusCode.BadRequest, "Test Body");
            var result        = new OAuthException(dummyResponse);

            Assert.That(result.ResponseBody, Is.EqualTo(dummyResponse.Body));
            Assert.That(result.StatusCode, Is.EqualTo(dummyResponse.StatusCode));
        }
コード例 #11
0
 public ErrorResponseBuilder(OAuthException exception)
 {
     SetStatusCode(400);
     DisableCache();
     SetErrorCode(exception.ErrorCode);
     SetErrorDescription(exception.ErrorDescription);
     SetErrorUri(exception.ErrorUri);
     SetState(exception.State);
 }
コード例 #12
0
 public ErrorResponseBuilder(OAuthException exception)
 {
     SetStatusCode(400);
     DisableCache();
     SetErrorCode(exception.ErrorCode);
     SetErrorDescription(exception.ErrorDescription);
     SetErrorUri(exception.ErrorUri);
     SetState(exception.State);
 }
コード例 #13
0
        public async Task <TokenResponseModel> ProvideTokenAsync(RequestTokenModel requestModel)
        {
            AppUserEntity entity = null;

            switch (requestModel.GrantType)
            {
            case SecurityConsts.GrantTypes.Password:
            {
                entity = await AuthenticateAsync(requestModel.Username, requestModel.Password);
            }
            break;

            case SecurityConsts.GrantTypes.RefreshToken:
            {
                var validResult = ValidateRefreshToken(requestModel.RefreshToken);

                entity = await _userManager.FindByIdAsync(validResult.IdentityName());
            }
            break;

            default:
            {
                throw OAuthException.UnsupportedGrantType(description: nameof(requestModel.GrantType));
            }
            }

            if (entity == null)
            {
                throw OAuthException.InvalidGrant();
            }

            var identity =
                await GetIdentityAsync(entity, JwtBearerDefaults.AuthenticationScheme);

            #region Handle scope
            if (requestModel.Scope != null)
            {
                // demo only, real scenario: validate requested scopes first --> ...
                var scopes = requestModel.Scope.Split(',')
                             .Select(scope => new Claim(SecurityConsts.ClaimTypes.AppScope, scope.Trim())).ToArray();

                identity.AddClaims(scopes);
            }
            #endregion

            var principal = new ClaimsPrincipal(identity);

            var tokenResponse = GenerateTokenResponse(principal);

            return(tokenResponse);
        }
コード例 #14
0
        static XElement GetHtmlFormattedErrorReport(OAuthException authEx)
        {
            // TODO: Review OAuth error reporting extension, I don't think it allows for html formatting of the error report.

            string reportAsHtmlDocument = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                          "<html xmlns=\"http://www.w3.org/1999/xhtml\" version=\"-//W3C//DTD XHTML 2.0//EN\" xml:lang=\"en\" " +
                                          "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
                                          "xsi:schemaLocation=\"http://www.w3.org/1999/xhtml http://www.w3.org/MarkUp/SCHEMA/xhtml2.xsd\">" +
                                          "<HEAD><TITLE>Request Error</TITLE></HEAD><BODY><DIV id=\"content\"><P class=\"heading1\"><B>" +
                                          HttpUtility.HtmlEncode(authEx.Report.ToString()) +
                                          "</B></P></DIV></BODY></html>";

            return(XElement.Load(new StringReader(reportAsHtmlDocument)));
        }
コード例 #15
0
        private ClaimsPrincipal ValidateRefreshToken(string tokenStr)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            try
            {
                SecurityToken secToken;

                return(tokenHandler.ValidateToken(tokenStr, SecurityConsts.DefaultTokenParameters, out secToken));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);

                throw OAuthException.InvalidGrant();
            }
        }
コード例 #16
0
        public void Should_round_trip_serialise_and_deserialise_exception()
        {
            var headers = new Dictionary <string, string>
            {
                { "Header1", "Header1Value" },
                { "Header2", "Header2Value" }
            };
            var response = new Response(HttpStatusCode.Forbidden, headers, "responseBody");

            var inputException = new OAuthException(response);

            var roundTripSerialiser = new RoundTripSerialiser();
            var outputException     = roundTripSerialiser.RoundTrip(inputException);

            Assert.That(outputException.Headers, Is.EqualTo(inputException.Headers));
            Assert.That(outputException.ResponseBody, Is.EqualTo(inputException.ResponseBody));
            Assert.That(outputException.StatusCode, Is.EqualTo(inputException.StatusCode));
            Assert.That(outputException.Message, Is.EqualTo(inputException.Message));
        }
コード例 #17
0
        private void MapProblemReport(OAuthException oauthException, AuthenticationException coreException)
        {
            if (oauthException.Report != null)
            {
                coreException.AcceptableVersionTo   = oauthException.Report.AcceptableVersionTo;
                coreException.AcceptableVersionFrom = oauthException.Report.AcceptableVersionFrom;
                coreException.ParametersRejected    = oauthException.Report.ParametersRejected;
                coreException.ParametersAbsent      = oauthException.Report.ParametersAbsent;
                coreException.ProblemAdvice         = oauthException.Report.ProblemAdvice;
                coreException.Problem = oauthException.Report.Problem;
                coreException.AcceptableTimeStampsTo   = oauthException.Report.AcceptableTimeStampsTo;
                coreException.AcceptableTimeStampsFrom = oauthException.Report.AcceptableTimeStampsFrom;
            }

            if (oauthException.Context != null)
            {
                coreException.RequestUri           = oauthException.Context.RawUri;
                coreException.AuthorizationHeaders = oauthException.Context.AuthorizationHeaderParameters.AllKeys.Select(k => k + ": " + oauthException.Context.AuthorizationHeaderParameters[k]);
            }
        }
コード例 #18
0
ファイル: Provider.cs プロジェクト: waffle-iron/nequeo
        /// <summary>
        /// Create a access token from the request.
        /// </summary>
        /// <param name="rawUri">A System.Uri object containing information regarding the URL of the current request.</param>
        /// <param name="queryString">The collection of HTTP query string variables.</param>
        /// <param name="form">The collection of form variables.</param>
        /// <param name="headers">The collection of HTTP headers.</param>
        /// <param name="cookies">The collection of cookies sent by the client.</param>
        /// <returns>The token if successful; else null.</returns>
        public string CreateAccessToken(Uri rawUri, NameValueCollection queryString,
                                        NameValueCollection form, NameValueCollection headers, HttpCookieCollection cookies)
        {
            try
            {
                // Make sure that all the passed parameters are valid.
                if (rawUri == null)
                {
                    throw new ArgumentNullException("rawUri");
                }
                if (queryString == null)
                {
                    throw new ArgumentNullException("queryString");
                }
                if (form == null)
                {
                    throw new ArgumentNullException("form");
                }
                if (headers == null)
                {
                    throw new ArgumentNullException("headers");
                }
                if (cookies == null)
                {
                    throw new ArgumentNullException("cookies");
                }

                // Make sure that all the maditory OAuth parameters
                // have been passed to the provider from the consumer
                OAuthProblemReport validate = new OAuthProblemReport(queryString);
                validate.ValidateAccessParametersAbsent(queryString);
                string validationError = validate.ToString();

                // If any of the maditory OAuth parameters are missing.
                if (!String.IsNullOrEmpty(validationError))
                {
                    throw new OAuthException(OAuthProblemParameters.ParameterAbsent, "Absent Parameters", new Exception(validationError));
                }

                // Create an assign each manditory parameter.
                IOAuthContext context = new OAuthContextProvider();
                context.RawUri                = rawUri;
                context.RequestMethod         = "GET";
                context.Headers               = headers;
                context.QueryParameters       = queryString;
                context.FormEncodedParameters = form;
                context.Token           = queryString[Parameters.OAuth_Token];
                context.Nonce           = queryString[Parameters.OAuth_Nonce];
                context.ConsumerKey     = queryString[Parameters.OAuth_Consumer_Key];
                context.SignatureMethod = queryString[Parameters.OAuth_Signature_Method];
                context.Timestamp       = queryString[Parameters.OAuth_Timestamp];
                context.Signature       = queryString[Parameters.OAuth_Signature];
                context.Verifier        = queryString[Parameters.OAuth_Verifier];

                // Assign each optional parameter
                GetOptionalAccessParameters(context, queryString);

                // Create the access token from the stores.
                IToken token = _oAuthProvider.ExchangeRequestTokenForAccessToken(context);
                return(UriUtility.FormatTokenForResponse(token));
            }
            catch (OAuthException aex)
            {
                // Get the current token errors.
                _tokenError = aex.Report.ToString();
                return(null);
            }
            catch (Exception ex)
            {
                // Transform the execption.
                OAuthException OAuthException =
                    new OAuthException(OAuthProblemParameters.ParameterRejected, ex.Message, ex);

                // Get the current token errors.
                _tokenError = OAuthException.Report.ToString();
                return(null);
            }
        }
コード例 #19
0
ファイル: Provider.cs プロジェクト: waffle-iron/nequeo
        /// <summary>
        /// Create a authorise token from the request.
        /// </summary>
        /// <param name="rawUri">A System.Uri object containing information regarding the URL of the current request.</param>
        /// <param name="queryString">The collection of HTTP query string variables.</param>
        /// <param name="form">The collection of form variables.</param>
        /// <param name="headers">The collection of HTTP headers.</param>
        /// <param name="cookies">The collection of cookies sent by the client.</param>
        /// <param name="isApprovedByUser">Has the user approved the client to access the resources.</param>
        /// <returns>The formatted redirect url; else null.</returns>
        public string CreateAuthoriseToken(Uri rawUri, NameValueCollection queryString,
                                           NameValueCollection form, NameValueCollection headers, HttpCookieCollection cookies, bool isApprovedByUser = false)
        {
            try
            {
                // Make sure that all the passed parameters are valid.
                if (rawUri == null)
                {
                    throw new ArgumentNullException("rawUri");
                }
                if (queryString == null)
                {
                    throw new ArgumentNullException("queryString");
                }
                if (form == null)
                {
                    throw new ArgumentNullException("form");
                }
                if (headers == null)
                {
                    throw new ArgumentNullException("headers");
                }
                if (cookies == null)
                {
                    throw new ArgumentNullException("cookies");
                }

                // Only process if the user has approved the request.
                if (isApprovedByUser)
                {
                    // Make sure that all the maditory OAuth parameters
                    // have been passed to the provider from the consumer
                    OAuthProblemReport validate = new OAuthProblemReport(queryString);
                    validate.ValidateAuthoriseParametersAbsent(queryString);
                    string validationError = validate.ToString();

                    // If any of the maditory OAuth parameters are missing.
                    if (!String.IsNullOrEmpty(validationError))
                    {
                        throw new OAuthException(OAuthProblemParameters.ParameterAbsent, "Absent Parameters", new Exception(validationError));
                    }

                    // Create an assign each manditory parameter.
                    IOAuthContext context = new OAuthContextProvider();
                    context.RawUri                = rawUri;
                    context.RequestMethod         = "GET";
                    context.Headers               = headers;
                    context.QueryParameters       = queryString;
                    context.FormEncodedParameters = form;
                    context.Token       = queryString[Parameters.OAuth_Token];
                    context.CallbackUrl = queryString[Parameters.OAuth_Callback];
                    string companyUniqueUserID = queryString[Parameters.Company_Unique_User_Identifier];

                    // Assign each optional parameter
                    GetOptionalAuthoriseParameters(context, queryString);

                    // Create a new OAuth provider.
                    _oAuthProvider = new OAuthProvider(_tokenStore,
                                                       new NonceStoreInspector(_nonceStore),
                                                       new TimestampRangeInspector(new TimeSpan(1, 0, 0)),
                                                       new ConsumerValidationInspector(_consumerStore),
                                                       new XAuthValidationInspector(ValidateXAuthMode, AuthenticateXAuthUsernameAndPassword));

                    // Create the access token from the stores, and create a new verification code.
                    string verifier = _consumerStore.SetVerificationCode(context, companyUniqueUserID);
                    IToken token    = _oAuthProvider.CreateAccessToken(context);

                    // Create the parameter response.
                    NameValueCollection parameters = new NameValueCollection();
                    parameters[Parameters.OAuth_Token]    = token.Token;
                    parameters[Parameters.OAuth_Verifier] = verifier;

                    // Return the token callback query string..
                    return(context.CallbackUrl + "?" + UriUtility.FormatQueryString(parameters));
                }
                else
                {
                    throw new OAuthException(OAuthProblemParameters.PermissionDenied, "Authorisation Denied", new Exception("User has denied access"));
                }
            }
            catch (OAuthException aex)
            {
                // Get the current token errors.
                _tokenError = aex.Report.ToString();
                return(null);
            }
            catch (Exception ex)
            {
                // Transform the execption.
                OAuthException OAuthException =
                    new OAuthException(OAuthProblemParameters.ParameterRejected, ex.Message, ex);

                // Get the current token errors.
                _tokenError = OAuthException.Report.ToString();
                return(null);
            }
        }
コード例 #20
0
 /// <summary>
 /// Creates an ActionResult for the error specified in a particular <see cref="OAuthException" />.
 /// </summary>
 /// <param name="exception"></param>
 public OAuthExceptionResult(OAuthException exception)
 {
     _exception = exception;
 }
コード例 #21
0
        private KiiUser CreateCurrentKiiUser(
            Dictionary <string, object> queryParameters)
        {
            string succeeded = (string)queryParameters["kii_succeeded"];

            if (succeeded == "false")
            {
                // server error. fail to login.
                SocialException exception = null;
                string          errorCode = (string)queryParameters["kii_error_code"];
                if ("UNAUTHORIZED" == errorCode)
                {
                    exception = new OAuthException(
                        "authorization credentials are rejected by provider");
                }
                else
                {
                    exception = new SocialException(
                        "login failed with error: " + errorCode);
                }
                throw exception;
            }

            if (succeeded != "true")
            {
                // server error. invalid response.
                throw new SocialException("unknown kii_succeed: " + succeeded);
            }

            KiiUser retval = KiiUser.CreateByUri(
                new Uri(Utils.Path("kiicloud://", "users", GetNotEmptyString(
                                       queryParameters, "kii_user_id"))));
            Dictionary <string, object> dictionary =
                new Dictionary <string, object>()
            {
                { KiiUser.SocialResultParams.PROVIDER_USER_ID,
                  GetNotEmptyString(queryParameters, "provider_user_id") },
                { KiiUser.SocialResultParams.PROVIDER, this.provider },
                { KiiUser.SocialResultParams.KII_NEW_USER,
                  queryParameters["kii_new_user"] }
            };

            // oauth_token and oauth_token_secret are optinal fields.
            if (queryParameters.ContainsKey("oauth_token"))
            {
                dictionary.Add(KiiUser.SocialResultParams.OAUTH_TOKEN,
                               queryParameters["oauth_token"]);
            }
            if (queryParameters.ContainsKey("oauth_token_secret"))
            {
                dictionary.Add(KiiUser.SocialResultParams.OAUTH_TOKEN_SECRET,
                               queryParameters["oauth_token_secret"]);
            }
            if (queryParameters.ContainsKey("kii_expires_in"))
            {
                dictionary.Add("kii_expires_in",
                               queryParameters["kii_expires_in"]);
            }
            if (queryParameters.ContainsKey("oauth_token_expires_in"))
            {
                dictionary.Add("oauth_token_expires_in",
                               queryParameters["oauth_token_expires_in"]);
            }
            _KiiInternalUtils.SetSocialAccessTokenDictionary(retval,
                                                             dictionary);

            _KiiInternalUtils.SetCurrentUser(retval);
            _KiiInternalUtils.UpdateAccessToken(GetNotEmptyString(
                                                    queryParameters, "kii_access_token"));

            return(retval);
        }
コード例 #22
0
        /// <summary>
        /// Verify that the request is valid.
        /// </summary>
        /// <param name="rawUri">A System.Uri object containing information regarding the URL of the current request.</param>
        /// <param name="queryString">The collection of HTTP query string variables.</param>
        /// <param name="form">The collection of form variables.</param>
        /// <param name="headers">The collection of HTTP headers.</param>
        /// <returns>The token if successful; else null.</returns>
        public bool VerifyAuthorisation(Uri rawUri, NameValueCollection queryString,
                                        NameValueCollection form, NameValueCollection headers)
        {
            try
            {
                // Make sure that all the passed parameters are valid.
                if (rawUri == null)
                {
                    throw new ArgumentNullException("rawUri");
                }
                if (queryString == null)
                {
                    throw new ArgumentNullException("queryString");
                }
                if (form == null)
                {
                    throw new ArgumentNullException("form");
                }
                if (headers == null)
                {
                    throw new ArgumentNullException("headers");
                }

                // Make sure that all the maditory OAuth parameters
                // have been passed to the provider from the consumer
                OAuthProblemReport validate = new OAuthProblemReport(queryString);
                validate.ValidateResourceParametersAbsent(queryString);
                string validationError = validate.ToString();

                // If any of the maditory OAuth parameters are missing.
                if (!String.IsNullOrEmpty(validationError))
                {
                    throw new OAuthException(OAuthProblemParameters.ParameterAbsent, "Absent Parameters", new Exception(validationError));
                }

                // Create an assign each manditory parameter.
                IOAuthContext context = new OAuthContextProvider();
                context.RawUri                = rawUri;
                context.RequestMethod         = "GET";
                context.Headers               = headers;
                context.QueryParameters       = queryString;
                context.FormEncodedParameters = form;
                context.Token       = queryString[Parameters.OAuth_Token];
                context.ConsumerKey = queryString[Parameters.OAuth_Consumer_Key];

                // Assign each optional parameter
                GetOptionalRequestParameters(context, queryString);

                // Access protected resource; throws exception if access rejected.
                _oAuthProvider.AccessProtectedResourceRequest(context);

                // Return true verify.
                return(true);
            }
            catch (OAuthException aex)
            {
                // Get the current token errors.
                _tokenError = aex.Report.ToString();
                return(false);
            }
            catch (Exception ex)
            {
                // Transform the execption.
                OAuthException OAuthException =
                    new OAuthException(OAuthProblemParameters.ParameterRejected, ex.Message, ex);

                // Get the current token errors.
                _tokenError = OAuthException.Report.ToString();
                return(false);
            }
        }
コード例 #23
0
        private KiiUser CreateCurrentKiiUser(
            Dictionary<string, object> queryParameters)
        {
            string succeeded = (string)queryParameters["kii_succeeded"];
            if (succeeded == "false")
            {
                // server error. fail to login.
                SocialException exception = null;
                string errorCode = (string)queryParameters["kii_error_code"];
                if ("UNAUTHORIZED" == errorCode)
                {
                    exception = new OAuthException(
                        "authorization credentials are rejected by provider");
                }
                else
                {
                    exception = new SocialException(
                        "login failed with error: " + errorCode);
                }
                throw exception;
            }

            if (succeeded != "true")
            {
                // server error. invalid response.
                throw new SocialException("unknown kii_succeed: " + succeeded);
            }

            KiiUser retval = KiiUser.CreateByUri(
                new Uri(Utils.Path("kiicloud://", "users", GetNotEmptyString(
                                    queryParameters, "kii_user_id"))));
            Dictionary<string, object> dictionary =
                new Dictionary<string, object>() {
                    { KiiUser.SocialResultParams.PROVIDER_USER_ID,
                      GetNotEmptyString(queryParameters, "provider_user_id")},
                    { KiiUser.SocialResultParams.PROVIDER, this.provider },
                    { KiiUser.SocialResultParams.KII_NEW_USER,
                      queryParameters["kii_new_user"] }
            };

            // oauth_token and oauth_token_secret are optinal fields.
            if (queryParameters.ContainsKey("oauth_token"))
            {
                dictionary.Add(KiiUser.SocialResultParams.OAUTH_TOKEN,
                        queryParameters["oauth_token"]);
            }
            if (queryParameters.ContainsKey("oauth_token_secret"))
            {
                dictionary.Add(KiiUser.SocialResultParams.OAUTH_TOKEN_SECRET,
                        queryParameters["oauth_token_secret"]);
            }
            if (queryParameters.ContainsKey("kii_expires_in"))
            {
                dictionary.Add("kii_expires_in",
                        queryParameters["kii_expires_in"]);
            }
            if (queryParameters.ContainsKey("oauth_token_expires_in")) {
                dictionary.Add("oauth_token_expires_in",
                    queryParameters["oauth_token_expires_in"]);
            }
            _KiiInternalUtils.SetSocialAccessTokenDictionary(retval,
                    dictionary);

            _KiiInternalUtils.SetCurrentUser(retval);
            _KiiInternalUtils.UpdateAccessToken(GetNotEmptyString(
                        queryParameters, "kii_access_token"));

            return retval;
        }