Example #1
0
        public async ValueTask <UserJwtV2> ResourceOwner_GrantV2(ResourceOwnerV2 model)
        {
            var response = await Endpoints.ResourceOwner_AuthV2(model);

            if (response.IsSuccessStatusCode)
            {
                return(await response.Content.ReadAsAsync <UserJwtV2>().ConfigureAwait(false));
            }

            throw new HttpRequestException(response.RequestMessage.ToString(),
                                           new Exception(response.ToString()));
        }
Example #2
0
        public async ValueTask <HttpResponseMessage> ResourceOwner_AuthV2(ResourceOwnerV2 model)
        {
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("issuer", model.issuer),
                new KeyValuePair <string, string>("client", model.client),
                new KeyValuePair <string, string>("grant_type", model.grant_type),
                new KeyValuePair <string, string>("user", model.user),
                new KeyValuePair <string, string>("password", model.password),
            });

            return(await _http.PostAsync("oauth2/v2/ropg", content));
        }
Example #3
0
        public IActionResult ResourceOwnerV2_Grant([FromForm] ResourceOwnerV2 input)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Guid       issuerID;
            tbl_Issuer issuer;

            //check if identifier is guid. resolve to guid if not.
            if (Guid.TryParse(input.issuer, out issuerID))
            {
                issuer = uow.Issuers.Get(x => x.Id == issuerID).SingleOrDefault();
            }
            else
            {
                issuer = uow.Issuers.Get(x => x.Name == input.issuer).SingleOrDefault();
            }

            if (issuer == null)
            {
                ModelState.AddModelError(MessageType.IssuerNotFound.ToString(), $"Issuer:{input.issuer}");
                return(NotFound(ModelState));
            }
            else if (!issuer.IsEnabled)
            {
                ModelState.AddModelError(MessageType.IssuerInvalid.ToString(), $"Issuer:{issuer.Id}");
                return(BadRequest(ModelState));
            }

            Guid     userID;
            tbl_User user;

            //check if identifier is guid. resolve to guid if not.
            if (Guid.TryParse(input.user, out userID))
            {
                user = uow.Users.Get(x => x.Id == userID).SingleOrDefault();
            }
            else
            {
                user = uow.Users.Get(x => x.UserName == input.user).SingleOrDefault();
            }

            if (user == null)
            {
                ModelState.AddModelError(MessageType.UserNotFound.ToString(), $"User:{input.user}");
                return(NotFound(ModelState));
            }
            //check that user is confirmed...
            //check that user is not locked...
            else if (uow.Users.IsLockedOut(user) ||
                     !user.EmailConfirmed ||
                     !user.PasswordConfirmed)
            {
                ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}");
                return(BadRequest(ModelState));
            }

            var audienceList = uow.Audiences.Get(QueryExpressionFactory.GetQueryExpression <tbl_Audience>()
                                                 .Where(x => x.tbl_Roles.Any(y => y.tbl_UserRoles.Any(z => z.UserId == user.Id))).ToLambda());

            var audiences = new List <tbl_Audience>();

            //check if client is single, multiple or undefined...
            if (string.IsNullOrEmpty(input.client))
            {
                audiences = uow.Audiences.Get(x => audienceList.Contains(x) &&
                                              x.IsLockedOut == false).ToList();
            }
            else
            {
                foreach (string entry in input.client.Split(","))
                {
                    Guid         audienceID;
                    tbl_Audience audience;

                    //check if identifier is guid. resolve to guid if not.
                    if (Guid.TryParse(entry.Trim(), out audienceID))
                    {
                        audience = uow.Audiences.Get(x => x.Id == audienceID).SingleOrDefault();
                    }
                    else
                    {
                        audience = uow.Audiences.Get(x => x.Name == entry.Trim()).SingleOrDefault();
                    }

                    if (audience == null)
                    {
                        ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:{entry}");
                        return(NotFound(ModelState));
                    }
                    else if (audience.IsLockedOut ||
                             !audienceList.Contains(audience))
                    {
                        ModelState.AddModelError(MessageType.AudienceInvalid.ToString(), $"Audience:{audience.Id}");
                        return(BadRequest(ModelState));
                    }

                    audiences.Add(audience);
                }
            }

            if (audiences.Count == 0)
            {
                ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:None");
                return(BadRequest(ModelState));
            }

            var logins = uow.Logins.Get(QueryExpressionFactory.GetQueryExpression <tbl_Login>()
                                        .Where(x => x.tbl_UserLogins.Any(y => y.UserId == user.Id)).ToLambda());

            switch (uow.InstanceType)
            {
            case InstanceContext.DeployedOrLocal:
            case InstanceContext.End2EndTest:
            {
                //check if login provider is local...
                if (logins.Where(x => x.Name.Equals(DefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any())
                {
                    //check that password is valid...
                    if (!PBKDF2.Validate(user.PasswordHashPBKDF2, input.password))
                    {
                        uow.AuthActivity.Create(
                            map.Map <tbl_AuthActivity>(new AuthActivityV1()
                            {
                                UserId       = user.Id,
                                LoginType    = GrantFlowType.ResourceOwnerPasswordV2.ToString(),
                                LoginOutcome = GrantFlowResultType.Failure.ToString(),
                            }));

                        uow.Commit();

                        ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}");
                        return(BadRequest(ModelState));
                    }
                }
                else
                {
                    ModelState.AddModelError(MessageType.LoginNotFound.ToString(), $"No login for user:{user.Id}");
                    return(NotFound(ModelState));
                }
            }
            break;

            case InstanceContext.SystemTest:
            case InstanceContext.IntegrationTest:
            {
                //check if login provider is local or test...
                if (logins.Where(x => x.Name.Equals(DefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any() ||
                    logins.Where(x => x.Name.StartsWith(TestDefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any())
                {
                    //check that password is valid...
                    if (!PBKDF2.Validate(user.PasswordHashPBKDF2, input.password))
                    {
                        uow.AuthActivity.Create(
                            map.Map <tbl_AuthActivity>(new AuthActivityV1()
                            {
                                UserId       = user.Id,
                                LoginType    = GrantFlowType.ResourceOwnerPasswordV2.ToString(),
                                LoginOutcome = GrantFlowResultType.Failure.ToString(),
                            }));

                        uow.Commit();

                        ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}");
                        return(BadRequest(ModelState));
                    }
                }
                else
                {
                    ModelState.AddModelError(MessageType.LoginNotFound.ToString(), $"No login for user:{user.Id}");
                    return(NotFound(ModelState));
                }
            }
            break;

            default:
                throw new NotImplementedException();
            }

            var rop_claims = uow.Users.GenerateAccessClaims(issuer, user);
            var rop        = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], audiences.Select(x => x.Name).ToList(), rop_claims);

            uow.AuthActivity.Create(
                map.Map <tbl_AuthActivity>(new AuthActivityV1()
            {
                UserId       = user.Id,
                LoginType    = GrantFlowType.ResourceOwnerPasswordV2.ToString(),
                LoginOutcome = GrantFlowResultType.Success.ToString(),
            }));

            var rt_claims = uow.Users.GenerateRefreshClaims(issuer, user);
            var rt        = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], audiences.Select(x => x.Name).ToList(), rt_claims);

            uow.Refreshes.Create(
                map.Map <tbl_Refresh>(new RefreshV1()
            {
                IssuerId     = issuer.Id,
                UserId       = user.Id,
                RefreshType  = ConsumerType.User.ToString(),
                RefreshValue = rt.RawData,
                IssuedUtc    = rt.ValidFrom,
                ValidFromUtc = rt.ValidFrom,
                ValidToUtc   = rt.ValidTo,
            }));

            uow.AuthActivity.Create(
                map.Map <tbl_AuthActivity>(new AuthActivityV1()
            {
                UserId       = user.Id,
                LoginType    = GrantFlowType.RefreshTokenV2.ToString(),
                LoginOutcome = GrantFlowResultType.Success.ToString(),
            }));

            uow.Commit();

            var result = new UserJwtV2()
            {
                token_type    = "bearer",
                access_token  = rop.RawData,
                refresh_token = rt.RawData,
                user          = user.UserName,
                client        = audiences.Select(x => x.Name).ToList(),
                issuer        = issuer.Name + ":" + conf["IdentityTenant:Salt"],
                expires_in    = (int)(new DateTimeOffset(rop.ValidTo).Subtract(DateTime.UtcNow)).TotalSeconds,
            };

            return(Ok(result));
        }