예제 #1
0
        private bool IsAuthorizationValid(HashSet <string> requestedScopes, string clientIdentifier, DateTime issuedUtc, string username)
        {
            // If db precision exceeds token time precision (which is common), the following query would
            // often disregard a token that is minted immediately after the authorization record is stored in the db.
            // To compensate for this, we'll increase the timestamp on the token's issue date by 1 second.
            issuedUtc += TimeSpan.FromSeconds(1);
            var sql = string.Format(@"SELECT CA.scope FROM ClientAuthorization CA
                        INNER JOIN Client C ON CA.ClientId = C.ClientId
                        INNER JOIN [User] U ON CA.UserId = U.UserId
                        WHERE C.ClientIdentifier = '{0}' AND CA.CreatedOnUtc <= '{1}' AND
                        (CA.ExpirationDateUtc Is null OR CA.ExpirationDateUtc >= '{2}')
                        AND U.OpenIDClaimedIdentifier = '{3}'", clientIdentifier, issuedUtc, DateTime.UtcNow, username);
            var grantedScopeStrings = m_ClientRep.Query <string>(sql, null);

            if (!grantedScopeStrings.Any())
            {
                // No granted authorizations prior to the issuance of this token, so it must have been revoked.
                // Even if later authorizations restore this client's ability to call in, we can't allow
                // access tokens issued before the re-authorization because the revoked authorization should
                // effectively and permanently revoke all access and refresh tokens.
                return(false);
            }

            var grantedScopes = new HashSet <string>(OAuthUtilities.ScopeStringComparer);

            foreach (string scope in grantedScopeStrings)
            {
                grantedScopes.UnionWith(OAuthUtilities.SplitScopes(scope));
            }

            return(requestedScopes.IsSubsetOf(grantedScopes));
        }
예제 #2
0
        // Determine whether the given authorization is still ok
        public bool IsAuthorizationValid(IAuthorizationDescription authorization)
        {
            // If db precision exceeds token time precision (which is common), the following query would
            // often disregard a token that is minted immediately after the authorization record is stored in the db.
            // To compensate for this, we'll increase the timestamp on the token's issue date by 1 second.
            var grantedAuths = _authorizationRepository.FindCurrent(authorization.ClientIdentifier, authorization.User,
                                                                    authorization.UtcIssued + TimeSpan.FromSeconds(1)).ToList();

            if (!grantedAuths.Any())
            {
                // No granted authorizations prior to the issuance of this token, so it must have been revoked.
                // Even if later authorizations restore this client's ability to call in, we can't allow
                // access tokens issued before the re-authorization because the revoked authorization should
                // effectively and permanently revoke all access and refresh tokens.
                return(false);
            }

            // Determine the set of all scopes the user has authorized for this client
            var grantedScopes = new HashSet <string>(OAuthUtilities.ScopeStringComparer);

            foreach (var auth in grantedAuths)
            {
                grantedScopes.UnionWith(OAuthUtilities.SplitScopes(auth.Scope));
            }

            // See if what's requested is authorized
            return(authorization.Scope.IsSubsetOf(grantedScopes));
        }
예제 #3
0
        private bool IsAuthorizationValid(HashSet <string> requestedScopes, string clientIdentifier, DateTime issuedUtc, string username)
        {
            var grantedScopeStrings = from auth in Database.DataContext.ClientAuthorizations
                                      where
                                      auth.Client.ClientIdentifier == clientIdentifier &&
                                      auth.CreatedOnUtc <= issuedUtc &&
                                      (!auth.ExpirationDateUtc.HasValue || auth.ExpirationDateUtc.Value >= DateTime.UtcNow) &&
                                      auth.User.AuthenticationTokens.Any(token => token.ClaimedIdentifier == username)
                                      select auth.Scope;

            if (!grantedScopeStrings.Any())
            {
                // No granted authorizations prior to the issuance of this token, so it must have been revoked.
                // Even if later authorizations restore this client's ability to call in, we can't allow
                // access tokens issued before the re-authorization because the revoked authorization should
                // effectively and permanently revoke all access and refresh tokens.
                return(false);
            }

            var grantedScopes = new HashSet <string>(OAuthUtilities.ScopeStringComparer);

            foreach (string scope in grantedScopeStrings)
            {
                grantedScopes.UnionWith(OAuthUtilities.SplitScopes(scope));
            }

            return(requestedScopes.IsSubsetOf(grantedScopes));
        }
        public ViewResult ClientCredentialsGrant(ClientCredentialsGrantViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    // Create the client with which we will be connecting to the server.
                    var webServerClient = new WebServerClient(this.AuthorizationServerDescription, clientIdentifier: model.ClientId, clientSecret: model.ClientSecret);

                    // 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 = OAuthUtilities.SplitScopes(model.Scope ?? string.Empty);

                    // 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 WebServerAgentClient instance
                    this.ViewBag.AccessToken = webServerClient.GetClientAccessToken(clientScopes);
                }
                catch (Exception ex)
                {
                    this.ViewBag.Exception = ex;
                }
            }

            return(this.View(model));
        }
