Exemplo n.º 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.pendingRequest = OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequest();
                if (this.pendingRequest == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
                }

                this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie();
                var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
                this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name);
                this.scopeLabel.Text        = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope));

                // Consider auto-approving if safe to do so.
                if (((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices).CanBeAutoApproved(this.pendingRequest))
                {
                    OAuthServiceProvider.AuthorizationServer.ApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name);
                }
                this.ViewState["AuthRequest"] = this.pendingRequest;
            }
            else
            {
                Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value);
                this.pendingRequest = (EndUserAuthorizationRequest)this.ViewState["AuthRequest"];
            }
        }
Exemplo n.º 2
0
        public bool TryAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest, out string canonicalUserName)
        {
            var user = MvcApplication.DataContext.Users.SingleOrDefault(
                u => u.Username == userName && u.Password == password);

            canonicalUserName = userName;

            if (user == null)
            {
                return(false);
            }

            #region add an authorization for this client

            // 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 == accessRequest.ClientIdentifier);
            client.ClientAuthorizations.Add(
                new ClientAuthorization
            {
                Scope        = OAuthUtilities.JoinScopes(accessRequest.Scope),
                User         = MvcApplication.DataContext.Users.FirstOrDefault(u => u.Username == userName),
                CreatedOnUtc = DateTime.UtcNow,
            });
            MvcApplication.DataContext.SaveChanges(); // submit now so that this new row can be retrieved later in this same HTTP request

            #endregion

            return(true);
        }
Exemplo n.º 3
0
        public ActionResult AuthorizeResponse(bool isApproved)
        {
            var pendingRequest = this.m_AuthorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);

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

            if (isApproved)
            {
                var clientInfo = m_ClientRep.Get(s => s.ClientIdentifier == pendingRequest.ClientIdentifier);
                var user       = AuthorizeHelper.GetCurrentUser();
                var userInfo   = m_UserRep.Get(s => s.OpenIDClaimedIdentifier == user.UserName);
                m_ClientAuthRep.Add(new ClientAuthorization()
                {
                    Scope        = OAuthUtilities.JoinScopes(pendingRequest.Scope),
                    UserId       = userInfo.UserId,
                    CreatedOnUtc = DateTime.UtcNow,
                    ClientId     = clientInfo.ClientId
                });

                response = this.m_AuthorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, user.UserName);
            }
            else
            {
                response = this.m_AuthorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
            }
            var res = this.m_AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);

            Response.ContentType = res.Content.Headers.ContentType.ToString();
            return(res.AsActionResult());
        }
