For authentication I am using Auth0 AuthenticationApi. In Account Controller, I need to fetch the user_metadata but it's missing. Any alternative to fetch the user_metadata?
AuthenticationApiClient client = new AuthenticationApiClient(new Uri($"https://{_auth0Options.Domain}/"));
var authenticateResponse = await client.GetTokenAsync(new ResourceOwnerTokenRequest
{
ClientId = _auth0Options.ClientId,
ClientSecret = _auth0Options.ClientSecret,
Scope = "openid",
Realm = _auth0Options.Connection,
Username = vm.EmailAddress,
Password = vm.Password
});
var user = await client.GetUserInfoAsync(authenticateResponse.AccessToken);
if (user.UserMetadata != null)
{
// Giving error...any alternative to access the userMetaData ?
}
Yes, as far as I see it now, the legacy call still works. However, I don't have a non-legacy solution yet :(
using (var client = GetClient())
{
var jObject = new JObject(new JProperty("id_token", id_token));
var response = await client.PostAsJsonAsync("tokeninfo", jObject);
if (response.IsSuccessStatusCode)
{
var userProfileJson = JObject.Parse(await response.Content.ReadAsStringAsync());
retVal.user_id = userProfileJson.Value<string>("user_id");
retVal.email = userProfileJson.Value<string>("email");
retVal.user_name = userProfileJson.Value<string>("nickname");
if (userProfileJson.Value<string>("created_at") != null)
{
retVal.created_at = userProfileJson.Value<DateTime>("created_at");
}
var exists = userProfileJson.TryGetValue("user_metadata", out JToken meta);
Related
I am running into a bit of a snag setting up pagination in Google Apps Script. I am trying to use it for Shopify API. Reference links attached.
I attached the code below of what I have so far -
trying to figure out how to use the "While" statement to make it check if there is a Next Page URL
trying to figure out a way to parse the Link in the header. Example below. On pages 2+ there will be a next and previous link. We only need the next
https://shop-domain.myshopify.com/admin/api/2019-07/products.json?limit=50&page_info=eyJkaXJlY3Rpb24iOiJwcmV2IiwibGFzdF9pZCI6MTk4NTgyMTYzNCwibGFzdF92YWx1ZSI6IkFjcm9saXRoaWMgQWx1bWludW0gUGVuY2lsIn0%3D; rel="previous", https://shop-domain.myshopify.com/admin/api/2019-07/products.json?limit=50&page_info=eyJkaXJlY3Rpb24iOiJuZXh0IiwibGFzdF9pZCI6MTk4NTgzNjU0NiwibGFzdF92YWx1ZSI6IkFoaXN0b3JpY2FsIFZpbnlsIEtleWJvYXJkIn0%3D; rel="next
function callShopifyOrderCount() {
var accessToken = 'xxxx';
var store_url = 'https://xxxx.myshopify.com/admin/api/2021-01/orders.json?status=any&fields=created_at,id,name,total-price&limit=20';
var headers = {
"Content-Type": "application/json",
'X-Shopify-Access-Token': accessToken
};
var options = {
"method": "GET",
"headers": headers,
"contentType": "application/json",
"muteHttpExceptions": true,
}
var response = UrlFetchApp.fetch(store_url, options)
// Call the link header for next page
var header = response.getHeaders()
var linkHeader = header.Link;
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
if (responseCode === 200) {
var responseJson = JSON.parse(responseBody);
var objectLength = responseJson.orders.length;
for (var i = 0; i < objectLength; i++) {
var orderId = responseJson.orders[i].id;
var orderPrice = responseJson.orders[i].total_price;
var orderName = responseJson.orders[i].name;
}
} else {
Logger.log(
Utilities.formatString(
"First Request failed. Expected 200, got %d: %s",
responseCode,
responseBody
)
);
// ...
}
// *** NEED TO FIGURE OUT WHILE STATEMENT //
while (Link != null) {
var store_url = linkHeader;
var response = UrlFetchApp.fetch(store_url, options)
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
var header = response.getHeaders()
var linkHeader = header.Link;
if (responseCode === 200) {
var responseJson = JSON.parse(responseBody);
var objectLength = responseJson.orders.length;
for (var i = 0; i < tweetLength; i++) {
var orderId = responseJson.orders[i].id;
var orderPrice = responseJson.orders[i].total_price;
var orderName = responseJson.orders[i].name;
}
}
else {
Logger.log(
Utilities.formatString(
"Second Request failed. Expected 200, got %d: %s",
responseCode,
responseBody
)
);
}
}
}
References:
https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api
https://www.shopify.com/partners/blog/relative-pagination
So I have made a News App using APIs available on the internet. So I had to use different API for each different Category. There are more than 9 categories, So this is making my app load very slow. So, what is the solution to this. How can I only call 2 APIs at the initial state and rest of the others after some time when the app has loaded.
See the code below:
class NewsCard extends StatefulWidget {
#override
_NewsCardState createState() => _NewsCardState();
}
class _NewsCardState extends State<NewsCard>
with SingleTickerProviderStateMixin {
TabController tabController;
static DateTime now = DateTime.now();
String formattedDate;
List newsData;
List topNews1;
List businessNews1;
List worldNews1;
List sportsNews1;
List entertainmentNews1;
List educationNews1;
List tvnews1;
List electionNews1;
List lifeNews1;
bool isLoading = true;
final String toi= "https://timesofindia.indiatimes.com/";
final String topNews =
"API url";
final String sportsNews =
"API url";
final String businessNews =
"API url";
final String worldNews =
"API url ";
final String entertainmentNews =
"API url ";
final String educationNews =
"API url";
final String tvNews =
"API url ";
final String electionNews =
"API url";
final String lifeNews =
"API url";
final String url =
"https://newsapi.org/v2/top-headlines?sources=google-news-in&apiKey=";
Future getData() async {
var response = await http.get(
Uri.encodeFull(url),
headers: {
HttpHeaders.authorizationHeader: ""
},
);
var response1 = await http.get(
Uri.encodeFull(topNews),
);
var response2 = await http.get(
Uri.encodeFull(businessNews),
);
var response3 = await http.get(
Uri.encodeFull(worldNews),
);
var response4 = await http.get(
Uri.encodeFull(sportsNews),
);
var response5 = await http.get(
Uri.encodeFull(entertainmentNews),
);
var response6 = await http.get(
Uri.encodeFull(tvNews),
);
var response7 = await http.get(
Uri.encodeFull(lifeNews),
);
var response8 = await http.get(
Uri.encodeFull(electionNews),
);
var response9 = await http.get(
Uri.encodeFull(educationNews),
);
List data = jsonDecode(response.body)['articles'];
List topNewsData = jsonDecode(response1.body)['stories'];
List businessNewsData = jsonDecode(response2.body)['items'][0]['stories'];
List worldNewsData = jsonDecode(response3.body)['items'][0]['stories'];
List sportsNewsData = jsonDecode(response4.body)['items'][0]['stories'];
List entertainmentNewsData = jsonDecode(response5.body)['items'][0]['stories'];
List tvNewsData = jsonDecode(response6.body)['items'][0]['stories'];
List lifeNewsData = jsonDecode(response7.body)['items'][0]['stories'];
List electionsNewsData = jsonDecode(response8.body)['items'][0]['stories'];
List educationNewsData = jsonDecode(response9.body)['items'][0]['stories'];
setState(() {
newsData = data;
topNews1 = topNewsData;
businessNews1 = businessNewsData;
worldNews1 = worldNewsData;
sportsNews1 = sportsNewsData;
entertainmentNews1 = entertainmentNewsData;
tvnews1 = tvNewsData;
lifeNews1=lifeNewsData;
electionNews1 = electionsNewsData;
educationNews1 = educationNewsData;
isLoading = false; //this is for the initial loading, this is taking too much of time.
});
}
#override
void initState() {
super.initState();
this.getData();
tabController = TabController(vsync: this, length: 9);
}
Inside the Scaffold
isLoading
?Column(....):Column(.....)
Do keep in Mind that i am a beginner in Flutter, So if my method of approach is wrong then kindly request me to do the perfect approach.
Since there is no dependency between different api calls (api call 1 need not wait for api call 0 to finish), better to start them all and await for the results at end. So don't use await for every api call. Instead use Future.wait to wait for all futures at the end. Something like:
Future getData() async {
List<Future> responseFutures = [
http.get(
Uri.encodeFull(url),
headers: {HttpHeaders.authorizationHeader: ""},
),
http.get(
Uri.encodeFull(topNews),
),
http.get(
Uri.encodeFull(businessNews),
),
http.get(
Uri.encodeFull(worldNews),
),
http.get(
Uri.encodeFull(sportsNews),
),
http.get(
Uri.encodeFull(entertainmentNews),
),
http.get(
Uri.encodeFull(tvNews),
),
http.get(
Uri.encodeFull(lifeNews),
),
http.get(
Uri.encodeFull(electionNews),
),
http.get(
Uri.encodeFull(educationNews),
),
];
List responses = await Future.wait(responseFutures);
List data = jsonDecode(responses[0].body)['articles'];
List topNewsData = jsonDecode(responses[1].body)['stories'];
List businessNewsData = jsonDecode(responses[2].body)['items'][0]['stories'];
List worldNewsData = jsonDecode(responses[3].body)['items'][0]['stories'];
List sportsNewsData = jsonDecode(responses[4].body)['items'][0]['stories'];
List entertainmentNewsData = jsonDecode(responses[5].body)['items'][0]['stories'];
List tvNewsData = jsonDecode(responses[6].body)['items'][0]['stories'];
List lifeNewsData = jsonDecode(responses[7].body)['items'][0]['stories'];
List electionsNewsData = jsonDecode(responses[8].body)['items'][0]['stories'];
List educationNewsData = jsonDecode(responses[9].body)['items'][0]['stories'];
setState(() {
newsData = data;
topNews1 = topNewsData;
businessNews1 = businessNewsData;
worldNews1 = worldNewsData;
sportsNews1 = sportsNewsData;
entertainmentNews1 = entertainmentNewsData;
tvnews1 = tvNewsData;
lifeNews1 = lifeNewsData;
electionNews1 = electionsNewsData;
educationNews1 = educationNewsData;
isLoading = false; //this is for the initial loading, this is taking too much of time.
});
}
I am trying to use refresh token when the access token expires. A similar so question is answered here. And a sample code to renew token by an action
And i end up with the following code in the startup.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
//ExpireTimeSpan = TimeSpan.FromSeconds(100),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Events = new CookieAuthenticationEvents()
{
OnValidatePrincipal = async x =>
{
if (x.Properties?.Items[".Token.expires_at"] == null) return;
var logger = loggerFactory.CreateLogger(this.GetType());
var now = DateTimeOffset.UtcNow;
var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
var timeRemaining = tokenExpireTime.Subtract(now.DateTime);
if (timeElapsed > timeRemaining)
{
var httpContextAuthentication = x.HttpContext.Authentication;//Donot use the HttpContext.Authentication to retrieve anything, this cause recursive call to this event
var oldAccessToken = await httpContextAuthentication.GetTokenAsync("access_token");
var oldRefreshToken = await httpContextAuthentication.GetTokenAsync("refresh_token");
logger.LogInformation($"Refresh token :{oldRefreshToken}, old access token:{oldAccessToken}");
var disco = await DiscoveryClient.GetAsync(AuthorityServer);
if (disco.IsError) throw new Exception(disco.Error);
var tokenClient = new TokenClient(disco.TokenEndpoint, ApplicationId, "secret");
var tokenResult = await tokenClient.RequestRefreshTokenAsync(oldRefreshToken);
logger.LogInformation("Refresh token requested. " + tokenResult.ErrorDescription);
if (!tokenResult.IsError)
{
var oldIdToken = await httpContextAuthentication.GetTokenAsync("id_token");
var newAccessToken = tokenResult.AccessToken;
var newRefreshToken = tokenResult.RefreshToken;
var tokens = new List<AuthenticationToken>
{
new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken},
new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken}
};
var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });
var info = await httpContextAuthentication.GetAuthenticateInfoAsync("Cookies");
info.Properties.StoreTokens(tokens);
await httpContextAuthentication.SignInAsync("Cookies", info.Principal, info.Properties);
}
x.ShouldRenew = true;
}
else
{
logger.LogInformation("Not expired");
}
}
}
});
The client setup is as follows
AllowAccessTokensViaBrowser = true,
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
AbsoluteRefreshTokenLifetime = 86400,
AccessTokenLifetime = 10,
AllowOfflineAccess = true,
AccessTokenType = AccessTokenType.Reference
After successfully login, i am getting a 401 for every other request. And the log says
[Identity Server]2017-07-04 10:15:58.819 +01:00 [Debug]
"TjpIkvHQi../cfivu6Nql5ADJJlZRuoJV1QI=" found in database: True
[Identity Server]2017-07-04 10:15:58.820 +01:00 [Debug]
"reference_token" grant with value:
"..9e64c1235c6675fcef617914911846fecd72f7b372" found in store, but has
expired.
[Identity Server]2017-07-04 10:15:58.821 +01:00 [Error] Invalid
reference token. "{ \"ValidateLifetime\": true,
\"AccessTokenType\": \"Reference\", \"TokenHandle\":
\"..9e64c1235c6675fcef617914911846fecd72f7b372\" }"
[Identity Server]2017-07-04 10:15:58.822 +01:00 [Debug] Token is
invalid.
[Identity Server]2017-07-04 10:15:58.822 +01:00 [Debug] Creating
introspection response for inactive token.
[Identity Server]2017-07-04 10:15:58.822 +01:00 [Information] Success
token introspection. Token status: "inactive", for API name: "api1"
Any help would by highly appreciated
UPDATE:
Basically, when the token expires i get a System.StackOverflowException on the following line
var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
UPDATE 2:
Do not use HttpContext.Authentication to retrieve anything. Check my answer below to find the working implementaion
I was working on this for last two days and could not make this work. Funnily, after posting the question here, within 2 hours I make it working :)
Events = new CookieAuthenticationEvents()
{
OnValidatePrincipal = async x =>
{
if (x.Properties?.Items[".Token.expires_at"] == null) return;
var now = DateTimeOffset.UtcNow;
var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
var timeRemaining = tokenExpireTime.Subtract(now.DateTime);
WriteMessage($"{timeRemaining} and elapsed at {timeElapsed}");
if (timeElapsed > timeRemaining)
{
var oldAccessToken = x.Properties.Items[".Token.access_token"];
var oldRefreshToken = x.Properties.Items[".Token.refresh_token"];
WriteMessage($"Refresh token :{oldRefreshToken}, old access token {oldAccessToken}");
var disco = await DiscoveryClient.GetAsync(AuthorityServer);
if (disco.IsError) throw new Exception(disco.Error);
var tokenClient = new TokenClient(disco.TokenEndpoint, ApplicationId, "secret");
var tokenResult = await tokenClient.RequestRefreshTokenAsync(oldRefreshToken);
if (!tokenResult.IsError)
{
var oldIdToken = x.Properties.Items[".Token.id_token"];//tokenResult.IdentityToken
var newAccessToken = tokenResult.AccessToken;
var newRefreshToken = tokenResult.RefreshToken;
var tokens = new List<AuthenticationToken>
{
new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken},
new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken}
};
var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });
x.Properties.StoreTokens(tokens);
WriteMessage($"oldAccessToken: {oldAccessToken}{Environment.NewLine} and new access token {newAccessToken}");
}
x.ShouldRenew = true;
}
}
}
Basically httpContextAuthentication.GetTokenAsync make this recursive, for that reason StackOverflowException occured.
Please let me know if this implementation has any issue
We need to update users claims after they log in to our website. This is caused by changes in the users licenses done by another part of our system.
However I am not able to comprehend how to update the claims without logout/login.
Rigth now this is our client setup
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
//user validation host
Authority = UrlConstants.BaseAddress,
//Client that the user is validating against
ClientId = guid,//if not convertet to Gui the compare from the server fails
RedirectUri = UrlConstants.RedirectUrl,
PostLogoutRedirectUri = UrlConstants.RedirectUrl,
ResponseType = "code id_token token",
Scope = "openid profile email roles licens umbraco_api umbracoaccess",
UseTokenLifetime = false,
SignInAsAuthenticationType = "Cookies",
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = async n =>
{
_logger.Info("ConfigureAuth", "Token valdidated");
var id = n.AuthenticationTicket.Identity;
var nid = new ClaimsIdentity(
id.AuthenticationType,
Constants.ClaimTypes.GivenName,
Constants.ClaimTypes.Role);
// get userinfo data
var uri = new Uri(n.Options.Authority + "/connect/userinfo");
var userInfoClient = new UserInfoClient(uri,n.ProtocolMessage.AccessToken);
var userInfo = await userInfoClient.GetAsync();
userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));
var licens = id.FindAll(LicenseScope.Licens);
nid.AddClaims(licens);
// keep the id_token for logout
nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
n.AuthenticationTicket = new AuthenticationTicket(
nid,
n.AuthenticationTicket.Properties);
_logger.Info("ConfigureAuth", "AuthenticationTicket created");
},
RedirectToIdentityProvider = async n =>
{
// if signing out, add the id_token_hint
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
_logger.Debug("ConfigureAuth", "id_token for logout set on request");
_logger.Debug("ConfigureAuth", "Old PostLogoutRedirectUri: {0}", n.ProtocolMessage.PostLogoutRedirectUri.ToString());
n.ProtocolMessage.IdTokenHint = idTokenHint;
var urlReferrer = HttpContext.Current.Request.UrlReferrer.ToString();
if (!urlReferrer.Contains("localhost"))
{
n.ProtocolMessage.PostLogoutRedirectUri = GetRedirectUrl();
}
else
{
n.ProtocolMessage.PostLogoutRedirectUri = urlReferrer;
}
_logger.Debug("ConfigureAuth", string.Format("Setting PostLogoutRedirectUri to: {0}", n.ProtocolMessage.PostLogoutRedirectUri.ToString()));
}
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
{
n.ProtocolMessage.RedirectUri = GetRedirectUrl2();
n.ProtocolMessage.AcrValues = GetCurrentUmbracoId();
_logger.Debug("ConfigureAuth", string.Format("Setting RedirectUri to: {0}", n.ProtocolMessage.RedirectUri.ToString()));
}
},
}
});
We get our custom claims in SecurityTokenValidated
var licens = id.FindAll(LicenseScope.Licens);
nid.AddClaims(licens);
I do not follow how to get this without doing a login? Any help is highly appreciated.
That's a reminder that you should not put claims into tokens that might change during the lifetime of the session.
That said - you can set a new cookie at any point in time.
Reach into the OWIN authentication manager and call the SignIn method. Pass the claims identity that you want to serialize into the cookie.
e.g.
Request.GetOwinContext().Authentication.SignIn(newIdentity);
any one have the huawei SMS API documentation? (api/sms/sms-list)
I need to know how to talk with this API to get the SMS list:
It must be something like this:
<request>
<PageIndex>1</PageIndex>
<ReadCount>20</ReadCount>
<BoxType>1</BoxType>
<SortType>0</SortType>
<Ascending>0</Ascending>
<UnreadPreferred>0</UnreadPreferred>
</request>
But I got only a error code 100003 as answer. And I don't what that mean.
Thank You,
michel
I have done this on an Huawei E5221 with Python. The error you are getting is because you are not authenticated and need to login first. Then the list can be retrieved.
Also note that all API requests are POST's and not GET's.
Method to login:
def LoginToSMSGateway(sms_gateway_ip, username, password):
api_url = '/api/user/login'
post_data = '<request><Username>'+username+'</Username><Password>'+ base64.b64encode(password) +'</Password>'
r = requests.post(url='http://' + sms_gateway_ip + api_url, data=post_data)
if r.status_code == 200:
result = False
root = ET.fromstring(r.text)
for results in root.iter('response'):
if results.text == 'OK':
result = True
return result
else:
return False
Method to retrieve SMS List (The method will turn the XML results into a Python list of SMS's):
def GetSMSList(sms_gateway_ip):
class SMS:
Opened = False
Message = ''
api_url = '/api/sms/sms-list'
post_data = '<?xml version="1.0" encoding="UTF-8"?><request><PageIndex>1</PageIndex><ReadCount>20</ReadCount><BoxType>1</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>0</UnreadPreferred></request>'
headers = {'Referer': 'http://' + sms_gateway_ip + '/html/smsinbox.html'}
r = requests.post(url='http://' + sms_gateway_ip + api_url, data=post_data, headers=headers)
root = ET.fromstring(r.text)
resultsList = list()
for messages in root.iter('Messages'):
for message in messages:
sms = SMS()
sms.Message = message.find('Content').text
sms.Opened = False if message.find('SmsType').text == '1' else True
resultsList.append(sms)
return resultsList
To use it(The IP and credentials are the default values and need to be secured.) :
if LoginToSMSGateway('192.168.1.1', 'admin', 'admin'):
print 'Logged in.'
smsList = GetSMSList('192.168.1.1')
for sms in smsList:
print sms.Message
Since this the subject has been posted I think the API has changed a bit.
To get the SMS list, no need to login but you do need to get a sessionID and the corresponding Token. You can use that Method to get them.
def GetTokenAndSessionID(sms_gateway_ip):
url = '/html/smsinbox.html'
r = requests.get(sms_gateway_ip + url)
Setcookie = r.headers.get('set-cookie')
sessionID = Setcookie.split(';')[0]
token = re.findall(r'"([^"]*)"', r.text)[2]
return token, sessionID
And then the Method to get the sms list (It's using the first Method to wrap the sessionID and the Token in the headers).
def GetSmsList(sms_gateway_ip):
class SMS:
Opened = False
Message = ''
url = '/api/sms/sms-list'
token,sessionID = GetTokenAndSessionID(sms_gateway_ip)
post_data = '<request><PageIndex>1</PageIndex><ReadCount>20</ReadCount><BoxType>2</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>0</UnreadPreferred></request>'
headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'__RequestVerificationToken': token,
'Cookie': sessionID
}
r = requests.post(sms_gateway_ip + url, data = post_data, headers=headers)
root = ET.fromstring(r.text)
resultsList = list()
for messages in root.iter('Messages'):
for message in messages :
sms = SMS()
sms.Message = message.find('Content').text
sms.Opened = False if message.find('SmsType').text == '1' else True
resultsList.append(sms)
To use it you just need to call it with the ip of the sms gateway: 192.168.8.1
GetSmsList(sms_gateway_ip)
Similar Code in Java hereunder using Apache HTTP Client classes
CloseableHttpClient httpclient = HttpClients.createDefault();
// 1. Have apache HTTPClient manage the cookie containing the SessionID
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// 2. Extract the token
String token = "";
HttpGet hget = new HttpGet("http://192.168.8.1/html/smsinbox.html");
CloseableHttpResponse getRespo = httpclient.execute(hget, httpContext);
try {
StatusLine statusLine = getRespo.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
HttpEntity entity = getRespo.getEntity();
if (entity == null) {
throw new ClientProtocolException("Get response contains no content");
}
long len = entity.getContentLength();
StringTokenizer st = null;
if (len != -1 && len > 250) {
st = new StringTokenizer(EntityUtils.toString(entity).substring(0, 250), "\"");
}
int i = 1;
while (st != null && st.hasMoreTokens()) {
if (i++ == 10) {
token = st.nextToken();
break;
} else {
st.nextToken();
}
}
} finally {
getRespo.close();
}
System.out.println("Token: " + token);
// 3. Get the SMS messages using the Token
HttpPost hpost = new HttpPost("http://192.168.8.1/api/sms/sms-list");
String xmlRequest = "<request><PageIndex>1</PageIndex><ReadCount>1</ReadCount><BoxType>1</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>1</UnreadPreferred></request>";
StringEntity reqEntity = new StringEntity(xmlRequest);
reqEntity.setContentType("text/xml");
hpost.setEntity(reqEntity);
hpost.addHeader("__RequestVerificationToken", token);
CloseableHttpResponse postRespo = httpclient.execute(hpost, httpContext);
try {
StatusLine statusLine = postRespo.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
HttpEntity entity = postRespo.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
System.out.println(EntityUtils.toString(entity));
//Your further processing here.
} finally {
postRespo.close();
}