问题
when i use the app in local (on executing with visual studio) there is no probleme, but when i deploy my project the authentification doesn't work. the probleme is situated here :
string path = HostingEnvironment.MapPath("~/App_Data");
FileDataStore file = new FileDataStore(path);
credential =new GoogleWebAuthorizationBroker().AuthorizeAsync(
new ClientSecrets
{
ClientId = "Client_ID",
ClientSecret = "Client_Secret"
},
Scopes,
"me",
CancellationToken.None
, file
).Result;
回答1:
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:
- this solution is for multi-client application.
- for all requests with google apis we have: just a text or Json text returned by handlers.
来源:https://stackoverflow.com/questions/51466654/deploying-gmail-apis-project-authentification-probleme