예제 #5
0
        private bool IsAuthorizationValid(HashSet <string> requestedScopes, string clientIdentifier, DateTime issuedUtc, string username)
        {
            // If db precision exceeds token time precision (which is common), the following query would
            // often disregard a token that is minted immediately after the authorization record is stored in the db.
            // To compensate for this, we'll increase the timestamp on the token's issue date by 1 second.
            issuedUtc += TimeSpan.FromSeconds(1);
            var grantedScopeStrings = from auth in MvcApplication.DataContext.ClientAuthorizations
                                      where
                                      auth.Client.ClientIdentifier == clientIdentifier &&
                                      auth.CreatedOnUtc <= issuedUtc &&
                                      (!auth.ExpirationDateUtc.HasValue || auth.ExpirationDateUtc.Value >= DateTime.UtcNow) &&
                                      auth.User.OpenIDClaimedIdentifier == username
                                      select auth.Scope;

            if (!grantedScopeStrings.Any())
            {
                // No granted authorizations prior to the issuance of this token, so it must have been revoked.
                // Even if later authorizations restore this client's ability to call in, we can't allow
                // access tokens issued before the re-authorization because the revoked authorization should
                // effectively and permanently revoke all access and refresh tokens.
                return(false);
            }

            var grantedScopes = new HashSet <string>(OAuthUtilities.ScopeStringComparer);

            foreach (string scope in grantedScopeStrings)
            {
                grantedScopes.UnionWith(OAuthUtilities.SplitScopes(scope));
            }

            return(requestedScopes.IsSubsetOf(grantedScopes));
        }
        /// <summary>
        /// Determines whether a given set of resource owner credentials is valid based on the authorization server's user database
        /// and if so records an authorization entry such that subsequent calls to <see cref="M:DotNetOpenAuth.OAuth2.IAuthorizationServerHost.IsAuthorizationValid(DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationDescription)" /> would
        /// return <c>true</c>.
        /// </summary>
        /// <param name="userName">Username on the account.</param>
        /// <param name="password">The user's password.</param>
        /// <param name="accessRequest">The access request the credentials came with.
        /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param>
        /// <returns>
        /// A value that describes the result of the authorization check.
        /// </returns>
        public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest)
        {
            // Try to find a user with the specified username and password
            var user = this.db.Users.FirstOrDefault(u => u.OpenIDClaimedIdentifier == userName && u.Password == password);

            // If no user was found with the specified username/password combination, do not authorize the request
            if (user == null)
            {
                return(new AutomatedUserAuthorizationCheckResponse(accessRequest, false, userName));
            }

            // Try to find the authorization the user has with the specified client
            var userAuthorizationForClient = user.Authorizations.FirstOrDefault(a => a.Client.ClientIdentifier == accessRequest.ClientIdentifier);

            // If no user authorization was found, that means that the user is not authorized for the specified client.
            // As a consequence, we do not authorize the request
            if (userAuthorizationForClient == null)
            {
                return(new AutomatedUserAuthorizationCheckResponse(accessRequest, false, userName));
            }

            // At this point we have verified that user credentials were valid and that the user has an authorization specified
            // for the requested client. All that remains is to check if that authorization gives the user enough rights for
            // the requested scopes.
            var isApproved = RequestedScopeIsValid(accessRequest.Scope, OAuthUtilities.SplitScopes(userAuthorizationForClient.Scope));

            return(new AutomatedUserAuthorizationCheckResponse(accessRequest, isApproved, userName));
        }
        public JsonResult GetValues()
        {
            bool   isOK         = false;
            bool   requiresAuth = false;
            string redirectURL  = "";

            if (Session["AccessToken"] == null)
            {
                this.Authorization.Scope.AddRange(OAuthUtilities.SplitScopes("http://localhost:49810/api/values"));
                Uri authorizationUrl = this.Client.RequestUserAuthorization(this.Authorization);
                requiresAuth = true;
                redirectURL  = authorizationUrl.AbsoluteUri;
                isOK         = true;
            }
            else
            {
                requiresAuth = false;
            }
            return(new JsonResult()
            {
                Data = new {
                    OK = isOK,
                    RequiresAuth = requiresAuth,
                    RedirectURL = redirectURL
                }
            });
        }
