I want to get access token from refresh token to send email in the server
But I get 400,"Bad Request" error.
here is the code I use on client side,
var CLIENT_ID = 'A';
var CLIENT_SECRET = 'B';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
var SCOPES = 'https://mail.google.com/';
function initClient() {
gapi.client.init({
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function() {
gapi.auth2.getAuthInstance().grantOfflineAccess().then(offline);
}, function(error) {
});
}
function offline(rtn) {
var refreshToken = rtn.code;
}
and here is the c# .net code I use on the server side to get access token
var secrets = new ClientSecrets
{
ClientId = "A",
ClientSecret = "B"
};
HttpClient xclient = new HttpClient();
xclient.BaseAddress = new Uri("https://www.googleapis.com");
var refreshMessage = new HttpRequestMessage(HttpMethod.Post, "/oauth2/v4/token")
{
Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("client_id", secrets.ClientId),
new KeyValuePair<string, string>("client_secret", secrets.ClientSecret),
new KeyValuePair<string, string>("refresh_token", refreshToken),
new KeyValuePair<string, string>("grant_type", "refresh_token")
})
};
Task.Run(async () =>
{
var response = await xclient.SendAsync(refreshMessage);
if (response.IsSuccessStatusCode)
{
var tokenResponse = await response.Content.ReadAsStringAsync();
}
}).GetAwaiter().GetResult();
What could be wrong?
Related
I want Access token for social login users with out password and password grant in ABP framework version 4.3 and .Net core 6.
IEnumerable<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("Client_Id",_configuration["AuthServer:ClientId"]),
new KeyValuePair<string, string>("UserName", userName),
new KeyValuePair<string, string>("Password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
ResponseTokenDTO response = new ResponseTokenDTO();
using (var httpClient = new HttpClient())
{
var identityUrl = _configuration["AuthServer:Authority"];
var url = identityUrl + "/connect/token";
using (var conn = new FormUrlEncodedContent(postData))
{
conn.Headers.Clear();
conn.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response1 = await httpClient.PostAsync(url, conn);
var userDetails = await _appUserRepository.FindAsync(r => r.UserName == userName);
if (response1.IsSuccessStatusCode)
{
result = await response1.Content.ReadAsStringAsync();
}
}
}
How to Get token with out password for google or apple login users because mobile team sharing email address for those users. with out token user not able to access APIs.
var tokenValue = "";
try
{
var claims = new Claim[] {
new (JwtRegisteredClaimNames.Sub, identityUser.Id.ToString()),
new (JwtRegisteredClaimNames.Email, identityUser.Email)
};
var signingCredentials = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecretKey)),
SecurityAlgorithms.HmacSha256);
var Token = new JwtSecurityToken(
_jwtOptions.Issuer,
_jwtOptions.Audience,
claims,
null,
DateTime.UtcNow.AddDays(1),
signingCredentials
);
tokenValue = new JwtSecurityTokenHandler().WriteToken(Token);
}
I tried above code but that token is not accepting ABP.
When trying to get a new access token, using the refresh token from v2, I now receive a very long token that looks like an encrypted key of some sort. Initially, it just used to be a straight forward access_token of almost the same length as the refresh_token. Is this now the new access_token to use going forward when sending an Uber request on behalf of a customer? Or how do I retrieve the actual access_token I should use in my Uber request, i.e. the one that used to be of almost the same length as the refresh token.
Below is a screenshot of the response I get using Postman.
POSTMAN Screenshot
Below is the C# sourcecode snippet method am calling to retrieve the access_token.
public async Task WebServerAsyncRefresh(string clientId, string clientSecret, string redirectUri, string RefreshToken)
{
if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException("clientId");
if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret");
if (string.IsNullOrEmpty(redirectUri)) throw new ArgumentNullException("redirectUri");
if (string.IsNullOrEmpty(RefreshToken)) throw new ArgumentNullException("refreshToken");
if (!Common.IsValidUri(redirectUri)) throw new ArgumentException("Invalid redirectUri");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "refresh_token"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("redirect_uri", redirectUri),
new KeyValuePair<string, string>("refresh_token", RefreshToken)
});
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(TokenUrl),
Content = content
};
var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
if (responseMessage.IsSuccessStatusCode)
{
var authToken = JsonConvert.DeserializeObject<AuthToken>(response);
AccessToken = authToken.access_token;
RefreshToken = authToken.refresh_token;
}
else
{
//TODO: Create appropriate error response
//var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
//throw new ForceAuthException(errorResponse.error, errorResponse.error_description);
throw new Exception("error");
}
}
I'm trying to get an authorization token for the Twitter REST api but it seems I'm doing something wrong. Is there something wrong with my code?
//Authorization
var customerKey = "xxxxxxxxxx";
var customerSecret = "xxxxxxxxxxxxxxxxxxx";
var b64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", WebUtility.UrlEncode(customerKey), WebUtility.UrlEncode(customerSecret))));
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token");
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", b64);
req.Content = new FormUrlEncodedContent(new Dictionary<string, string>() {
{ "grant_type", "client_credentials" }
});
var token = "";
using (var res = await http.SendAsync(req))
{
if (res.IsSuccessStatusCode)
token = Regex.Match(await res.Content.ReadAsStringAsync(), "\"access_token\":\"([^\"]+)").Groups[1].Value;
}
http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer ", token);
In response I'm getting this message:
{"errors":[{"code":99,"message":"Unable to verify your credentials","label":"authenticity_token_error"}]}
First up I am aware that the api is not supported.
https://stackoverflow.com/questions/16707164/is-there-a-google-play-music-api
I have been attempting to reverse engineer some of the apis in the above post. These have been the only real source of information as no where else documents it.
I have successfully been able to implement a oauth token retrieval system.
However when I pass my token To the following I get Forbidden Error 403
Url =
https://play.google.com/music/services/streamingloadalltracks?format=jsarray
Headers =
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(String.Format("GoogleLogin auth={0}", _token));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);
Code
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(paramObj.Base);
client.Timeout = TimeSpan.FromSeconds(5);
if (!paramObj.skipAuth)
{
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(String.Format("GoogleLogin auth={0}", _token));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);
}
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("sdch"));
try
{
if (paramObj.post)
{
return client
.PostAsync(paramObj.method + paramObj.queryString, paramObj.content)
.Result
.Content
.ReadAsStringAsync()
//.ReadAsByteArrayAsync()
.Result;
}
else
{
return client
.GetAsync(paramObj.method + paramObj.queryString)
.Result
.Content
.ReadAsStringAsync()
//.ReadAsByteArrayAsync()
.Result;
}
}
catch (Exception exception)
{
return null;
}
}
Question is why isnt this working. I have been looking into the other apis and they implement the same calls(i think my python is pretty rusty)
Token Generator.
public string Oauth2AuthorizeUrl =>
string.Format(
"{0}?response_type=code&client_id={1}&redirect_uri={2}&scope={3}&access_type=offline",
GooglePlayAuthorizeMethod,
ClientId,
HttpUtility.UrlEncode(GooglePlayAuthorizeRedirectURL),
GooglePlayAuthorizeScope
);
public void Oauth2RetrieveToken(string code)
{
var querystring = string.Format(
"?response_type=code&code={0}client_id={1}&client_secret={3}&redirect_uri={2}&grant_type=authorization_code",
code,
ClientId,
HttpUtility.UrlEncode(GooglePlayAuthorizeRedirectURL),
ClientSecret
);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://accounts.google.com");
client.Timeout = TimeSpan.FromSeconds(5);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("client_id", ClientId),
new KeyValuePair<string, string>("client_secret", ClientSecret),
new KeyValuePair<string, string>("redirect_uri", GooglePlayAuthorizeRedirectURL),
new KeyValuePair<string, string>("grant_type", "authorization_code")
});
var result = client
.PostAsync(GooglePlayRequestToken , content)
.Result
.Content
.ReadAsStringAsync()
.Result;
var value = JObject.Parse(result);
var libs = User.Libs;
libs.GooglePlayPassword = value["access_token"].ToString();
User.UpdateSettings(libs);
}
}
Check out my attempt of an google play music API here (https://github.com/coman3/Google.Music)).
It's working perfectly when it comes to authentication and calls (although does not support 2 factor auth).
I am getting this exception while trying to do a post call on a ASP.NET Web API. I am calling this from a Windows Universal App:
Type
'<>f__AnonymousType0`3[System.String,System.String,System.String]'
cannot be serialized. Consider marking it with the
DataContractAttribute attribute.
Here is my code:
var loginData = new { grant_type = "password", username = name, password = pass };
var queryString = "grant_type = password, username = " + name + ", password = " + pass;
HttpClient httpClient = new HttpClient();
try
{
string resourceAddress = "http://localhost:24721/Token";
//int age = Convert.ToInt32(this.Agetxt.Text);
//if (age > 120 || age < 0)
//{
// throw new Exception("Age must be between 0 and 120");
//}
string postBody = Serialize(loginData);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage wcfResponse = await httpClient.PostAsync(resourceAddress,
new StringContent(queryString, Encoding.UTF8));
}
Best guess is, you're getting that error because the serializer you're using doesn't support anonymous types. I would recommend trying to use Json.Net, which handles them nicely. I believe you can include it from NuGet.
If you reference the library in your project then you could modify your code like so:
var loginData = new { grant_type = "password", username = name, password = pass };
HttpClient httpClient = new HttpClient();
try
{
string resourceAddress = "http://localhost:24721/Token";
string postBody = Newtonsoft.Json.JsonConvert.SerializeObjectloginData);
var content = new StringContent(postBody, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage wcfResponse = await httpClient.PostAsync(resourceAddress, content);
}
I found the solution. i updated the post data as key value pair and it worked.
using (var client = new HttpClient())
{
string resourceAddress = "http://localhost:24721/Token";
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", name),
new KeyValuePair<string, string>("password", pass)
};
var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
var tokenServiceResponse = await client.PostAsync(resourceAddress, requestParamsFormUrlEncoded);
var responseString = await tokenServiceResponse.Content.ReadAsStringAsync();
var responseCode = tokenServiceResponse.StatusCode;
var responseMsg = new HttpResponseMessage(responseCode)
{
Content = new StringContent(responseString, Encoding.UTF8, "application/json")
};
return responseMsg;
}