oauth-2.0 授权错误403:Android管理API拒绝访问,未使用Google云项目帐户凭据

rsaldnfx  于 2022-10-31  发布在  Android
关注(0)|答案(1)|浏览(269)

当我使用谷歌云项目帐户凭据登录,然后一切像(创建新的企业,应用策略,看到注册的设备...)。我可以很容易地实现,但当尝试登录与谷歌云项目帐户创建的企业通过这些企业,我无法执行任何上述操作,因为我得到“403访问被拒绝错误”。
例如:我们的Google云项目帐户名称为:我们xyz@gmail.com已经创建了两个企业,如abc@gmail.com和pqr@gmail.com
但是,当我们尝试在任一企业(abc@gmail.com或www.example.com)中应用策略时pqr@gmail.com,我们会收到如下错误:错误403:access_denied开发者尚未授予您访问此应用的权限。此应用目前正在测试中,尚未通过Google验证。如果您认为您应该拥有访问权限,请联系开发者(xyz @ gmail. com)。
因此,我可以使用www.example.com执行任何操作xyz@gmail.com,但无法使用xyz@gmail.com的子企业(abc@gmail.com或www.example.com)执行任何操作pqr@gmail.com。
为了清楚起见,我已经分享了我的代码。请让我知道我需要修改的地方或者我需要做什么。
企业发布方法:

[GoogleScopedAuthorize(AndroidManagementService.ScopeConstants.Androidmanagement)]
        [HttpPost]
        public async Task<IActionResult> CreateEnterprise([FromServices] IGoogleAuthProvider auth)
        {
            try
            {
                EnterpriseDto enterpriseModel = new();

                #region OAuthFlow
                // Check if the required scopes have been granted. 
                if (await auth.RequireScopesAsync(AndroidManagementService.ScopeConstants.Androidmanagement) is IActionResult authResult)
                {
                    return authResult;
                }

                //The required scopes have now been granted.
                GoogleCredential cred = await auth.GetCredentialAsync();
                var service = new AndroidManagementService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = cred.CreateScoped(AndroidManagementService.Scope.Androidmanagement),
                    ApplicationName = "BluProductsApp"
                });

                //Fetch client information from GCP
                dynamic name = "";
                dynamic email = "";
                if (User.Identity is ClaimsIdentity claimsIdentity)
                {
                    var listk = claimsIdentity.Claims.Select(x => new { x.Type, x.Value }).ToList();
                    name = listk[3].Value;
                    email = User.FindFirstValue(ClaimTypes.Email);
                }

                //var enterpriseRes = _iEmmMapper.GetEnterprises().Where(x=> x.ClientEmail == email);
                //if(enterpriseRes!= null)
                //{
                //    TempData["MsgSignupFailed"] = "There is already an Enterprise exist. Please try with a different mail to add a new Enterprise.";
                //    return View(enterpriseModel);
                //}
                #endregion

                dynamic response = "";
                string enterpriseToken = Convert.ToString(TempData["EnterpriseToken"]) ?? null;
                if (string.IsNullOrEmpty(enterpriseToken))
                {
                    //create signup url
                    var signupData = service.SignupUrls.Create();
                    signupData.AccessToken = cred.UnderlyingCredential.GetAccessTokenForRequestAsync().Result;
                    signupData.ProjectId = ProjectId;
                    signupData.CallbackUrl = _iConfiguration.GetValue<string>("AppSetting:CallBackURL");
                    response = signupData.Execute();

                    //assign signup data to vmodel
                    enterpriseModel.SignupUrlName = response.Name;
                    enterpriseModel.SignupUrlURL = response.Url;

                    //store signupurl name in session
                    HttpContext.Session.SetString("SignupUrlName", Convert.ToString(enterpriseModel.SignupUrlName));

                    //assign client info to model
                    enterpriseModel.ClientName = name;
                    enterpriseModel.ClientEmail = email;

                    //insert data into database
                    var result = _iEmmMapper.CreateUpdateEnterprise(enterpriseModel);
                }
                else
                {
                    //create enterprise
                    var enterpriseData = service.Enterprises.Create(new Enterprise());
                    enterpriseData.AccessToken = cred.UnderlyingCredential.GetAccessTokenForRequestAsync().Result;
                    enterpriseData.ProjectId = ProjectId;
                    enterpriseData.SignupUrlName = HttpContext.Session.GetString("SignupUrlName");
                    enterpriseData.EnterpriseToken = Convert.ToString(TempData["EnterpriseToken"]) ?? null;
                    var enterpriseResponse = enterpriseData.Execute();
                    enterpriseModel.Name = enterpriseResponse.Name;
                    enterpriseModel.EnterpriseToken = enterpriseData.EnterpriseToken;

                    //assign client info to vmodel
                    enterpriseModel.ClientName = name;
                    enterpriseModel.ClientEmail = email;

                    //fetch enterprise from db
                    var resultEnterprise = _iEmmMapper.GetEnterprises();
                    if (resultEnterprise != null)
                    {
                        foreach (var enterprise in resultEnterprise)
                        {

                        //create default policies for [fixed enterprise]
                        string policyName = enterpriseModel.Name + "/policies/" + PolicyId;

                        //set a default policy with all latest changes
                        var appliedPolicyData = service.Enterprises.Policies.Patch(DefaultPolicies(commonPolicies), policyName).Execute();
                        enterpriseModel.PolicyName = policyName;

                            //create User
                            var user = new User
                            {
                                AccountIdentifier = Guid.NewGuid().ToString()
                            };

                            //create enrollmentToken with a with policy name & assign created user
                            EnrollmentToken token = new DemoEnrollmentToken().SetPolicyName(PolicyId).SetUser(user.AccountIdentifier).SetDuration("2592000s");
                            var tokenResponse = service.Enterprises.EnrollmentTokens.Create(token, enterpriseModel.Name).Execute();
                            var eToken = tokenResponse.Value;
                            enterpriseModel.EnrollmentToken = eToken;
                        }
                    }

                    //insert/update data into database
                    var result = _iEmmMapper.CreateUpdateEnterprise(enterpriseModel);
                }
                return View(enterpriseModel);
            }
            catch (Google.GoogleApiException gex)
            {
                string msgErr = "Error in " + this.GetType().ToString();
                _loggerManager.LogError($"{msgErr}{gex.Message}");
                TempData["Failure"] = "There is some technical issue. Please try again.";
                return View(new EnterpriseDto());
            }
            catch (Exception ex)
            {
                string msgErr = "Error in " + this.GetType().ToString();
                _loggerManager.LogError($"{msgErr}{ex.Message}");
                return View(new EnterpriseDto());
            }
        }

