//[HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
        public ActionResult Authorise()
        {
            var authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServerHost());
            var pendingRequest      = authorizationServer.ReadAuthorizationRequest();

            if (pendingRequest == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
            }
            var service          = ServiceFactory.GetOAuth2AuthService();
            var requestingClient = service.GetOAuthClient(pendingRequest.ClientIdentifier);

            // Consider auto-approving if safe to do so.
            if (((OAuth2AuthorizationServerHost)authorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest))
            {
                var approval = authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
                return(authorizationServer.Channel.PrepareResponse(approval).AsActionResultMvc5());
            }

            var model = new OAuthAccountAuthorizeViewModel
            {
                ClientApp            = requestingClient.Name,
                Scope                = pendingRequest.Scope,
                AuthorizationRequest = pendingRequest,
            };

            return(View(model));
        }
        public async Task <ActionResult> Respond(string request, bool approval)
        {
            var authServer  = new AuthorizationServer(new AuthorizationServerHost());
            var authRequest = await authServer.ReadAuthorizationRequestAsync(new Uri(request));

            IProtocolMessage responseMessage;

            if (approval)
            {
                var grantedResponse = authServer.PrepareApproveAuthorizationRequest(
                    authRequest, this.User.Identity.Name, authRequest.Scope);
                responseMessage = grantedResponse;
            }
            else
            {
                var rejectionResponse = authServer.PrepareRejectAuthorizationRequest(authRequest);
                rejectionResponse.Error = Protocol.EndUserAuthorizationRequestErrorCodes.AccessDenied;
                responseMessage         = rejectionResponse;
            }

            var response = await authServer.Channel.PrepareResponseAsync(responseMessage);

            Response.ContentType = response.Content.Headers.ContentType.ToString();
            return(response.AsActionResult());
        }
Esempio n. 3
0
        //[HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
        public ActionResult Authorise()
        {
            using (OAuth2AuthorizationServer server = (new OAuth2AuthorizationServer(new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToPfx"], ConfigurationManager.AppSettings["CertificatePassword"]),
                                                                                     new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToCertificate"]))))
            {
                AuthorizationServer authorizationServer = new AuthorizationServer(server);

                var pendingRequest = authorizationServer.ReadAuthorizationRequest();
                if (pendingRequest == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
                }

                var requestingClient = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);

                // Consider auto-approving if safe to do so.
                if (((OAuth2AuthorizationServer)authorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest))
                {
                    var approval = authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
                    return(authorizationServer.Channel.PrepareResponse(approval).AsActionResult());
                }

                var model = new AccountAuthorizeModel
                {
                    ClientApp            = requestingClient.Name,
                    Scope                = pendingRequest.Scope,
                    AuthorizationRequest = pendingRequest,
                };

                return(View(model));
            }
        }
Esempio n. 4
0
        public async Task DecodeRefreshToken()
        {
            var refreshTokenSource = new TaskCompletionSource <string>();

            Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
                async(req, ct) => {
                var server  = new AuthorizationServer(AuthorizationServerMock);
                var request = await server.ReadAuthorizationRequestAsync(req, ct);
                Assert.That(request, Is.Not.Null);
                var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
                return(await server.Channel.PrepareResponseAsync(response));
            });
            Handle(AuthorizationServerDescription.TokenEndpoint).By(
                async(req, ct) => {
                var server        = new AuthorizationServer(AuthorizationServerMock);
                var response      = await server.HandleTokenRequestAsync(req, ct);
                var authorization = server.DecodeRefreshToken(refreshTokenSource.Task.Result);
                Assert.That(authorization, Is.Not.Null);
                Assert.That(authorization.User, Is.EqualTo(ResourceOwnerUsername));
                return(response);
            });

            var client = new WebServerClient(AuthorizationServerDescription);

            try {
                var authState = new AuthorizationState(TestScopes)
                {
                    Callback = ClientCallback,
                };
                var authRedirectResponse = await client.PrepareRequestUserAuthorizationAsync(authState);

                this.HostFactories.CookieContainer.SetCookies(authRedirectResponse, ClientCallback);
                Uri authCompleteUri;
                using (var httpClient = this.HostFactories.CreateHttpClient()) {
                    using (var response = await httpClient.GetAsync(authRedirectResponse.Headers.Location)) {
                        response.EnsureSuccessStatusCode();
                        authCompleteUri = response.Headers.Location;
                    }
                }

                var authCompleteRequest = new HttpRequestMessage(HttpMethod.Get, authCompleteUri);
                this.HostFactories.CookieContainer.ApplyCookies(authCompleteRequest);
                var result = await client.ProcessUserAuthorizationAsync(authCompleteRequest);

                Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
                Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
                refreshTokenSource.SetResult(result.RefreshToken);
            } catch {
                refreshTokenSource.TrySetCanceled();
            }
        }
Esempio n. 5
0
        public async Task CreateAccessTokenSeesAuthorizingUserAuthorizationCodeGrant()
        {
            var authServerMock = CreateAuthorizationServerMock();

            authServerMock
            .Setup(a => a.IsAuthorizationValid(It.IsAny <IAuthorizationDescription>()))
            .Returns <IAuthorizationDescription>(req => {
                Assert.That(req.User, Is.EqualTo(ResourceOwnerUsername));
                return(true);
            });

            Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
                async(req, ct) => {
                var server  = new AuthorizationServer(authServerMock.Object);
                var request = await server.ReadAuthorizationRequestAsync(req, ct);
                Assert.That(request, Is.Not.Null);
                var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
                return(await server.Channel.PrepareResponseAsync(response));
            });
            Handle(AuthorizationServerDescription.TokenEndpoint).By(
                async(req, ct) => {
                var server = new AuthorizationServer(authServerMock.Object);
                return(await server.HandleTokenRequestAsync(req, ct));
            });

            var client    = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
            var authState = new AuthorizationState(TestScopes)
            {
                Callback = ClientCallback,
            };
            var authRedirectResponse = await client.PrepareRequestUserAuthorizationAsync(authState);

            this.HostFactories.CookieContainer.SetCookies(authRedirectResponse, ClientCallback);
            Uri authCompleteUri;

            this.HostFactories.AllowAutoRedirects = false;
            using (var httpClient = this.HostFactories.CreateHttpClient()) {
                using (var response = await httpClient.GetAsync(authRedirectResponse.Headers.Location)) {
                    Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redirect));
                    authCompleteUri = response.Headers.Location;
                }
            }

            var authCompleteRequest = new HttpRequestMessage(HttpMethod.Get, authCompleteUri);

            this.HostFactories.CookieContainer.ApplyCookies(authCompleteRequest);
            var result = await client.ProcessUserAuthorizationAsync(authCompleteRequest);

            Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
            Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
        }