예제 #8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Request.IsSecureConnection)
            {
                throw new HttpException((int)HttpStatusCode.Forbidden, Resources.LocalizedText.oAuthErrNotSecure);
            }

            if (!IsPostBack)
            {
                if ((m_pendingRequest = this.authorizationServer.ReadAuthorizationRequest()) == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrMissingRequest);
                }

                MFBOauth2Client client = (MFBOauth2Client)authorizationServer.AuthorizationServerServices.GetClient(m_pendingRequest.ClientIdentifier);

                if (Uri.Compare(m_pendingRequest.Callback, new Uri(client.Callback), UriComponents.HostAndPort | UriComponents.PathAndQuery, UriFormat.UriEscaped, StringComparison.CurrentCultureIgnoreCase) != 0)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrBadRedirectURL);
                }

                HashSet <string> allowedScopes = OAuthUtilities.SplitScopes(client.Scope);

                if (!m_pendingRequest.Scope.IsSubsetOf(allowedScopes))
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrUnauthorizedScopes);
                }

                IEnumerable <MFBOAuthScope> requestedScopes = MFBOauthServer.ScopesFromStrings(m_pendingRequest.Scope);

                // See if there are any scopes that are requested that are not allowed.

                IEnumerable <string> lstScopes = MFBOauthServer.ScopeDescriptions(requestedScopes);
                mvScopesRequested.SetActiveView(lstScopes.Count() == 0 ? vwNoScopes : vwRequestedScopes);
                rptPermissions.DataSource = lstScopes;
                rptPermissions.DataBind();

                ViewState[szVSKeyPendingRequest] = m_pendingRequest;

                lblClientName.Text = client.ClientName;
            }
            else
            {
                m_pendingRequest = (EndUserAuthorizationRequest)ViewState[szVSKeyPendingRequest];
            }
        }
        catch (HttpException ex)
        {
            RejectWithError(ex.Message);
        }
        catch (MyFlightbook.MyFlightbookException ex)
        {
            lblErr.Text = ex.Message;
            mvAuthorize.SetActiveView(vwErr);
        }
    }