企业获取方法:

[HttpGet]
        public IActionResult CreateEnterprise(EnterpriseDto enterpriseDto, string enterpriseToken)
        {
            try
            {
                TempData["EnterpriseToken"] = string.Empty;
                if (!string.IsNullOrEmpty(enterpriseToken))
                {
                    TempData["EnterpriseToken"] = Convert.ToString(HttpContext.Request.Query["enterpriseToken"]);
                    TempData["MsgEnterpriseToken"] = "Google Play signup successful.";
                }
                //
                var result = _iEmmMapper.GetEnterprises();
                if (result != null)
                {
                    foreach (var enterprise in result)
                    {
                        enterpriseDto.Name = enterprise.Name;
                        enterpriseDto.EnrollmentToken = enterprise.EnrollmentToken;
                        enterpriseDto.EnrollmentTokenExpiryDate = enterprise.ModifiedDate.AddMonths(1).ToShortDateString();
                    }
                }
                //
                return View(enterpriseDto);
            }
            catch (Exception ex)
            {
                _loggerManager.LogError($"Something went wrong inside CreateEnterprise get action: {ex.Message}");
                return View(enterpriseDto);
            }
        }

创建企业.cshtml网页:

<form id='fCreateEnterprise' asp-action="CreateEnterprise">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                @if (Model != null)
                {
                    <div class="row" style="display:none;">
                        <div class="col-md-6">
                            <label asp-for=@Model.SignupUrlName class="control-label mt-2"></label>
                            <input asp-for=@Model.SignupUrlName class="form-control" readonly="readonly" />
                        </div>
                        <div class="col-md-6">
                            <label asp-for=@Model.SignupUrlURL class="control-label mt-2"></label>
                            <input asp-for=@Model.SignupUrlURL class="form-control" readonly="readonly" />
                        </div>
                    </div>
                }
                <div class="col-md-4 mt-4 offset-4">
                    <input type="submit" id="btnVerify" value="Verify" class="btn btn-success text-center" />
                    @*<input type="button" id="btnVerification" value="Verification" class="btn btn-success text-center" />*@
                    @if (Model.SignupUrlURL != null)
                    {
                        <a href="@Model.SignupUrlURL" target="_blank" class="btn btn-secondary text-center">Complete Signup</a>
                    }
                    else
                    {
                        <a href="#" target="_blank" class="btn btn-secondary text-center">Complete Signup</a>
                    }
                    <input type="submit" value="Create Enterprise" class="btn btn-primary text-center" />
                </div>
            </form>
siv3szwd

siv3szwd1#

在AM API上创建的企业只能由通过Cloud IAM在您的云项目中注册的唯一服务帐户管理。对于现有EMM合作伙伴,这是推荐的身份验证方法。由于您提到有多个企业,请注意,您可以使用此身份验证方法管理多个企业。
或者,您也可以考虑使用客户管理的企业。quickstart指南也可作为注册企业、创建策略和配置设备的参考。

相关问题