Esempio n. 6
0
        public async Task <ActionResult> Authorize()
        {
            var pendingRequest = await _authorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);

            if (pendingRequest == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
            }

            var approval = _authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
            var response = await _authorizationServer.Channel.PrepareResponseAsync(approval, Response.ClientDisconnectedToken);

            Response.ContentType = response.Content.Headers.ContentType.ToString();
            FormsAuthentication.SignOut();
            return(response.AsActionResult());
        }
Esempio n. 7
0
        public async Task AuthorizationCodeGrant()
        {
            Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
                async(req, ct) => {
                var server  = new AuthorizationServer(AuthorizationServerMock);
                var request = await server.ReadAuthorizationRequestAsync(req, ct);
                Assert.That(request, Is.Not.Null);
                var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
                return(await server.Channel.PrepareResponseAsync(response, ct));
            });
            Handle(AuthorizationServerDescription.TokenEndpoint).By(
                async(req, ct) => {
                var server = new AuthorizationServer(AuthorizationServerMock);
                return(await server.HandleTokenRequestAsync(req, ct));
            });
            {
                var client    = new UserAgentClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
                var authState = new AuthorizationState(TestScopes)
                {
                    Callback = ClientCallback,
                };
                var request = client.PrepareRequestUserAuthorization(authState);
                Assert.AreEqual(EndUserAuthorizationResponseType.AuthorizationCode, request.ResponseType);
                var authRequestRedirect = await client.Channel.PrepareResponseAsync(request);

                Uri authRequestResponse;
                this.HostFactories.AllowAutoRedirects = false;
                using (var httpClient = this.HostFactories.CreateHttpClient()) {
                    using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) {
                        authRequestResponse = httpResponse.Headers.Location;
                    }
                }
                var incoming =
                    await
                    client.Channel.ReadFromRequestAsync(
                        new HttpRequestMessage(HttpMethod.Get, authRequestResponse), CancellationToken.None);

                var result = await client.ProcessUserAuthorizationAsync(authState, incoming, CancellationToken.None);

                Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
                Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
            }
        }
        public ActionResult AuthoriseResponse(bool isApproved)
        {
            var authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServerHost());
            var pendingRequest      = authorizationServer.ReadAuthorizationRequest();

            if (pendingRequest == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
            }

            IDirectedProtocolMessage response;

            if (isApproved)
            {
                // The authorization we file in our database lasts until the user explicitly revokes it.
                // You can cause the authorization to expire by setting the ExpirationDateUTC
                // property in the below created ClientAuthorization.
                var service = ServiceFactory.GetOAuth2AuthService();
                var client  = service.GetOAuthClient(pendingRequest.ClientIdentifier);
                var user    = service.GetOAuthUsers(HttpContext.User.Identity.Name);
                service.AddOAuthClientAuthor(new OAuthClientAuthor
                {
                    UserID    = user.ID,
                    ClientID  = client.ID,
                    Scope     = OAuthUtilities.JoinScopes(pendingRequest.Scope),
                    ExpireUtc = DateTime.Now.AddDays(1),
                    Time      = DateTime.Now,
                });
                // submit now so that this new row can be retrieved later in this same HTTP request

                // In this simple sample, the user either agrees to the entire scope requested by the client or none of it.
                // But in a real app, you could grant a reduced scope of access to the client by passing a scope parameter to this method.
                response = authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
            }
            else
            {
                response = authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
            }

            return(authorizationServer.Channel.PrepareResponse(response).AsActionResultMvc5());
        }