Exemplo n.º 4
0
        private static void Main()
        {
            // DotNetOpenAuth only issues access tokens when the client uses an HTTPS connection. As we will most
            // likely run the server on our local development machine with only a self-signed SSL certificate, setting up
            // connection to the server will fail as the SSL certificate is considered invalid by the .NET framework.
            // To circumvent this, we add the line below that will consider all SSL certificates as valid, including
            // self-signed certificaties. Note: this should only be used for testing purposes.
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

            // The description of the authorization server to which we will be connecting. The most important component
            // is the token endpoint, which is the URL at which the server listens for token requests
            var authorizationServerDescription = new AuthorizationServerDescription
            {
                TokenEndpoint   = new Uri("https://localhost:44303/tokens"),
                ProtocolVersion = ProtocolVersion.V20
            };

            // Create the client with which we will be connecting to the server.
            var userAgentClient = new UserAgentClient(authorizationServerDescription, clientIdentifier: "demo-client-1", clientSecret: "demo-client-secret-1");

            // The scope that we request for the client. Note: this can also be null if we don't want to request any specific
            // scope or more than one scope if we want to request an access token that is valid for several scopes
            var clientScopes = new[] { "demo-scope-client-1" };

            // Request a new client access token for the specified scopes (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4)
            // This method will use the client identifier and client secret used when constructing the UserAgentClient instance
            var clientAccessToken = userAgentClient.GetClientAccessToken(clientScopes);

            // Output some information about the retrieved client access token
            Console.WriteLine("[RETRIEVED CLIENT ACCESS TOKEN]");
            Console.WriteLine("Access token: {0}", clientAccessToken.AccessToken);
            Console.WriteLine("Expiration time: {0}", clientAccessToken.AccessTokenExpirationUtc);
            Console.WriteLine("Scope: {0}", OAuthUtilities.JoinScopes(clientAccessToken.Scope));

            // The scope that we request for the user. Note: this can also be null if we don't want to request any specific
            // scope or more than one scope if we want to request an access token that is valid for several scopes
            var userScopes = new[] { "demo-scope-1" };

            // Request a new user access token for the specified user and the specified scopes (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#page-35)
            var userAccessToken = userAgentClient.ExchangeUserCredentialForToken("demo-user-1", "demo-user-password-1", userScopes);

            // Output some information about the retrieved user access token
            Console.WriteLine("\n[RETRIEVED USER ACCESS TOKEN]");
            Console.WriteLine("Access token: {0}", userAccessToken.AccessToken);
            Console.WriteLine("Refresh token: {0}", userAccessToken.RefreshToken);
            Console.WriteLine("Expiration time: {0}", userAccessToken.AccessTokenExpirationUtc);
            Console.WriteLine("Scope: {0}", OAuthUtilities.JoinScopes(userAccessToken.Scope));

            var refreshed = userAgentClient.RefreshAuthorization(userAccessToken);

            Console.WriteLine("\n[REFRESHING USER ACCESS TOKEN]");
            Console.WriteLine("Access token refreshed: {0}", refreshed);

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 5
0
        protected void yesButton_Click(object sender, EventArgs e)
        {
            var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);

            Database.LoggedInUser.ClientAuthorizations.Add(
                new ClientAuthorization {
                Client       = requestingClient,
                Scope        = OAuthUtilities.JoinScopes(this.pendingRequest.Scope),
                User         = Database.LoggedInUser,
                CreatedOnUtc = DateTime.UtcNow.CutToSecond(),
            });
            OAuthServiceProvider.AuthorizationServer.ApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name);
        }
Exemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                if (!IsPostBack)
                {
                    this.pendingRequest =
                        await
                        OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequestAsync(
                            new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                    if (this.pendingRequest == null)
                    {
                        throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
                    }

                    this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie();
                    var requestingClient =
                        Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
                    this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name);
                    this.scopeLabel.Text        = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope));

                    // Consider auto-approving if safe to do so.
                    if (
                        ((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices)
                        .CanBeAutoApproved(this.pendingRequest))
                    {
                        var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest(
                            this.pendingRequest, HttpContext.Current.User.Identity.Name);
                        var responseMessage =
                            await
                            OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(
                                response, Response.ClientDisconnectedToken);
                        await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
                        this.Context.Response.End();
                    }
                    this.ViewState["AuthRequest"] = this.pendingRequest;
                }
                else
                {
                    Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value);
                    this.pendingRequest = (EndUserAuthorizationRequest)this.ViewState["AuthRequest"];
                }
            }));
        }
Exemplo n.º 7
0
        public ActionResult AuthorizeResponse(bool isApproved)
        {
            var pendingRequest = this.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.LoggedInUser,
                    CreatedOnUtc = DateTime.UtcNow,
                });
                MvcApplication.DataContext.SubmitChanges();                 // 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 = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
            }
            else
            {
                response = this.authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
                //var errorResponse = response as EndUserAuthorizationFailedResponse;
                //if (errorResponse != null) {
                //    errorResponse.Error = "accesss_denied";  // see http://tools.ietf.org/id/draft-ietf-oauth-v2-31.html#rfc.section.4.1.2.1 for valid values
                //    errorResponse.ErrorDescription = "The resource owner or authorization server denied the request";
                //}
            }

            return(this.authorizationServer.Channel.PrepareResponse(response).AsActionResult());
        }
Exemplo n.º 8
0
        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());
        }
Exemplo 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());
            }
        }
Exemplo n.º 10
0
    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);
        }
    }
