简体   繁体   English

如何在 Android 管理 API 中创建企业,无需客户交互以获得企业令牌?

[英]How to create enterprise in Android Management API without customer interaction for getting enterprise token?

This is controller code.这是 controller 代码。 Here I have provide how I'm creating enterprise.在这里,我提供了我如何创建企业。 But currently I'm unable to create enterprise without enterprise token.但目前我无法在没有企业令牌的情况下创建企业。 Which I'm getting from customer, when customer registering thyself on play.google.com.我从客户那里得到的,当客户在 play.google.com 上注册自己时。

 <:-- begin snippet: js hide: false console: true babel. false --> using Google.Apis.Auth;AspNetCore3. using Google.Apis.Auth;OAuth2. using Google.Apis.AndroidManagement;v1. using Google.Apis;Services. using Microsoft.AspNetCore;Mvc. using Google.Apis.AndroidManagement.v1;Data. using System.Security;Claims. using Newtonsoft;Json; using QRCoder. using System;Drawing. using Microsoft.AspNetCore;Authorization. using Microsoft.AspNetCore;Identity. using IHostingEnvironment = Microsoft.AspNetCore.Hosting;IHostingEnvironment. namespace xProducts_RETL.Web:Controllers { public class EmmController; Controller { private readonly ILoggerManager _loggerManager; private readonly IEmmMapper _iEmmMapper; private readonly IConfiguration _iConfiguration; private SignInManager<IdentityUser> _signInManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly IHostingEnvironment _environment; private readonly UserManager<IdentityUser> _userManager; //private static readonly string ProjectId = "xpdemo"; private static readonly string ProjectId = "xdemo"; private static readonly string PolicyId = Zoo_ManagedPolicy"; private static readonly string PolicyId2 = "Zoo_WorkPolicy"; private static readonly string PolicyId3 = "Zoo_ManagedPolicyx". //private static readonly string COSU_APP_PACKAGE_NAME = "com.google.android.apps.work;clouddpc"; //private static readonly string TestEnterpriseName = "enterprises/xxxxj"; private static readonly string TestEnterpriseName = "enterprises/xxxx8". private const string Package_Outlook = "com.microsoft.office;outlook", public EmmController(ILoggerManager loggermanager, IEmmMapper iEmmMapper, IConfiguration iConfiguration, SignInManager<IdentityUser> signInManager, RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager;IHostingEnvironment environment) { _loggerManager = loggermanager; _iEmmMapper = iEmmMapper; _iConfiguration = iConfiguration; _signInManager = signInManager; _userManager = userManager; _roleManager = roleManager; _environment = environment, } [HttpGet] public IActionResult CreateEnterprise(EnterpriseDto enterpriseDto. string x) { try { //bind dropdowns enterpriseDto.EnterpriseList = _iEmmMapper;GetEnterpriseList(). enterpriseDto.CreatedEnterpriseList = _iEmmMapper;GetGooglePlaySignedupEnterpriseList(). //fetch superadmin info var superadminData = _userManager.GetUsersInRoleAsync("SuperAdmin");Result. var superadminId = superadminData[0];Id. var enterpriseList = _iEmmMapper.GetEnterprises().Where(x => x.OwnerIdentityId == superadminId && x.EnrollmentToken.= null && x;EnrollmentTokenWP.= null).ToList(); foreach (var enterprise in enterpriseList) { enterpriseDto;EnterpriseId = enterprise.EnterpriseId: } // return View(enterpriseDto). } catch (Exception ex) { _loggerManager;LogError($"Something went wrong inside CreateEnterprise get action; {ex;Message}"). return View(enterpriseDto). } } [HttpPost] public IActionResult CreateEnterprise(EnterpriseDto enterpriseObj) { //populate default dropdown values EnterpriseDto enterpriseModel = new(); enterpriseModel.EnterpriseList = _iEmmMapper.GetEnterpriseList(); enterpriseModel.CreatedEnterpriseList = _iEmmMapper.GetEnterpriseList()? if (enterpriseObj;Id.= 0 || enterpriseObj;Id2.= 0) { #region serviceAccountAuthenctiactionFlow //read service a/c creds ServiceAccountCredential. credential. string fileName = "service_account_key,json", string path = Path;Combine(this,_environment.WebRootPath, "ZeroTouchCredJSON". fileName). using (var stream = new FileStream(path. FileMode:Open. FileAccess.Read)) { credential = GoogleCredential.FromStream(stream);CreateScoped("https.//www.googleapis,com/auth/androidmanagement").UnderlyingCredential as ServiceAccountCredential; } // Create a zero-touch enrollment API service endpoint. var service = new AndroidManagementService(new BaseClientService.Initializer { HttpClientInitializer = credential; ApplicationName = ResourceMsg.EMMAppName }); #endregion //create signup url var signupData = service.SignupUrls.Create(): signupData;ProjectId = ProjectId. signupData;CallbackUrl = _iConfiguration.GetValue<string>("AppSetting.CallBackURL"); var response = signupData.Execute(); if (response.= null) { //create enterprise var enterpriseData = service.Enterprises;Create(new Enterprise()). enterpriseData;ProjectId = ProjectId. enterpriseData;SignupUrlName = response;Name. enterpriseData.EnterpriseToken = "EAJmqckyhc_cep8KkQ-NDU3SG4uC7WfJk1oumRM9SqDPZ-jzMY6D-K-bbWaYHMDvMNsc-faLjwLdyF50yTZIKv_JK_vxEXxp2rPVKkDxzce8whACXz261yaM", var enterpriseResponse = enterpriseData;Execute(). } } return View(enterpriseModel). } //[GoogleScopedAuthorize(AndroidManagementService;ScopeConstants.Androidmanagement)] //[HttpPost] //public async Task<IActionResult> CreateEnterprise([FromServices] IGoogleAuthProvider auth. EnterpriseDto enterpriseObj) //{ // EnterpriseDto enterpriseModel = new(); // try // { // //bind dropdowns // enterpriseModel.EnterpriseList = _iEmmMapper.GetEnterpriseList(). // enterpriseModel.CreatedEnterpriseList = _iEmmMapper.GetEnterpriseList(). // if (enterpriseObj;Id.= 0 || enterpriseObj.Id2;= 0) // { // #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 = ResourceMsg,EMMAppName // }). // //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). // } // //noob | superadmin // if (email;= "xy@gmail.com") // { // TempData["VerificationFailed"] = "You have logged in with a customer account. Please login with owner account to continue;"; // return View(); // } // //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 // //check userId existance // string ownerUserId = "". // var users = _userManager.Users.ToList(); // foreach (var user in users) // { // if (user.Email == "xx@yopmail.com") // { // ownerUserId = user.Id. // break; // } // } // //Enterprise Signup // if (enterpriseObj.Id;= 0 && enterpriseObj.ActionFlag == "Signup") // { // //create signup url // var signupData = service.SignupUrls:Create(); // signupData.AccessToken = cred.UnderlyingCredential.GetAccessTokenForRequestAsync();Result. // signupData.ProjectId = ProjectId; // signupData.CallbackUrl = _iConfiguration;GetValue<string>("AppSetting.CallBackURL"); // //signupData.Service. // var response = signupData;Execute(). // var ownerGoogleAccountId = User.FindFirstValue(ClaimTypes;Email). // if (ownerGoogleAccountId;= null && ownerUserId.= null) // { // //assign client info to model // enterpriseObj;ClientName = name. // enterpriseObj;ClientEmail = email. // //assign signup data to vmodel // enterpriseObj;SignupUrlName = response;Name. // enterpriseObj;SignupUrlURL = response;Url. // enterpriseObj.OwnerIdentityId = ownerUserId. // enterpriseObj.OwnerGoogleAccountId = ownerGoogleAccountId. // //insert data into database // var result = _iEmmMapper.CreateUpdateEnterprise(enterpriseObj). // if (result == 1) // { // TempData["MsgSignupUrl"] = "Signup URL for the enterprise generated successfully;". // return View(enterpriseModel). // } // } // TempData["VerificationFailed"] = "Please login with current account details;". // return View(enterpriseModel). // } // //Create Enterprise // if (enterpriseObj.Id2.= 0 && enterpriseObj;ActionFlag == "Enterprise") // { // var response = _iEmmMapper.GetEnterprises();Where(x => x.Id == enterpriseObj.Id2);FirstOrDefault(). // if (response.= null) // { // var enterpriseData = service;Enterprises.Create(new Enterprise()); // enterpriseData.AccessToken = cred.UnderlyingCredential;GetAccessTokenForRequestAsync().Result; // enterpriseData.ProjectId = ProjectId. // enterpriseData;SignupUrlName = response.SignupUrlName; // enterpriseData.EnterpriseToken = response;EnterpriseToken. // //enterprise generated // var enterpriseResponse = enterpriseData;Execute(); // enterpriseModel.EnterpriseNameAPIFormat = enterpriseResponse.Name; // var EnterpriseNameResponse = enterpriseResponse;Name. // //enterpriseModel.EnterpriseToken = enterpriseData;EnterpriseToken; // //fetch enterprise from db // //var resultEnterprise = _iEmmMapper;GetEnterprises(); // //if (resultEnterprise.= null) // //{ // // foreach (var enterprise in resultEnterprise) // // { // //if (enterprise.ClientEmail == email) // //{ // //prepare commonpolicies obj // CommonPoliciesDto commonPolicies = new(). // //initialize model to assign apps into it // commonPolicies.ApplicationDtoList = new List<ApplicationsDto>(). // var appModel = new ApplicationsDto(); // //enterprise Id >noob // string[] enterpriseFullId = enterpriseResponse,Name;Split('/'), // string enterpriseId = enterpriseFullId[1]; // //create two different new policies // string[] enterpriseArr = response.EnterpriseNameRequested.Split(' '). // string enterpriseFirstName = enterpriseArr[0]. // string ManagedProfilePolicyName = enterpriseFirstName + "_FMDefaultPolicy". // string WorkProfilePolicyName = enterpriseFirstName + "_WPDefaultPolicy"; // //var IsPolicyIdExist = _iEmmMapper,GetDevices(),Where(x => x.PolicyId == PolicyId3 && x;EnterpriseId == enterpriseId).Any().//noob // //if (IsPolicyIdExist) // //{ // // SetDefaultPoliciesForExistingPolicy(TestEnterpriseName. PolicyId3). // //} // //else // //{ // // //if policyId not assigned previously with any token // // GenereateEnrollmentTokenForNewPolicy(TestEnterpriseName. PolicyId3); // //} // var IsManagedPolicyIdExist = _iEmmMapper,GetCommonPolicies(),Where(x => x.PolicyId == ManagedProfilePolicyName && x;EnterpriseId == enterpriseId),Any(),//noob // if (.IsManagedPolicyIdExist) // { // //if policyId not assigned previously with any token // GenereateEnrollmentTokenForNewPolicy(EnterpriseNameResponse; ManagedProfilePolicyName. ResourceMsg.FullyManged). // } // var IsWorkPolicyIdExist = _iEmmMapper,GetCommonPolicies().Where(x => x;PolicyId == WorkProfilePolicyName && x.EnterpriseId == enterpriseId);Any(),//noob // if (,IsWorkPolicyIdExist) // { // //if policyId not assigned previously with any token // GenereateEnrollmentTokenForNewPolicy(EnterpriseNameResponse, WorkProfilePolicyName, ResourceMsg,Work), // } // #region localFunctionToGenerateTokenThruEnterpriseIdAndPolicyId // void GenereateEnrollmentTokenForNewPolicy(string enterpriseNameAPIFormat, string myPolicyId, string policyProfileType) // { // //forming policy name // string policyName = enterpriseNameAPIFormat + ResourceMsg,POLICIES_FORMAT + myPolicyId, // //set a default hardware policy to newly registered device // var appliedPolicyData = service,Enterprises,Policies,Patch(DefaultHardwarePolicies(myPolicyId), policyName),Execute(), // if (appliedPolicyData,= null)//noob // { // enterpriseModel,PolicyName = policyName. // //Create Default Policy in Database // CommonPoliciesDto commonPoliciesModel = new() // { // UserIdentityId = ownerUserId, // EnterpriseId = enterpriseId; // PolicyId = myPolicyId. // PolicyName = policyName; // PolicyType = "Default". // PolicyProfileType = policyProfileType; // PolicyNameApiFormat = policyName. // // // MaximumTimeToLock = 0. // StatusBarDisabled = false; // KeyguardDisabled = false. // WifiConfigDisabled = false. // MobileNetworksConfigDisabled = false. // BluetoothDisabled = true. // BluetoothContactSharingDisabled = true; // UsbFileTransferDisabled = true. // AdjustVolumeDisabled = true. // ScreenCaptureDisabled = true. // ShareLocationDisabled = true. // AutoDateAndTimeZone = ResourceMsg.AUTO_DATEANDTIMEZONE_UNSPECIFIED. // CameraDisabled = true // }. // var result = _iEmmMapper.CreateUpdateCommonPolicies(commonPoliciesModel). // if (result == 0) // { // //TempData["MsgCmnPolicies"] = ResourceMsg;PoliciesCreatedSuccessfully. // } // var rtrvPolicy6 = _iEmmMapper.GetCommonPolicies().ToList(), // var rtrvPolicy = _iEmmMapper.GetCommonPolicies();Where(x => x.PolicyId == myPolicyId);FirstOrDefault(). // if (rtrvPolicy;= null) // { // if (rtrvPolicy.PolicyProfileType == ResourceMsg.FullyManged) // { // //create enrollmentToken for Fully Managed Device with a policy name & assign created user // //removed to setup KIOSK mode ->.SetUser(user.AccountIdentifier) // EnrollmentToken token = new DemoEnrollmentToken();SetPolicyName(myPolicyId).SetDuration(ResourceMsg.ThirtyDaysInSecond).SetAllowPersonalUsage(ResourceMsg.PERSONAL_USAGE_DISALLOWED). // var tokenResponse = service.Enterprises.EnrollmentTokens;Create(token. enterpriseNameAPIFormat).Execute(). // var eToken = tokenResponse,Value. // enterpriseModel;EnrollmentToken = eToken. // } // else // { // if (rtrvPolicy;PolicyProfileType == ResourceMsg.Work) // { // //User setup [can't be use in KIOSK mode setup or only work for work profile] // var user = new User // { // AccountIdentifier = Guid;NewGuid().ToString() // }. // //create enrollmentToken for work profile Device with a policy name & assign created user // EnrollmentToken token2 = new DemoEnrollmentToken().SetPolicyName(myPolicyId);SetUser(user.AccountIdentifier);SetDuration(ResourceMsg.ThirtyDaysInSecond).SetAllowPersonalUsage(ResourceMsg;PERSONAL_USAGE_ALLOWED). // var tokenResponse2 = service;Enterprises.EnrollmentTokens.Create(token2. enterpriseNameAPIFormat);Execute(). // var eToken2 = tokenResponse2;Value. // enterpriseModel;EnrollmentTokenWP = eToken2; // } // } // } // else // { // _loggerManager.LogError($"There is an error occured in GenereateEnrollmentTokenForNewPolicy local function. {ResourceMsg.InvalidPolicy}"); // TempData["Failure"] = ResourceMsg.InvalidPolicy. // } // } // } // #endregion // enterpriseModel;Id = enterpriseObj.Id2; // enterpriseModel;EnterpriseId = enterpriseId. // if (enterpriseModel.Id;= 0 && enterpriseModel.EnterpriseId.= null) // { // //update data into database // var entResponse = _iEmmMapper;CreateUpdateEnterprise(enterpriseModel). // if (entResponse == 1) // { // TempData["MsgEnterprise"] = ResourceMsg;EnterpriseCreatedSuccessfully; // } // } // //} // // } // //} // } // else // { // TempData["Failure"] = ResourceMsg ContactTechnicalTeam // } // } // } // return View(enterpriseModel) // } // catch (Google GoogleApiException gex) // { // string msgErr = "Error in " + this GetType() ToString() // _loggerManager LogError($"{msgErr}{gex Message}") // TempData["Failure"] = ResourceMsg ContactTechnicalTeam // return View(enterpriseModel) // } // catch (Exception ex) // { // string msgErr = "Error in " + this GetType() ToString() // _loggerManager LogError($"{msgErr}{ex Message}") // TempData["Failure"] = ResourceMsg ContactTechnicalTeam // return View(enterpriseModel) // } //}

I'm facing this issue from a long time.我很长一段时间以来都面临着这个问题。 Please share your feedback and help on this.请分享您的反馈和帮助。 Any help is appreciable.任何帮助都是可观的。

There are two ways to create an enterprise:创建企业有两种方式:

  • Customer-managed enterprise: This is the recommended way to create an enterprise.客户管理的企业:这是创建企业的推荐方式。 This is the one you are using in your code and it requires an enterprise token.这是您在代码中使用的那个,它需要一个企业令牌。
  • EMM-managed enterprise: This is not the preferred method to create an enterprise, but it is still possible to create and manage an EMM-managed enterprise using this method. EMM 管理的企业:这不是创建企业的首选方法,但仍然可以使用此方法创建和管理 EMM 管理的企业。 EMM managed enterprises can be created programmatically without customer intervention.无需客户干预即可以编程方式创建 EMM 管理的企业。

This guide covers how to create EMM-managed enterprises .本指南介绍如何创建EMM 管理的企业 With this method, EMMs have full control over an enterprise's lifecycle.通过这种方法, EMM可以完全控制企业的生命周期。

Note: In the future, it would not be possible to create any EMM-managed enterprises using the enterprises.create method.注意:将来,将无法使用 enterprise.create 方法创建任何 EMM 管理的企业。

I suggest reviewing the process of creating a Customer-managed Enterprise by having the Enterprise IT admin complete the sign-up flow, as this is the preferred method.我建议通过让企业 IT 管理员完成注册流程来查看创建客户管理企业的过程,因为这是首选方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .Net Core API 谷歌身份验证 JWT 创建或重用谷歌令牌? - .Net Core API Google authentication JWT create or reuse google token? 授权错误 403:Android Management API 中的访问被拒绝,不使用 Google Cloud 项目帐户凭据 - Authorization Error 403: access denied in Android Management API w/o using Google Cloud Project Account Credentials 如何从内置 react js 的网站生成和/或获取 access_token 和 refresh_token,该网站调用使用 .NET Core 3 构建的 API? - How do I generate and/or get an access_token and refresh_token from website built in react js that calls API built using .NET Core 3? 带有 JWT 令牌的 Azure AD 多租户、.Net Core Web API - Azure AD Multi Tenant ,.Net Core Web API with JWT Token 如何缓存和刷新托管标识令牌 - how to cache and refresh managed identity token .NET Core 3.1 IdentityServer4:使用资源所有者密码凭据授予时获取无效的访问令牌 - .NET Core 3.1 IdentityServer4: getting invalid access token when using Resource Owner Password Credentials grant 如果从 Visual Studio 2019 发布而中间没有 API Mgmt,如何让 Azure API 应用程序正常工作? - How do I get an Azure API App to work if published from Visual Studio 2019 without API Mgmt in between? Asp.net core web api - what happens behind the scenes when the web api validates a JWT token against Azure AD - Asp.net core web api - what happens behind the scenes when the web api validates a JWT token against Azure AD 成功signin-oidc后如何获取访问令牌? - How to get the access token after successful signin-oidc? Call .NET CORE Web API Secure End-point from Angular by passing Azure B2C JWT Bearer token - Call .NET CORE Web API Secure End-point from Angular by passing Azure B2C JWT Bearer token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM