Ejemplo n.º 1
0
        public async ValueTask <UserJwtV2> DeviceCode_GrantV2(DeviceCodeV2 model)
        {
            var response = await Endpoints.DeviceCode_AuthV2(model);

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

            throw new HttpRequestException(response.RequestMessage.ToString(),
                                           new Exception(response.ToString()));
        }
Ejemplo n.º 2
0
        public async ValueTask <HttpResponseMessage> DeviceCode_AuthV2(DeviceCodeV2 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_code", model.user_code),
                new KeyValuePair <string, string>("device_code", model.device_code),
            });

            return(await _http.PostAsync("oauth2/v2/dcg", content));
        }
Ejemplo n.º 3
0
        public IActionResult DeviceCodeV2_Ask([FromForm] DeviceCodeAskV2 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));
            }

            Guid         audienceID;
            tbl_Audience audience;

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

            if (audience == null)
            {
                ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:{input.client}");
                return(NotFound(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));
            }

            var expire = uow.Settings.Get(x => x.IssuerId == issuer.Id && x.AudienceId == null && x.UserId == null &&
                                          x.ConfigKey == SettingsConstants.TotpExpire).Single();

            var polling = uow.Settings.Get(x => x.IssuerId == issuer.Id && x.AudienceId == null && x.UserId == null &&
                                           x.ConfigKey == SettingsConstants.PollingMax).Single();

            var authorize = new Uri(string.Format("{0}/{1}/{2}", conf["IdentityMeUrls:BaseUiUrl"], conf["IdentityMeUrls:BaseUiPath"], "authorize"));
            var nonce     = Base64.CreateString(32);

            //create domain model for this result type...
            var result = new DeviceCodeV2()
            {
                issuer           = issuer.Id.ToString(),
                client           = audience.Id.ToString(),
                verification_url = authorize.AbsoluteUri,
                user_code        = new TimeBasedTokenFactory(8, 10).Generate(user.SecurityStamp, user.Id.ToString()),
                device_code      = nonce,
                interval         = uint.Parse(polling.ConfigValue),
            };

            var state = uow.States.Create(
                map.Map <tbl_State>(new StateV1()
            {
                IssuerId     = issuer.Id,
                AudienceId   = audience.Id,
                UserId       = user.Id,
                StateValue   = nonce,
                StateType    = ConsumerType.Device.ToString(),
                StateConsume = false,
                ValidFromUtc = DateTime.UtcNow,
                ValidToUtc   = DateTime.UtcNow.AddSeconds(uint.Parse(expire.ConfigValue)),
            }));

            uow.Commit();

            return(Ok(result));
        }
Ejemplo n.º 4
0
        public IActionResult DeviceCodeV2_Grant([FromForm] DeviceCodeV2 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         audienceID;
            tbl_Audience audience;

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

            if (audience == null)
            {
                ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:{input.client}");
                return(NotFound(ModelState));
            }
            else if (audience.IsLockedOut)
            {
                ModelState.AddModelError(MessageType.AudienceInvalid.ToString(), $"Audience:{audience.Id}");
                return(BadRequest(ModelState));
            }

            var polling = uow.Settings.Get(x => x.IssuerId == issuer.Id && x.AudienceId == null && x.UserId == null &&
                                           x.ConfigKey == SettingsConstants.PollingMax).Single();

            //check if state is valid...
            var state = uow.States.Get(x => x.StateValue == input.device_code &&
                                       x.StateType == ConsumerType.Device.ToString() &&
                                       x.ValidFromUtc <DateTime.UtcNow &&
                                                       x.ValidToUtc> DateTime.UtcNow).SingleOrDefault();

            if (state == null ||
                state.StateConsume == true)
            {
                ModelState.AddModelError(MessageType.StateInvalid.ToString(), $"Device code:{input.device_code}");
                return(BadRequest(ModelState));
            }
            //check if device is polling too frequently...
            else if (uint.Parse(polling.ConfigValue) <= (state.LastPollingUtc.Subtract(DateTime.UtcNow)).TotalSeconds)
            {
                state.LastPollingUtc = DateTime.UtcNow;
                state.StateConsume   = false;

                uow.States.Update(state);
                uow.Commit();

                ModelState.AddModelError(MessageType.StateSlowDown.ToString(), $"Device code:{input.device_code}");
                return(BadRequest(ModelState));
            }

            //check if device has been approved/denied...
            if (!state.StateDecision.HasValue)
            {
                ModelState.AddModelError(MessageType.StatePending.ToString(), $"Device code:{input.device_code}");
                return(BadRequest(ModelState));
            }
            else if (state.StateDecision.HasValue &&
                     !state.StateDecision.Value)
            {
                ModelState.AddModelError(MessageType.StateDenied.ToString(), $"Device code:{input.device_code}");
                return(BadRequest(ModelState));
            }

            var user = uow.Users.Get(x => x.Id == state.UserId).SingleOrDefault();

            if (user == null)
            {
                ModelState.AddModelError(MessageType.UserNotFound.ToString(), $"User:{state.UserId}");
                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));
            }

            if (!new TimeBasedTokenFactory(8, 10).Validate(user.SecurityStamp, input.user_code, user.Id.ToString()))
            {
                uow.AuthActivity.Create(
                    map.Map <tbl_AuthActivity>(new AuthActivityV1()
                {
                    UserId       = user.Id,
                    LoginType    = GrantFlowType.DeviceCodeV2.ToString(),
                    LoginOutcome = GrantFlowResultType.Failure.ToString(),
                }));

                uow.Commit();

                ModelState.AddModelError(MessageType.TokenInvalid.ToString(), $"Token:{input.user_code}");
                return(BadRequest(ModelState));
            }

            //no reuse of state after this...
            state.LastPollingUtc = DateTime.UtcNow;
            state.StateConsume   = true;

            //adjust state...
            uow.States.Update(state);

            var dc_claims = uow.Users.GenerateAccessClaims(issuer, user);
            var dc        = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], new List <string>()
            {
                audience.Name
            }, dc_claims);

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

            var rt_claims = uow.Users.GenerateRefreshClaims(issuer, user);
            var rt        = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], new List <string>()
            {
                audience.Name
            }, rt_claims);

            uow.Refreshes.Create(
                map.Map <tbl_Refresh>(new RefreshV1()
            {
                IssuerId     = issuer.Id,
                UserId       = user.Id,
                RefreshType  = ConsumerType.User.ToString(),
                RefreshValue = rt.RawData,
                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  = dc.RawData,
                refresh_token = rt.RawData,
                user          = user.UserName,
                client        = new List <string>()
                {
                    audience.Name
                },
                issuer     = issuer.Name + ":" + conf["IdentityTenant:Salt"],
                expires_in = (int)(new DateTimeOffset(dc.ValidTo).Subtract(DateTime.UtcNow)).TotalSeconds,
            };

            return(Ok(result));
        }