/// <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));
        }
示例#2
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());
        }
示例#3
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);
        }
示例#4
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));
        }
示例#5
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"];
            }
        }
        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));
        }
示例#7
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));
        }
示例#8
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));
        }
示例#9
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));
        }
        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
                }
            });
        }
示例#11
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);
        }
    }
示例#12
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);
            }
        }
示例#13
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();
        }
示例#14
0
        public static IEnumerable <MFBOAuthScope> ScopesFromString(string sz)
        {
            List <MFBOAuthScope> lst = new List <MFBOAuthScope>();

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

            return(ScopesFromStrings(OAuthUtilities.SplitScopes(sz)));
        }
示例#15
0
        public override ClientAuthenticationResult TryAuthenticateClient(IAuthorizationServerHost authorizationServerHost, AuthenticatedClientRequestBase requestMessage, out string clientIdentifier)
        {
            var credential = OAuthUtilities.ParseHttpBasicAuth(requestMessage.Headers);

            if (credential != null)
            {
                clientIdentifier = credential.UserName;
                return(TryAuthenticateClientBySecret(authorizationServerHost, credential.UserName, credential.Password));
            }
            clientIdentifier = null;
            return(ClientAuthenticationResult.NoAuthenticationRecognized);
        }
示例#16
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);
        }
示例#17
0
        /// <summary>
        /// Discovers what access the client should have considering the access token in the current request.
        /// </summary>
        /// <param name="httpRequestInfo">The HTTP request info.</param>
        /// <param name="requiredScopes">The set of scopes required to approve this request.</param>
        /// <returns>
        /// The access token describing the authorization the client has.  Never <c>null</c>.
        /// </returns>
        /// <exception cref="ProtocolFaultResponseException">
        /// Thrown when the client is not authorized.  This exception should be caught and the
        /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage"/> message should be returned to the client.
        /// </exception>
        public virtual AccessToken GetAccessToken(HttpRequestBase httpRequestInfo = null, params string[] requiredScopes)
        {
            if (httpRequestInfo == null)
            {
                httpRequestInfo = this.Channel.GetRequestFromContext();
            }

            AccessToken accessToken;
            AccessProtectedResourceRequest request = null;

            try
            {
                if (this.Channel.TryReadFromRequest <AccessProtectedResourceRequest>(httpRequestInfo, out request))
                {
                    accessToken = this.AccessTokenAnalyzer.DeserializeAccessToken(request, request.AccessToken);
                    ErrorUtilities.VerifyHost(accessToken != null, "IAccessTokenAnalyzer.DeserializeAccessToken returned a null reslut.");
                    if (string.IsNullOrEmpty(accessToken.UserDataAndNonce) && string.IsNullOrEmpty(accessToken.ClientIdentifier))
                    {
                        ErrorUtilities.ThrowProtocol(ResourceServerStrings.InvalidAccessToken);
                    }

                    var requiredScopesSet = OAuthUtilities.ParseScopeSet(requiredScopes);
                    if (!this.ScopeSatisfiedCheck.IsScopeSatisfied(requiredScope: requiredScopesSet, grantedScope: accessToken.Scope))
                    {
                        var response = UnauthorizedResponse.InsufficientScope(request, requiredScopesSet);
                        throw new ProtocolFaultResponseException(this.Channel, response);
                    }

                    return(accessToken);
                }
                else
                {
                    var ex       = new ProtocolException(ResourceServerStrings.MissingAccessToken);
                    var response = UnauthorizedResponse.InvalidRequest(ex);
                    throw new ProtocolFaultResponseException(this.Channel, response, innerException: ex);
                }
            }
            catch (ProtocolException ex)
            {
                if (ex is ProtocolFaultResponseException)
                {
                    // This doesn't need to be wrapped again.
                    throw;
                }

                var response = request != null?UnauthorizedResponse.InvalidToken(request, ex) : UnauthorizedResponse.InvalidRequest(ex);

                throw new ProtocolFaultResponseException(this.Channel, response, innerException: ex);
            }
        }
 public override void ApplyClientCredential(string clientIdentifier, HttpRequestMessage request)
 {
     if (clientIdentifier != null)
     {
         if (this.credential != null)
         {
             ErrorUtilities.VerifyHost(
                 string.Equals(this.credential.UserName, clientIdentifier, StringComparison.Ordinal),
                 "Client identifiers \"{0}\" and \"{1}\" do not match",
                 this.credential.UserName,
                 clientIdentifier
                 );
         }
     }
     OAuthUtilities.ApplyHttpBasicAuth(request.Headers, clientIdentifier, this.clientSecret);
 }
示例#19
0
        public OAuth20ConstructedAssertion ConstructAssertion(string userName)
        {
            // Get the UTC Date Timestamp
            string timestamp = DateTime.UtcNow.ToString("s") + "Z";

            // Setup the Assertion String
            string assertion = String.Format("{0}|{1}|{2}|{3}|{4}|{5}", clientName, publicKey, applicationId, clientString, userName, timestamp);

            // Generate the CMAC used for Assertion Security
            string cmac = OAuthUtilities.GenerateCmacHEX(privateKey, assertion);

            // Add the CMAC to the Assertion String
            string assertionFinal = String.Format("{0}|{1}", assertion, cmac);

            return(assertionFinal);
        }
示例#20
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()));
            }
        }
        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));
        }
示例#22
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"];
                }
            }));
        }
示例#23
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);
            }
        }
示例#24
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);
            }
        }
示例#25
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());
        }
        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());
        }
示例#27
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);
        }
    }
示例#29
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());
        }
示例#30
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();
     }));
 }