예제 #9
0
        private void oauth2BeginButton_Click(object sender, RoutedEventArgs e)
        {
            var authServer = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription {
                AuthorizationEndpoint = new Uri(this.oauth2AuthorizationUrlBox.Text),
            };

            if (this.oauth2TokenEndpointBox.Text.Length > 0)
            {
                authServer.TokenEndpoint = new Uri(this.oauth2TokenEndpointBox.Text);
            }

            try {
                var client = new OAuth2.UserAgentClient(authServer, this.oauth2ClientIdentifierBox.Text, this.oauth2ClientSecretBox.Text);

                var authorizePopup = new Authorize2(client);
                authorizePopup.Authorization.Scope.AddRange(OAuthUtilities.SplitScopes(this.oauth2ScopeBox.Text));
                authorizePopup.Owner = this;
                bool?result = authorizePopup.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    var requestUri = new UriBuilder(this.oauth2ResourceUrlBox.Text);
                    if (this.oauth2ResourceHttpMethodList.SelectedIndex > 0)
                    {
                        requestUri.AppendQueryArgument("access_token", authorizePopup.Authorization.AccessToken);
                    }

                    var request = (HttpWebRequest)WebRequest.Create(requestUri.Uri);
                    request.Method = this.oauth2ResourceHttpMethodList.SelectedIndex < 2 ? "GET" : "POST";
                    if (this.oauth2ResourceHttpMethodList.SelectedIndex == 0)
                    {
                        client.AuthorizeRequest(request, authorizePopup.Authorization);
                    }

                    using (var resourceResponse = request.GetResponse()) {
                        using (var responseStream = new StreamReader(resourceResponse.GetResponseStream())) {
                            this.oauth2ResultsBox.Text = responseStream.ReadToEnd();
                        }
                    }
                }
                else
                {
                    return;
                }
            } catch (Messaging.ProtocolException ex) {
                MessageBox.Show(this, ex.Message);
            } catch (WebException ex) {
                string responseText = string.Empty;
                if (ex.Response != null)
                {
                    using (var responseReader = new StreamReader(ex.Response.GetResponseStream())) {
                        responseText = responseReader.ReadToEnd();
                    }
                }
                MessageBox.Show(this, ex.Message + "  " + responseText);
            }
        }
예제 #10
0
        public static IEnumerable <MFBOAuthScope> ScopesFromString(string sz)
        {
            List <MFBOAuthScope> lst = new List <MFBOAuthScope>();

            if (sz == null)
            {
                return(lst);
            }

            return(ScopesFromStrings(OAuthUtilities.SplitScopes(sz)));
        }
        public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest)
        {
            // Find the client
            var client = _lstClients.Single(consumerCandidate => consumerCandidate.ClientIdentifier == accessRequest.ClientIdentifier);

            // Parse the scopes the client is authorized for
            var scopesClientIsAuthorizedFor = OAuthUtilities.SplitScopes(client.Scope);

            // Check if the scopes that are being requested are a subset of the scopes the user is authorized for.
            // If not, that means that the user has requested at least one scope it is not authorized for
            var clientIsAuthorizedForRequestedScopes = accessRequest.Scope.IsSubsetOf(scopesClientIsAuthorizedFor);

            // The token request is approved when the client is authorized for the requested scopes
            var isApproved = clientIsAuthorizedForRequestedScopes;

            return(new AutomatedAuthorizationCheckResponse(accessRequest, isApproved));
        }
예제 #12
0
        private void beginWcfAuthorizationButton_Click(object sender, RoutedEventArgs e)
        {
            var auth = new Authorize2(this.wcf);

            auth.Authorization.Scope.AddRange(OAuthUtilities.SplitScopes("http://tempuri.org/IDataApi/GetName http://tempuri.org/IDataApi/GetAge http://tempuri.org/IDataApi/GetFavoriteSites"));
            auth.Authorization.Callback = new Uri("http://localhost:59721/");
            auth.Owner = this;
            bool?result = auth.ShowDialog();

            if (result.HasValue && result.Value)
            {
                this.wcfAccessToken           = auth.Authorization;
                this.wcfName.Content          = this.CallService(client => client.GetName());
                this.wcfAge.Content           = this.CallService(client => client.GetAge());
                this.wcfFavoriteSites.Content = this.CallService(client => string.Join(", ", client.GetFavoriteSites()));
            }
        }
