Beispiel #1
0
        public HttpResponseMessage OAuthRequestToken()
        {
            var identity = KmsIdentity.GetCurrentPrincipalIdentity();

            // --- Evitar doble Login ---
            if (identity.IsAuthenticated)
            {
                throw new HttpAlreadyLoggedInException(
                          "100" + ControllerStrings.Warning100_CannotLoginAgain
                          );
            }

            // --- Generar nuevo Token OAuth ---
            Token token = new Token {
                ApiKey = OAuth.ConsumerKey,
                Guid   = Guid.NewGuid(),
                Secret = Guid.NewGuid(),

                CallbackUri
                    = OAuth.CallbackUri == null
                    ? "oob"
                    : OAuth.CallbackUri.AbsoluteUri,

                ExpirationDate = DateTime.UtcNow.AddMinutes(10)
            };

            Database.TokenStore.Add(token);
            Database.SaveChanges();

            // --- Preparar y devolver detalles de Token OAuth ---
            return(new HttpResponseMessage {
                RequestMessage
                    = Request,

                StatusCode
                    = HttpStatusCode.OK,
                Content
                    = new StringContent(
                          string.Format(
                              CultureInfo.InvariantCulture,

                              "oauth_token={0}"
                              + "&oauth_token_secret={1}"
                              + "&oauth_callback_confirmed={2}"
                              + "&x_token_expires={3}",

                              token.Guid.ToString("N"),
                              token.Secret.ToString("N"),
                              identity.OAuth.CallbackUri == null
                                ? "false"
                                : "true",
                              10 * 60
                              )
                          )
            });
        }
Beispiel #2
0
        public HttpResponseMessage DeleteToken()
        {
            var identity = KmsIdentity.GetCurrentPrincipalIdentity();
            var token    = identity.OAuth.Token;

            Database.TokenStore.Delete(token.Guid);
            Database.SaveChanges();

            return(new HttpResponseMessage(
                       HttpStatusCode.NoContent
                       ));
        }
Beispiel #3
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Database = (WorkUnit)HttpContext.Current.Items["Database"];

            #if !DEBUG
            // --- Validar que la peitición venga de HTTPS
            if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                HttpResponseMessage response
                    = new HttpResponseMessage(HttpStatusCode.Forbidden);

                response.Headers.TryAddWithoutValidation(
                    "Warning",
                    "000 " + MessageHandlerStrings.Warning000_HttpsRequired
                    );

                return(await response.NewHttpResponseTask());
            }
            #endif

            // --- Validar que no ésta URI no esté en lista de ByPass ---
            var comparableUri = request.RequestUri.AbsolutePath.TrimStart(
                new char[] {
                '/'
            });
            if (
                WebApiConfig.KmsOAuthConfig.BypassOAuthAbsoluteUris.Any(a =>
                                                                        a == comparableUri ||
                                                                        (
                                                                            a.EndsWith("*") &&
                                                                            comparableUri.StartsWith(a.Remove(a.Length - 1))
                                                                        )
                                                                        )
                )
            {
                // Crear Principal Anónimo y continuar ejecución
                new KmsPrincipal(new KmsIdentity()).SetAsCurrent();

                return(await base.SendAsync(
                           request,
                           cancellationToken
                           ));
            }

            // --- Validar que se recibió cabecera Authorization correctamente ---
            if (request.Headers.Authorization == null || request.Headers.Authorization.Scheme != "OAuth")
            {
                HttpResponseMessage response
                    = new HttpResponseMessage(HttpStatusCode.Unauthorized);

                response.Headers.TryAddWithoutValidation(
                    "Warning",
                    "101 " + MessageHandlerStrings.Warning101_AuthorizationNotFound
                    );

                response.Headers.TryAddWithoutValidation(
                    "WWW-Authenticate",
                    "OAuth realm=\"" + WebApiConfig.KmsOAuthConfig.ApiRealm + "\""
                    );

                return(await response.NewHttpResponseTask());
            }

            // --- Extraer información de OAuth de la cabecera Authorize ---
            var httpOAuth = HttpOAuthAuthorization.FromAuthenticationHeader(
                request.Headers.Authorization
                );

            var httpOAuthValidRequest = await httpOAuth.ValidateRequestAsync(request);

            if (httpOAuthValidRequest)
            {
                // Actualizar LastUseDate de Token
                if (httpOAuth.Token != null && httpOAuth.Token.LastUseDate < DateTime.UtcNow.AddMinutes(-1))
                {
                    httpOAuth.Token.IPAddress = request.GetClientIpAddress();
                    Database.TokenStore.Update(httpOAuth.Token);
                }
            }
            else
            {
                HttpResponseMessage response
                    = new HttpResponseMessage(HttpStatusCode.Unauthorized);

                response.Headers.TryAddWithoutValidation(
                    "Warning",
                    "100 " + MessageHandlerStrings.Warning100_OAuthAuthorizationInvalid
                    );

                response.Headers.TryAddWithoutValidation(
                    "WWW-Authenticate",
                    "OAuth realm=\"" + WebApiConfig.KmsOAuthConfig.ApiRealm + "\""
                    );

                return(await response.NewHttpResponseTask());
            }

            // --- Establecer contexto de seguridad ---
            var identity = new KmsIdentity(httpOAuth);
            new KmsPrincipal(identity).SetAsCurrent();

            // --- Continuar con la ejecución ---
            return(await base.SendAsync(
                       request,
                       cancellationToken
                       ));
        }