/// <summary>
        /// Handles the AuthenticateRequest event of the HttpApplication.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void context_AuthenticateRequest(object sender, EventArgs e)
        {
            // Don't read OAuth messages directed at the OAuth controller or else we'll fail nonce checks.
            if (this.IsOAuthControllerRequest())
            {
                return;
            }

            using (var crypto = OAuthResourceServer.CreateRSA()) {
                var tokenAnalyzer  = new SpecialAccessTokenAnalyzer(crypto, crypto);
                var resourceServer = new ResourceServer(tokenAnalyzer);
                var context        = this.application.Context;
                Task.Run(
                    async delegate {
                    ProtocolFaultResponseException exception = null;
                    try {
                        IPrincipal principal = await resourceServer.GetPrincipalAsync(new HttpRequestWrapper(context.Request));
                        context.User         = principal;
                        return;
                    } catch (ProtocolFaultResponseException ex) {
                        exception = ex;
                    }

                    var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
                    await errorResponse.SendAsync();
                }).Wait();
            }
        }
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            if (!base.CheckAccessCore(operationContext))
            {
                return(false);
            }

            var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            var requestUri  = operationContext.RequestContext.RequestMessage.Properties.Via;

            return(Task.Run(
                       async delegate {
                using (var crypto = OAuthResourceServer.CreateRSA()) {
                    var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto);
                    var resourceServer = new ResourceServer(tokenAnalyzer);
                    ProtocolFaultResponseException exception = null;
                    try {
                        IPrincipal principal =
                            await resourceServer.GetPrincipalAsync(httpDetails, requestUri, CancellationToken.None, operationContext.IncomingMessageHeaders.Action);
                        var policy = new OAuthPrincipalAuthorizationPolicy(principal);
                        var policies = new List <IAuthorizationPolicy> {
                            policy,
                        };

                        var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
                        if (operationContext.IncomingMessageProperties.Security != null)
                        {
                            operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
                        }
                        else
                        {
                            operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
                                ServiceSecurityContext = securityContext,
                            };
                        }

                        securityContext.AuthorizationContext.Properties["Identities"] = new List <IIdentity> {
                            principal.Identity,
                        };

                        return true;
                    } catch (ProtocolFaultResponseException ex) {
                        // Return the appropriate unauthorized response to the client.
                        exception = ex;
                    } catch (DotNetOpenAuth.Messaging.ProtocolException /* ex*/) {
                        ////Logger.Error("Error processing OAuth messages.", ex);
                    }

                    var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
                    await errorResponse.SendAsync();
                }

                return false;
            }).Result);
        }
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            if (!base.CheckAccessCore(operationContext))
            {
                return(false);
            }

            var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            var requestUri  = operationContext.RequestContext.RequestMessage.Properties.Via;

            return(Task.Run(async delegate {
                ProtocolFaultResponseException exception = null;
                try {
                    var principal = await VerifyOAuth2Async(
                        httpDetails,
                        requestUri,
                        operationContext.IncomingMessageHeaders.Action ?? operationContext.IncomingMessageHeaders.To.AbsolutePath);
                    if (principal != null)
                    {
                        var policy = new OAuthPrincipalAuthorizationPolicy(principal);
                        var policies = new List <IAuthorizationPolicy> {
                            policy,
                        };

                        var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
                        if (operationContext.IncomingMessageProperties.Security != null)
                        {
                            operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
                        }
                        else
                        {
                            operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
                                ServiceSecurityContext = securityContext,
                            };
                        }

                        securityContext.AuthorizationContext.Properties["Identities"] = new List <IIdentity> {
                            principal.Identity,
                        };

                        return true;
                    }
                    else
                    {
                        return false;
                    }
                } catch (ProtocolFaultResponseException ex) {
                    Global.Logger.Error("Error processing OAuth messages.", ex);
                    exception = ex;
                } catch (ProtocolException ex) {
                    Global.Logger.Error("Error processing OAuth messages.", ex);
                }

                if (exception != null)
                {
                    // Return the appropriate unauthorized response to the client.
                    var outgoingResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
                    this.Respond(WebOperationContext.Current.OutgoingResponse, outgoingResponse);
                }

                return false;
            }).GetAwaiter().GetResult());
        }
Example #4
0
        private static void HandleOAuth2Exception(IHttpRequest req, IHttpResponse res, ProtocolFaultResponseException ex)
        {
            var response = ex.CreateErrorResponse();

            if (ex.ErrorResponseMessage is UnauthorizedResponse)
            {
                var oauth2Error = ex.ErrorResponseMessage as UnauthorizedResponse;
                response.Body = JsonSerializer.SerializeToString(oauth2Error.ToOAuth2JsonResponse());
                response.Headers[HttpResponseHeader.ContentType] = "application/json";
            }
            var context = ((HttpRequest)req.OriginalRequest).RequestContext.HttpContext;

            response.Respond(context);
            res.EndRequest();
        }
        protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext, ProtocolFaultResponseException ex)
        {
            var response = ex.CreateErrorResponse();
            UnauthorizedResponse error = ex.ErrorResponseMessage as UnauthorizedResponse;

            if (error != null)
            {
                response.Body = JsonConvert.SerializeObject(error.ToGameApiUnauthorizedErrorResponse());
                response.Headers[System.Net.HttpResponseHeader.ContentType] = "application/json";
            }
            HttpContext context = actionContext.Request.GetHttpContext();

            response.Respond(context);

            // these two lines to ensure IIS doesn't mess with our response body
            context.Response.TrySkipIisCustomErrors = true;
            context.Response.Status = context.Response.Status;

            context.Response.End();
        }