public bool CanBeAutoApproved(EndUserAuthorizationRequest authorizationRequest)
        {
            if (authorizationRequest == null)
            {
                throw new ArgumentNullException("authorizationRequest");
            }

            // NEVER issue an auto-approval to a client that would end up getting an access token immediately
            // (without a client secret), as that would allow arbitrary clients to masquarade as an approved client
            // and obtain unauthorized access to user data.
            if (authorizationRequest.ResponseType == EndUserAuthorizationResponseType.AuthorizationCode)
            {
                // Never issue auto-approval if the client secret is blank, since that too makes it easy to spoof
                // a client's identity and obtain unauthorized access.
                var db = new OAuthEntities();
                var requestingClient = db.oauth_client.First(c => c.ClientIdentifier == authorizationRequest.ClientIdentifier);
                if (!string.IsNullOrEmpty(requestingClient.ClientSecret))
                {
                    return this.IsAuthorizationValid(
                        authorizationRequest.Scope,
                        authorizationRequest.ClientIdentifier,
                        DateTime.UtcNow,
                        "zhangsan"
                        //HttpContext.Current.User.Identity.Name
                        );
                }
            }

            // Default to not auto-approving.
            return false;
        }
Beispiel #2
0
        public ActionResult Authorize()
        {
            var pendingRequest = this.authorizationServer.ReadAuthorizationRequest();
            if (pendingRequest == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
            }
            var db = new OAuthEntities();
            var requestingClient = db.oauth_client.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);

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

                return this.authorizationServer.Channel.PrepareResponse(approval).AsActionResult();

            }

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

            return View(model);
        }
 public void RemoveKey(string bucket, string handle)
 {
     var db = new OAuthEntities();
     var match = db.oauth_symmetriccryptokey.FirstOrDefault(k => k.Bucket == bucket && k.Handle == handle);
     if (match != null)
     {
         db.oauth_symmetriccryptokey.DeleteObject(match);
     }
 }
 public CryptoKey GetKey(string bucket, string handle)
 {
     //var db = new OAuthEntities();
     //var _db = db.symmetriccryptokeys.Where(k => k.Bucket == bucket && k.Handle == handle).ToList();
     //// Perform a case senstive match
     //var matches = from key in _db
     //              where string.Equals(key.Bucket, bucket, StringComparison.Ordinal) &&
     //              string.Equals(key.Handle, handle, StringComparison.Ordinal)
     //              select new CryptoKey(key.Secret, key.ExpiresUtc.AsUtc());
     //return matches.FirstOrDefault();
     var db = new OAuthEntities();
     var cryptoKey = db.oauth_symmetriccryptokey.Where(c => c.Bucket == bucket && c.Handle == handle).OrderByDescending(c => c.ExpiresUtc).FirstOrDefault();
     return new CryptoKey(cryptoKey.Secret, cryptoKey.ExpiresUtc.AsUtc());
 }
