Esempio n. 1
0
        /// <summary>
        /// Approves an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client.
        /// </summary>
        /// <param name="authorizationRequest">The authorization request to approve.</param>
        /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param>
        /// <param name="nonce">The nonce data.</param>
        /// <param name="successAccessTokenResponse">The end user authorization success access token response.</param>
        /// <param name="scopes">The scope of access the client should be granted.  If <c>null</c>, all scopes in the original request will be granted.</param>
        /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
        public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, string nonce,
                                                out EndUserAuthorizationSuccessAccessTokenResponse successAccessTokenResponse, IEnumerable <string> scopes = null, Uri callback = null)
        {
            var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, userName, nonce, out successAccessTokenResponse, scopes, callback);

            this.Channel.Respond(response);
        }
Esempio n. 2
0
        /// <summary>
        /// Approves an authorization request.
        /// </summary>
        /// <param name="authorizationRequest">The authorization request to approve.</param>
        /// <param name="userDataAndNonce">The username of the account that approved the request (or whose data will be accessed by the client).</param>
        /// <param name="nonce">The nonce data.</param>
        /// <param name="successAccessTokenResponse">The end user authorization success access token response.</param>
        /// <param name="scopes">The scope of access the client should be granted.  If <c>null</c>, all scopes in the original request will be granted.</param>
        /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
        /// <returns>The authorization response message to send to the Client.</returns>
        public EndUserAuthorizationSuccessResponseBase PrepareApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest,
                                                                                          string userDataAndNonce, string nonce, out EndUserAuthorizationSuccessAccessTokenResponse successAccessTokenResponse, IEnumerable <string> scopes = null, Uri callback = null)
        {
            Contract.Ensures(Contract.Result <EndUserAuthorizationSuccessResponseBase>() != null);

            if (callback == null)
            {
                callback = this.GetCallback(authorizationRequest);
            }

            var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier);
            EndUserAuthorizationSuccessResponseBase        response;
            EndUserAuthorizationSuccessAccessTokenResponse implicitGrantResponse = null;

            switch (authorizationRequest.ResponseType)
            {
            case EndUserAuthorizationResponseType.AccessToken:
                IAccessTokenRequestInternal accessRequestInternal = (EndUserAuthorizationImplicitRequest)authorizationRequest;
                var accessTokenResult = this.AuthorizationServerServices.CreateAccessToken(accessRequestInternal, nonce);
                ErrorUtilities.VerifyHost(accessTokenResult != null, "IAuthorizationServerHost.CreateAccessToken must not return null.");

                accessRequestInternal.AccessTokenResult = accessTokenResult;

                implicitGrantResponse          = new EndUserAuthorizationSuccessAccessTokenResponse(callback, authorizationRequest);
                implicitGrantResponse.Lifetime = accessTokenResult.AccessToken.Lifetime;
                accessTokenResult.AccessToken.ApplyAuthorization(implicitGrantResponse.Scope, userDataAndNonce, implicitGrantResponse.Lifetime);

                IAccessTokenCarryingRequest tokenCarryingResponse = implicitGrantResponse;
                tokenCarryingResponse.AuthorizationDescription = accessTokenResult.AccessToken;

                response = implicitGrantResponse;
                break;

            case EndUserAuthorizationResponseType.AuthorizationCode:
                var authCodeResponse = new EndUserAuthorizationSuccessAuthCodeResponseAS(callback, authorizationRequest);
                IAuthorizationCodeCarryingRequest codeCarryingResponse = authCodeResponse;
                codeCarryingResponse.AuthorizationDescription = new AuthorizationCode(
                    authorizationRequest.ClientIdentifier,
                    authorizationRequest.Callback,
                    authCodeResponse.Scope,
                    userDataAndNonce);
                response = authCodeResponse;
                break;

            default:
                throw ErrorUtilities.ThrowInternal("Unexpected response type.");
            }

            response.AuthorizingUsername = userDataAndNonce;

            // Customize the approved scope if the authorization server has decided to do so.
            if (scopes != null)
            {
                response.Scope.ResetContents(scopes);
            }

            successAccessTokenResponse = implicitGrantResponse;
            return(response);
        }
Esempio n. 3
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);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Updates the authorization state maintained by the client with the content of an outgoing response.
        /// </summary>
        /// <param name="authorizationState">The authorization state maintained by the client.</param>
        /// <param name="accessTokenSuccess">The access token containing response message.</param>
        internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess)
        {
            Requires.NotNull(authorizationState, "authorizationState");
            Requires.NotNull(accessTokenSuccess, "accessTokenSuccess");

            authorizationState.AccessToken = accessTokenSuccess.AccessToken;
            authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime;
            authorizationState.AccessTokenIssueDateUtc  = DateTime.UtcNow;
            if (accessTokenSuccess.Scope != null && accessTokenSuccess.Scope != authorizationState.Scope)
            {
                if (authorizationState.Scope != null)
                {
                    Logger.OAuth.InfoFormat(
                        "Requested scope of \"{0}\" changed to \"{1}\" by authorization server.",
                        authorizationState.Scope,
                        accessTokenSuccess.Scope);
                }

                authorizationState.Scope.ResetContents(accessTokenSuccess.Scope);
            }

            authorizationState.SaveChanges();
        }
Esempio n. 5
0
        /// <summary>
        /// Updates the authorization state maintained by the client with the content of an outgoing response.
        /// </summary>
        /// <param name="authorizationState">The authorization state maintained by the client.</param>
        /// <param name="accessTokenSuccess">The access token containing response message.</param>
        internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess)
        {
            authorizationState.AccessToken = accessTokenSuccess.AccessToken;
            authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime;
            authorizationState.AccessTokenIssueDateUtc  = DateTime.UtcNow;
            if (accessTokenSuccess.Scope != null && accessTokenSuccess.Scope != authorizationState.Scope)
            {
                if (authorizationState.Scope != null)
                {
                }

                authorizationState.Scope.ResetContents(accessTokenSuccess.Scope);
            }

            authorizationState.SaveChanges();
        }