예제 #13
0
        private async void oauth2BeginButton_Click(object sender, RoutedEventArgs e)
        {
            var authServer = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription {
                AuthorizationEndpoint = new Uri(this.oauth2AuthorizationUrlBox.Text),
            };

            if (this.oauth2TokenEndpointBox.Text.Length > 0)
            {
                authServer.TokenEndpoint = new Uri(this.oauth2TokenEndpointBox.Text);
            }

            try {
                var client = new OAuth2.UserAgentClient(authServer, this.oauth2ClientIdentifierBox.Text, this.oauth2ClientSecretBox.Text);

                var authorizePopup = new Authorize2(client);
                authorizePopup.Authorization.Scope.AddRange(OAuthUtilities.SplitScopes(this.oauth2ScopeBox.Text));
                authorizePopup.Authorization.Callback = new Uri("http://www.microsoft.com/en-us/default.aspx");
                authorizePopup.Owner = this;
                authorizePopup.ClientAuthorizationView.RequestImplicitGrant = this.flowBox.SelectedIndex == 1;
                bool?result = authorizePopup.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    var request = new HttpRequestMessage(
                        new HttpMethod(((ComboBoxItem)this.oauth2ResourceHttpMethodList.SelectedValue).Content.ToString()),
                        this.oauth2ResourceUrlBox.Text);
                    using (var httpClient = new HttpClient(client.CreateAuthorizingHandler(authorizePopup.Authorization))) {
                        using (var resourceResponse = await httpClient.SendAsync(request)) {
                            this.oauth2ResultsBox.Text = await resourceResponse.Content.ReadAsStringAsync();
                        }
                    }
                }
            } catch (Messaging.ProtocolException ex) {
                MessageBox.Show(this, ex.Message);
            } catch (WebException ex) {
                string responseText = string.Empty;
                if (ex.Response != null)
                {
                    using (var responseReader = new StreamReader(ex.Response.GetResponseStream())) {
                        responseText = responseReader.ReadToEnd();
                    }
                }
                MessageBox.Show(this, ex.Message + "  " + responseText);
            }
        }