Esempio n. 9
0
        public ActionResult AuthoriseResponse(bool isApproved)
        {
            using (OAuth2AuthorizationServer server = (new OAuth2AuthorizationServer(new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToPfx"], ConfigurationManager.AppSettings["CertificatePassword"]),
                                                                                     new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToCertificate"]))))
            {
                AuthorizationServer authorizationServer = new AuthorizationServer(server);
                var pendingRequest = authorizationServer.ReadAuthorizationRequest();
                if (pendingRequest == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
                }

                IDirectedProtocolMessage response;
                if (isApproved)
                {
                    // The authorization we file in our database lasts until the user explicitly revokes it.
                    // You can cause the authorization to expire by setting the ExpirationDateUTC
                    // property in the below created ClientAuthorization.
                    var client = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
                    client.ClientAuthorizations.Add(
                        new ClientAuthorization
                    {
                        Scope        = OAuthUtilities.JoinScopes(pendingRequest.Scope),
                        User         = MvcApplication.DataContext.Users.FirstOrDefault(u => u.Username == System.Web.HttpContext.Current.User.Identity.Name),
                        CreatedOnUtc = DateTime.UtcNow,
                    });
                    MvcApplication.DataContext.SaveChanges(); // submit now so that this new row can be retrieved later in this same HTTP request

                    // In this simple sample, the user either agrees to the entire scope requested by the client or none of it.
                    // But in a real app, you could grant a reduced scope of access to the client by passing a scope parameter to this method.
                    response = authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
                }
                else
                {
                    response = authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
                }

                return(authorizationServer.Channel.PrepareResponse(response).AsActionResult());
            }
        }
    protected void btnYes_Click(object sender, EventArgs e)
    {
        if (m_pendingRequest == null)
        {
            throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrMissingRequest);
        }

        MFBOauthClientAuth ca = new MFBOauthClientAuth {
            Scope = OAuthUtilities.JoinScopes(m_pendingRequest.Scope), ClientId = m_pendingRequest.ClientIdentifier, UserId = Page.User.Identity.Name, ExpirationDateUtc = DateTime.UtcNow.AddDays(14)
        };

        if (ca.fCommit())
        {
            EndUserAuthorizationSuccessResponseBase resp = authorizationServer.PrepareApproveAuthorizationRequest(m_pendingRequest, Page.User.Identity.Name);
            OutgoingWebResponse wr = authorizationServer.Channel.PrepareResponse(resp);
            wr.Send();
        }
        else
        {
            RejectWithError(Resources.LocalizedText.oAuthErrCreationFailed);
        }
    }
Esempio n. 11
0
        /// <summary>
        /// Create a authorise token from the request. Returns the bdy html result.
        /// </summary>
        /// <param name="httpRequest">The current http request.</param>
        /// <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="returnType">The type of response to return.</param>
        /// <param name="responseHeaders">The response headers for the request.</param>
        /// <param name="isApprovedByUser">Has the user approved the client to access the resources.</param>
        /// <returns>The formatted redirect url; else null.</returns>
        private object CreateAuthorise(HttpRequestBase httpRequest, Uri rawUri, NameValueCollection queryString,
                                       NameValueCollection form, NameValueCollection headers, HttpCookieCollection cookies, int returnType,
                                       out System.Net.WebHeaderCollection responseHeaders, bool isApprovedByUser)
        {
            IDirectedProtocolMessage response    = null;
            OutgoingWebResponse      webResponse = null;
            string clientID = null;
            string nonce    = null;
            string codeKey  = null;

            try
            {
                // Make sure that all the passed parameters are valid.
                if (httpRequest == null)
                {
                    throw new ArgumentNullException("httpRequest");
                }
                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");
                }

                // Read the request make sure it is valid.
                EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest(httpRequest);
                if (pendingRequest == null)
                {
                    throw new Exception("Missing authorization request.");
                }

                // Only process if the user has approved the request.
                if (isApprovedByUser)
                {
                    // Make sure all maditor parameters are present.
                    _oAuthAuthorizationServer.ValidateAuthoriseRequestParametersAbsent(queryString);
                    if (_oAuthAuthorizationServer.ParametersAbsent.Count() > 0)
                    {
                        throw new Exception("Some authorisation request parameters are missing.");
                    }

                    // Assign each query string parameter.
                    clientID = pendingRequest.ClientIdentifier;
                    string callback            = pendingRequest.Callback.ToString();
                    string state               = pendingRequest.ClientState;
                    string scope               = OAuthUtilities.JoinScopes(pendingRequest.Scope);
                    string responseType        = (pendingRequest.ResponseType == EndUserAuthorizationResponseType.AccessToken ? "token" : "code");
                    string companyUniqueUserID = queryString["com_unique_uid"];

                    // Set the crytography key store values.
                    _authorizationServer.AuthorizationServerServices.CryptoKeyStore.ExpiryDateTime   = DateTime.UtcNow.AddYears(1);
                    _authorizationServer.AuthorizationServerServices.CryptoKeyStore.ClientIndetifier = clientID;
                    _authorizationServer.AuthorizationServerServices.CryptoKeyStore.GetCodeKey       = false;

                    // Create a new nonce and store it in the nonce store.
                    nonce = _nonceStore.GenerateNonce();
                    _nonceStore.StoreNonce(DateTime.UtcNow, nonce, clientID);

                    // Create the access token from the stores, and create a new verification code.
                    string verifier = _consumerStore.SetVerificationCode(clientID, nonce, companyUniqueUserID, scope);
                    EndUserAuthorizationSuccessAccessTokenResponse successAccessTokenResponse = null;

                    // Prepare the request. pass the nonce and join the userID and nonce of
                    // the user that approved the resource access request.
                    response = _authorizationServer.PrepareApproveAuthorizationRequest(
                        pendingRequest,
                        companyUniqueUserID + "_" + nonce,
                        nonce,
                        out successAccessTokenResponse);

                    // Prepare the authorisation response.
                    webResponse = _authorizationServer.Channel.PrepareResponse(response);

                    // Create the query collection of the code request
                    // and extract the code value that is to be sent
                    // the the client.
                    NameValueCollection queryResponseString = new NameValueCollection();
                    Uri uriRequest = webResponse.GetDirectUriRequest(_authorizationServer.Channel);

                    // For each query item.
                    string[] queries = uriRequest.Query.Split(new char[] { '&' });
                    foreach (string query in queries)
                    {
                        // Add the query name and value to the collection.
                        string[] queriesNameValue = query.Split(new char[] { '=' });
                        queryResponseString.Add(queriesNameValue[0].TrimStart(new char[] { '?' }), queriesNameValue[1]);
                    }

                    // What type of response is to be handled.
                    switch (pendingRequest.ResponseType)
                    {
                    case EndUserAuthorizationResponseType.AuthorizationCode:
                        // The user has requested a code, this is
                        // used so the client can get a token later.
                        // If the code response type exits.
                        if (queryResponseString["code"] != null)
                        {
                            codeKey = HttpUtility.UrlDecode(queryResponseString["code"]);
                        }

                        // Insert the code key (code or token);
                        if (!String.IsNullOrEmpty(codeKey))
                        {
                            _tokenStore.StoreCodeKey(clientID, nonce, codeKey);
                        }
                        break;

                    case EndUserAuthorizationResponseType.AccessToken:
                        // This is used so the client is approved and a token is sent back.
                        // Update the access token.
                        if (successAccessTokenResponse != null)
                        {
                            if (!String.IsNullOrEmpty(successAccessTokenResponse.AccessToken))
                            {
                                _tokenStore.UpdateAccessToken(successAccessTokenResponse.AccessToken, nonce);
                            }
                        }
                        break;
                    }
                }
                else
                {
                    // Send an error response.
                    response = _authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
                }

                // What type should be returned.
                switch (returnType)
                {
                case 0:
                    // A URI request redirect only.
                    responseHeaders = webResponse.Headers;
                    return(webResponse.GetDirectUriRequest(_authorizationServer.Channel));

                case 1:
                    // The complete html body.
                    responseHeaders = webResponse.Headers;
                    return(webResponse.Body);

                default:
                    // Default is the complete html body.
                    responseHeaders = webResponse.Headers;
                    return(webResponse.Body);
                }
            }
            catch (Exception ex)
            {
                // Get the current token errors.
                responseHeaders = null;
                _tokenError     = ex.Message;
                return(null);
            }
        }