Beispiel #5
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 db = new OAuthEntities();
                var client = db.oauth_client.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
                var username = "******";//HttpContext.User.Identity.Name;
                var user = db.sys_user.FirstOrDefault(c => c.Username == username);
                db.oauth_clientauthorization.AddObject(new oauth_clientauthorization
                {
                    UserId = user.ID,
                    ClientId = client.ClientId,
                    CreatedOnUtc = DateTime.UtcNow,
                    Scope = OAuthUtilities.JoinScopes(pendingRequest.Scope),
                    ExpirationDateUtc = DateTime.UtcNow.AddMinutes(1)
                });
                db.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 = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, username);
            }
            else
            {
                response = this.authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
            }
            var a = this.authorizationServer.Channel.PrepareResponse(response);
            return a.AsActionResult();
        }
        public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket)
        {
            var db = new OAuthEntities();
            //return from key in db.symmetriccryptokeys
            //       where key.Bucket == bucket
            //       orderby key.ExpiresUtc descending
            //       select new KeyValuePair<string, CryptoKey>(key.Handle, new CryptoKey(key.Secret, key.ExpiresUtc.AsUtc()));

            //var db = new OAuthEntities();
            //var cryptoKey = db.symmetriccryptokeys.Where(c => c.Bucket == bucket).OrderByDescending(c => c.ExpiresUtc);
            //return cryptoKey.Select(c => new KeyValuePair<string, CryptoKey>(c.Handle, new CryptoKey(c.Secret, c.ExpiresUtc.AsUtc())));

            var matches = from key in db.oauth_symmetriccryptokey
                          where key.Bucket == bucket
                          orderby key.ExpiresUtc descending
                          select key;

            List<KeyValuePair<string, CryptoKey>> en = new List<KeyValuePair<string, CryptoKey>>();

            foreach (var key in matches)
                en.Add(new KeyValuePair<string, CryptoKey>(key.Handle, new CryptoKey(key.Secret, key.ExpiresUtc.AsUtc())));

            return en.AsEnumerable<KeyValuePair<string, CryptoKey>>();
        }
 public void StoreKey(string bucket, string handle, CryptoKey key)
 {
     var keyRow = new oauth_symmetriccryptokey()
     {
         Bucket = bucket,
         Handle = handle,
         Secret = key.Key,
         ExpiresUtc = key.ExpiresUtc,
     };
     var db = new OAuthEntities();
     db.oauth_symmetriccryptokey.AddObject(keyRow);
     db.SaveChanges();
 }
 /// <summary>
 /// Stores a given nonce and timestamp.
 /// </summary>
 /// <param name="context">The context, or namespace, within which the
 /// <paramref name="nonce"/> must be unique.
 /// The context SHOULD be treated as case-sensitive.
 /// The value will never be <c>null</c> but may be the empty string.</param>
 /// <param name="nonce">A series of random characters.</param>
 /// <param name="timestampUtc">The UTC timestamp that together with the nonce string make it unique
 /// within the given <paramref name="context"/>.
 /// The timestamp may also be used by the data store to clear out old nonces.</param>
 /// <returns>
 /// True if the context+nonce+timestamp (combination) was not previously in the database.
 /// False if the nonce was stored previously with the same timestamp and context.
 /// </returns>
 /// <remarks>
 /// The nonce must be stored for no less than the maximum time window a message may
 /// be processed within before being discarded as an expired message.
 /// This maximum message age can be looked up via the
 /// <see cref="DotNetOpenAuth.Configuration.MessagingElement.MaximumMessageLifetime"/>
 /// property, accessible via the <see cref="Configuration"/>
 /// property.
 /// </remarks>
 public bool StoreNonce(string context, string nonce, DateTime timestampUtc)
 {
     var db = new OAuthEntities();
     db.oauth_nonce.AddObject(new oauth_nonce() { Context = context, Code = nonce, Timestamp = timestampUtc });
     try
     {
         db.SaveChanges();
         return true;
     }
     catch (SqlException)
     {
         return false;
     }
 }
        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 db = new OAuthEntities();
            var now = DateTime.UtcNow;
            var client = db.oauth_client.FirstOrDefault(c => c.ClientIdentifier == clientIdentifier);

            if (!string.IsNullOrEmpty(username))
            {
                var user = db.sys_user.FirstOrDefault(c => c.Username == username);
                //if (user != null)
                //部署到IIS下可用
                //HttpContext.Current.Response.Headers.Add("userid", user.ID.ToString());
            }
            //如果是内部客户端,直接返回
            if (client != null && client.ClientType == (int)ClientType.Public)
                return true;

            var grantedScopeStrings = db.sys_user.Join(db.oauth_clientauthorization, c => c.ID, a => a.UserId, (u, ca) => new { u, ca })
                          .Join(db.oauth_client, c => c.ca.ClientId, c => c.ClientId, (uca, c) => new { uca.u, uca.ca, c, })
                          .Where(
                              c =>
                              c.c.ClientIdentifier == clientIdentifier && c.ca.CreatedOnUtc <= issuedUtc &&
                              (c.ca.ExpirationDateUtc == null || c.ca.ExpirationDateUtc >= now) &&
                              c.u.Username == username).Select(c => c.ca.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 IClientDescription GetClient(string clientIdentifier)
        {
            var db = new OAuthEntities();
            var consumerRow = db.oauth_client.SingleOrDefault(
                consumerCandidate => consumerCandidate.ClientIdentifier == clientIdentifier);
            if (consumerRow == null)
            {
                throw new ArgumentOutOfRangeException("clientIdentifier");
            }

            return consumerRow;
        }
        /// <summary>
        /// password授权
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="accessRequest"></param>
        /// <returns></returns>
        public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest)
        {
            var db = new OAuthEntities();
            var md5PWD = password.ToMd5();
            var user = db.sys_user.FirstOrDefault(u => u.Username == userName && u.Password == md5PWD);

            if (user == null)
            {
                return new AutomatedUserAuthorizationCheckResponse(accessRequest, false, userName);
            }
            //返回userid,部署到IIS下可用
            //HttpContext.Current.Response.Headers.Add("userid", user.ID.ToString());
            var client = db.oauth_client.FirstOrDefault(c => c.ClientIdentifier == accessRequest.ClientIdentifier);
            //如果是内部客户端,直接返回
            if (client != null && client.ClientType == (int)ClientType.Public)
                return new AutomatedUserAuthorizationCheckResponse(accessRequest, true, userName);

            var userAuthorizationForClient = user.oauth_clientauthorization.FirstOrDefault(a => a.oauth_client.ClientIdentifier == accessRequest.ClientIdentifier && (a.ExpirationDateUtc == null || a.ExpirationDateUtc >= DateTime.UtcNow));
            if (userAuthorizationForClient == null)
            {
                return new AutomatedUserAuthorizationCheckResponse(accessRequest, false, userName);
            }

            var isApproved = RequestedScopeIsValid(accessRequest.Scope, OAuthUtilities.SplitScopes(userAuthorizationForClient.Scope));
            return new AutomatedUserAuthorizationCheckResponse(accessRequest, isApproved, userName);
        }