Ejemplo n.º 1
0
        public async Task <(byte[], Guid)> Authorize(string entityName, string sessionIdValue, byte[] body, byte[] hmacHeader, bool read)
        {
            var sessionId = String.IsNullOrEmpty(sessionIdValue)
                ? Guid.Empty
                : Guid.Parse(sessionIdValue);
            var session = sessions.Find(x => x.Id == sessionId);

            if (session == null)
            {
                var entity = await _entityService.Get(entityName);

                session = new Session();
                sessions.Add(session);
                var attributes = read ? entity.ReadAttributes : entity.WriteAttributes;
                var(protocolStep, Z) = _abeAuthBuilder.BuildStepOne(attributes, _options.Value.SGTSharedKey);
                session.Z            = Z;
                return(protocolStep, session.Id);
            }
            else
            {
                if (session.ProtocolStep == AbeAuthSteps.GetAccessPolicy)
                {
                    var request = _abeAuthBuilder.GetStepData <AbeAuthStepSix>(body);
                    _encryptor.SetKey(_options.Value.SGTSharedKey);
                    var sharedKey = _encryptor.Decrypt(request.CtPep);

                    var hmac = CryptoHelper.ComputeHash(session.Z, sharedKey);
                    if (!hmac.SequenceEqual(request.HMAC))
                    {
                        throw new ProtocolArgumentException("HMAC is incorrect!");
                    }

                    session.SharedKey    = sharedKey;
                    session.ProtocolStep = AbeAuthSteps.ConfirmAccessPolicy;

                    var protocolStep = _abeAuthBuilder.BuildStepSeven(request.HMAC, sharedKey);
                    return(protocolStep, session.Id);
                }
                else
                {
                    if (hmacHeader == null)
                    {
                        throw new ProtocolArgumentException("Session hmac is null!");
                    }

                    var correctHmac = CryptoHelper.ComputeHash(body, session.SharedKey);

                    if (!correctHmac.SequenceEqual(hmacHeader))
                    {
                        throw new ProtocolArgumentException("Session hmac is incorrect!");
                    }
                }
            }

            return(null, session.Id);
        }