Exemplo n.º 11
0
        public async Task <ActionResult> AuthorizeResponse(bool isApproved)
        {
            var pendingRequest = await this.authorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);

            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.LoggedInUser,
                    CreatedOnUtc = DateTime.UtcNow,
                });
                MvcApplication.DataContext.SubmitChanges();                 // 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 = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
            }
            else
            {
                response = this.authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
            }

            var preparedResponse = await this.authorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);

            Response.ContentType = preparedResponse.Content.Headers.ContentType.ToString();
            return(preparedResponse.AsActionResult());
        }
Exemplo n.º 12
0
 protected void yesButton_Click(object sender, EventArgs e)
 {
     this.RegisterAsyncTask(
         new PageAsyncTask(
             async ct => {
         var requestingClient =
             Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
         Database.LoggedInUser.ClientAuthorizations.Add(
             new ClientAuthorization {
             Client       = requestingClient,
             Scope        = OAuthUtilities.JoinScopes(this.pendingRequest.Scope),
             User         = Database.LoggedInUser,
             CreatedOnUtc = DateTime.UtcNow.CutToSecond(),
         });
         var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest(
             this.pendingRequest, HttpContext.Current.User.Identity.Name);
         var responseMessage =
             await
             OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
         await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
         this.Context.Response.End();
     }));
 }
Exemplo n.º 13
0
        public ActionResult ProcessAuthorization(bool isApproved)
        {
            // Have DotNetOpenAuth read the info we need out of the request
            EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest();

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

            // Make sure the client is one we recognize
            Client requestingClient = _clientRepository.GetById(pendingRequest.ClientIdentifier);

            if (requestingClient == null)
            {
                throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request");
            }

            // Make sure the resource is defined, it definitely should be due to the ResourceAuthenticated attribute
            Resource requestedResource = _resourceRepository.FindWithSupportedScopes(pendingRequest.Scope);

            if (requestedResource == null)
            {
                throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request");
            }

            // See if authorization of this client was approved by the user
            // At this point, the user either agrees to the entire scope requested by the client or none of it.
            // If we gave capability for user to reduce scope to give client less access, some changes would be required here
            IDirectedProtocolMessage authRequest;

            if (isApproved)
            {
                // Add user to our repository if this is their first time
                var requestingUser = _userRepository.GetById(User.Identity.Name);
                if (requestingUser == null)
                {
                    requestingUser = new User {
                        Id = User.Identity.Name, CreateDateUtc = DateTime.UtcNow
                    };
                    _userRepository.Insert(requestingUser);
                    _userRepository.Save();
                }

                // 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.
                _authorizationRepository.Insert(new Authorization
                {
                    ClientId     = requestingClient.Id,
                    Scope        = OAuthUtilities.JoinScopes(pendingRequest.Scope),
                    UserId       = requestingUser.Id,
                    ResourceId   = requestedResource.Id,
                    CreatedOnUtc = DateTime.UtcNow
                });
                _authorizationRepository.Save();

                // Have DotNetOpenAuth generate an approval to send back to the client
                authRequest = _authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
            }
            else
            {
                // Have DotNetOpenAuth generate a rejection to send back to the client
                authRequest = _authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
                // The PrepareResponse call below is giving an error of "The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationFailedResponse message: error"
                // unless I do this.....
                var msg = (EndUserAuthorizationFailedResponse)authRequest;
                msg.Error = "User denied your request";
            }

            // This will redirect to the client app using their defined callback, so they can handle
            // the approval or rejection as they see fit
            return(_authorizationServer.Channel.PrepareResponse(authRequest).AsActionResult());
        }
Exemplo n.º 14
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);
            }
        }
Exemplo n.º 15
0
        protected override string Serialize()
        {
            DateTime?expirationDateUtc = null;

            if (this.Lifetime.HasValue)
            {
                DateTime expirationDate = this.UtcIssued + this.Lifetime.Value;
                expirationDateUtc = expirationDate.ToLocalTime();
            }
            var token = this.SaveClientAuthorization(this.ClientIdentifier, this.User, OAuthUtilities.JoinScopes(this.Scope), expirationDateUtc);

            return(token);
        }