Deploying Gmail Apis Project Authentification probleme

柔情痞子 提交于 2019-12-02 08:10:11
Amine Ramoul

Finally I have found a solution (one of X) by my self so let begin:

First we generate the authorization url manually, look:

Response.Redirect("https://accounts.google.com/o/oauth2/v2/auth?"+
                "redirect_uri="+ WebConfigurationManager.AppSettings["RedirectUrl"].ToString() + "&" +
                "prompt=consent&"+
                "response_type=code&"+
                "client_id=" + WebConfigurationManager.AppSettings["ClientID"].ToString() + "&" +
                "scope=https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.modify&"+
                "access_type=offline"
                );

after that the RedirectUrl which I put on web config will be start after authentication and get a Code as parameter in the link (url with parameter Code), so now you just need to get token access, so lets see this code:

 protected async void Page_Load(object sender, EventArgs e)
            {

                if (Request["code"] != null && Session["credential"] ==null)
                {
                    var result = await getTokenResponse(Request["code"].ToString()); // here we get the code posted by google

                }

            }
private static string[] Scopes = { GmailService.Scope.GmailReadonly, GmailService.Scope.GmailModify };
        async Task<TokenResponse> getTokenResponse(String Code)
        {
            Code = Code.Replace("#", "");
            string redirectUri = WebConfigurationManager.AppSettings["RedirectUrl"].ToString();
            var init2 = new GoogleAuthorizationCodeFlow.Initializer();
            ClientSecrets cli = new ClientSecrets(); 
            cli.ClientId = WebConfigurationManager.AppSettings["ClientID"].ToString(); // init the Client_ID
            cli.ClientSecret = "ClientSecret"; // init the Client_Secret
            init2.ClientSecrets = cli;
            init2.Scopes = Scopes;
            init2.DataStore = null; // you dont need to store token cause we w'll store it in Session object
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(init2); /// init the flow which w'll get the token object 
            CancellationToken cancellationToken = default(CancellationToken);
            var token = await flow.ExchangeCodeForTokenAsync("me", Code, redirectUri, cancellationToken); 
            Response.Write(token);

            UserCredential credential = new UserCredential(flow, "me", token); // and know we have the credential 
            Session["credential"] = credential;
            return token;
        }

note:

  1. this solution is for multi-client application.
  2. for all requests with google apis we have: just a text or Json text returned by handlers.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!