예제 #14
0
        private AccessToken GetAccessToken(string accessToken)
        {
            using (var db = new OAuthDbContext())
            {
                var query = from auth in db.ClientAuthorizations
                            from client in db.Clients
                            where auth.ClientId == client.ClientId && auth.Token == accessToken
                            select new
                {
                    client.ClientIdentifier,
                    auth.UserId,
                    auth.Scope,
                    auth.ExpirationDateUtc,
                    auth.CreatedOnUtc
                };
                var clientAuth = query.FirstOrDefault();
                if (clientAuth == null)
                {
                    throw new Exception("当前AccessToken无效,请重新认证!");
                }

                else if (clientAuth.ExpirationDateUtc.HasValue && clientAuth.ExpirationDateUtc < DateTime.UtcNow)
                {
                    throw new Exception("当前AccessToken已过期!");
                }

                //token.UtcIssued和token.Lifetime此处可以不赋值(后续并没有用到)
                var token = new AccessToken
                {
                    ClientIdentifier = clientAuth.ClientIdentifier,
                    User             = clientAuth.UserId
                };

                var scopes = OAuthUtilities.SplitScopes(clientAuth.Scope);
                if (scopes.Count > 0)
                {
                    token.Scope.AddRange(scopes);
                }

                return(token);
            }
        }
        public ViewResult ResourceOwnerCredentialsGrant(ResourceOwnerCredentialsGrantViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    // Create the client with which we will be connecting to the server.
                    var webServerClient = new WebServerClient(this.AuthorizationServerDescription, clientIdentifier: model.ClientId);

                    // 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 = OAuthUtilities.SplitScopes(model.Scope ?? string.Empty);

                    // 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)
                    this.ViewBag.AccessToken = webServerClient.ExchangeUserCredentialForToken(model.Username, model.Password, userScopes);
                }
                catch (Exception ex)
                {
                    this.ViewBag.Exception = ex;
                }
            }

            return(this.View(model));
        }
        /// <summary>
        /// Determines whether a described authorization is (still) valid.
        /// </summary>
        /// <param name="authorization">The authorization.</param>
        /// <returns>
        ///   <c>true</c> if the original authorization is still valid; otherwise, <c>false</c>.
        /// </returns>
        /// <remarks>
        ///   <para>When establishing that an authorization is still valid,
        /// it's very important to only match on recorded authorizations that
        /// meet these criteria:</para>
        /// 1) The client identifier matches.
        /// 2) The user account matches.
        /// 3) The scope on the recorded authorization must include all scopes in the given authorization.
        /// 4) The date the recorded authorization was issued must be <em>no later</em> that the date the given authorization was issued.
        ///   <para>One possible scenario is where the user authorized a client, later revoked authorization,
        /// and even later reinstated authorization.  This subsequent recorded authorization
        /// would not satisfy requirement #4 in the above list.  This is important because the revocation
        /// the user went through should invalidate all previously issued tokens as a matter of
        /// security in the event the user was revoking access in order to sever authorization on a stolen
        /// account or piece of hardware in which the tokens were stored. </para>
        /// </remarks>
        public bool IsAuthorizationValid(IAuthorizationDescription authorization)
        {
            // Try to find a user with the specified username and password
            var user = this.db.Users.FirstOrDefault(u => u.OpenIDClaimedIdentifier == authorization.User);

            // If no user was found with the specified username/password combination, the authorization is not valid
            if (user == null)
            {
                return(false);
            }

            // Try to find the authorization the user has with the specified client
            var userAuthorizationForClient = user.Authorizations.FirstOrDefault(a => a.Client.ClientIdentifier == authorization.ClientIdentifier);

            // If no user authorization was found, that means that the user is not authorized for the specified client.
            // As a consequence, the authorization is not valid
            if (userAuthorizationForClient == null)
            {
                return(false);
            }

            // We check once again if the user is authorized for the specified scopes
            return(RequestedScopeIsValid(authorization.Scope, OAuthUtilities.SplitScopes(userAuthorizationForClient.Scope)));
        }
예제 #17
0
 /// <summary>
 /// Check if the access token provided is authorized for the requested scopes.
 /// </summary>
 /// <returns><c>true</c>, if the access token provided is authorized for the requested scopes; otherwise, <c>false</c>.</returns>
 protected virtual bool AccessTokenIsAuthorizedForRequestedScopes()
 {
     return(OAuthUtilities.SplitScopes(this.Scopes ?? string.Empty).IsSubsetOf(this.resourceServer.GetAccessToken().Scope));
 }
예제 #18
0
 /// <summary>
 /// Decodes the specified value.
 /// </summary>
 /// <param name="value">The string value carried by the transport.  Guaranteed to never be null, although it may be empty.</param>
 /// <returns>
 /// The deserialized form of the given string.
 /// </returns>
 /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
 public object Decode(string value)
 {
     return(OAuthUtilities.SplitScopes(value));
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Request.IsSecureConnection)
                {
                    throw new HttpException((int)HttpStatusCode.Forbidden, Resources.LocalizedText.oAuthErrNotSecure);
                }

                if (!IsPostBack)
                {
                    if ((m_pendingRequest = this.authorizationServer.ReadAuthorizationRequest()) == null)
                    {
                        throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrMissingRequest);
                    }

                    MFBOauth2Client client = (MFBOauth2Client)authorizationServer.AuthorizationServerServices.GetClient(m_pendingRequest.ClientIdentifier);

                    bool fIsValidCallback = false;
                    foreach (string callback in client.Callbacks)
                    {
                        if (Uri.Compare(m_pendingRequest.Callback, new Uri(callback), UriComponents.HostAndPort | UriComponents.PathAndQuery, UriFormat.SafeUnescaped, StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            fIsValidCallback = true;
                            break;
                        }
                    }
                    if (!fIsValidCallback)
                    {
                        throw new HttpException((int)HttpStatusCode.BadRequest, String.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.LocalizedText.oAuthErrBadRedirectURL, m_pendingRequest.Callback.ToString()));
                    }

                    HashSet <string> allowedScopes = OAuthUtilities.SplitScopes(client.Scope);

                    if (!m_pendingRequest.Scope.IsSubsetOf(allowedScopes))
                    {
                        throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrUnauthorizedScopes);
                    }

                    IEnumerable <MFBOAuthScope> requestedScopes = MFBOauthServer.ScopesFromStrings(m_pendingRequest.Scope);

                    // See if there are any scopes that are requested that are not allowed.

                    IEnumerable <string> lstScopes = MFBOauthServer.ScopeDescriptions(requestedScopes);
                    mvScopesRequested.SetActiveView(!lstScopes.Any() ? vwNoScopes : vwRequestedScopes);
                    rptPermissions.DataSource = lstScopes;
                    rptPermissions.DataBind();

                    ViewState[szVSKeyPendingRequest] = m_pendingRequest;

                    lblClientName.Text = HttpUtility.HtmlEncode(client.ClientName);
                }
                else
                {
                    m_pendingRequest = (EndUserAuthorizationRequest)ViewState[szVSKeyPendingRequest];
                }
            }
            catch (Exception ex) when(ex is HttpException || ex is ProtocolException || ex is ProtocolFaultResponseException || ex is MyFlightbook.MyFlightbookException)
            {
                lblErr.Text = ex.Message;
                mvAuthorize.SetActiveView(vwErr);
            }
        }
예제 #20
0
        public override AuthorizationState ConvertToken(HttpRequest Request)
        {
            if (Request == null)
            {
                throw new ArgumentNullException("Request");
            }

            HttpWebRequest hr = (HttpWebRequest)HttpWebRequest.Create(new Uri(oAuth2TokenEndpoint));

            hr.Method      = "POST";
            hr.ContentType = "application/x-www-form-urlencoded";

            string szPostData = String.Format(CultureInfo.InvariantCulture, "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
                                              Request["code"],
                                              AppKey,
                                              AppSecret,
                                              RedirectUri(Request, Request.Path, szParamGDriveAuth).ToString());

            byte[] rgbData = System.Text.Encoding.UTF8.GetBytes(szPostData);
            hr.ContentLength = rgbData.Length;
            using (Stream s = hr.GetRequestStream())
            {
                s.Write(rgbData, 0, rgbData.Length);
            }

            WebResponse response = hr.GetResponse();

            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                string result = sr.ReadToEnd();

                // JSonConvert can't deserialize space-delimited scopes into a hashset, so we need to do that manually.  Uggh.
                Dictionary <string, string> d = JsonConvert.DeserializeObject <Dictionary <string, string> >(result);

                AuthorizationState authstate = new AuthorizationState(d.ContainsKey("scope") ? OAuthUtilities.SplitScopes(d["scope"]) : null);
                authstate.AccessToken             = d.ContainsKey("access_token") ? d["access_token"] : string.Empty;
                authstate.AccessTokenIssueDateUtc = DateTime.UtcNow;
                if (d.ContainsKey("expires_in"))
                {
                    int exp = 0;
                    if (int.TryParse(d["expires_in"], NumberStyles.Integer, CultureInfo.InvariantCulture, out exp))
                    {
                        authstate.AccessTokenExpirationUtc = DateTime.UtcNow.AddSeconds(exp);
                    }
                }
                authstate.RefreshToken = d.ContainsKey("refresh_token") ? d["refresh_token"] : string.Empty;

                return(authstate);
            }
        }