My android project crashed when I called token.jwt for twilio chat - twilio

I am trying to generate access token for twilio chat but got this error:I have been trying to figure out where the error is coming from but can't get it figured out. I will really appreciate your help. Thanks
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zihron.projectmanagementapp, PID: 16355
java.lang.Error: javax.xml.datatype.DatatypeConfigurationException: Provider org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl not found
at javax.xml.bind.DatatypeConverterImpl.<clinit>(DatatypeConverterImpl.java:744)
at javax.xml.bind.DatatypeConverter.<clinit>(DatatypeConverter.java:78)
at javax.xml.bind.DatatypeConverter.printBase64Binary(DatatypeConverter.java:547)
at io.jsonwebtoken.impl.Base64Codec.encode(Base64Codec.java:24)
at io.jsonwebtoken.impl.Base64UrlCodec.encode(Base64UrlCodec.java:22)
at
io.jsonwebtoken.impl.AbstractTextCodec.encode(AbstractTextCodec.java:31)
at io.jsonwebtoken.impl.DefaultJwtBuilder.base64UrlEncode(DefaultJwtBuilder.java:314)
at io.jsonwebtoken.impl.DefaultJwtBuilder.compact(DefaultJwtBuilder.java:282)
at com.twilio.jwt.Jwt.toJwt(Jwt.java:100)
at ZihronChatApp.token.TokenGenerator.getToken(TokenGenerator.java:34)
at com.zihron.projectmanagementapp.ChatActivity.onCreateView(ChatActivity.java:43)
I have my details below:
public AccessToken getToken() {
// Required for all types of tokens
String twilioAccountSid ="AC601f2c7***7ed***640***264c***d0d";
String twilioApiKey = "SK684***dda***c81****6c4a****093**";
String twilioApiSecret ="96****dbc06****b74d50***b9***3*4";
String serviceSid="IS***a29****e24****5d****4b20**3e*";
String identity = "joshua.hamilton#gmail.com";
ChatGrant grant = new ChatGrant();
grant.setServiceSid(serviceSid);
AccessToken token = new AccessToken.Builder(twilioAccountSid,
twilioApiKey, twilioApiSecret)
.identity(identity).grant(grant).build();
Log.e("++==--",""+token.toJwt());
//.identity(identity).grant(grant);
return token;
}

Twilio developer evangelist here.
The Twilio Java library is not intended for use within Android projects.
The issue here is that you should not be storing your credentials within your application. A malicious user could decompile your application, take your credentials and abuse them.
Instead, you should create a server (or use some sort of serverless environment, like Twilio Functions) that can run this code and return the token. You should then make an HTTP request from your Android application to fetch that token. Check out the Twilio Programmable Chat Android Quickstart to see how it's done there.

Related

How to connect the incoming call after accepting a reservation through Twilio Task Router?

I'm able to follow Twilio TaskRouter example to accept reservations:
import { Worker } from 'twilio-taskrouter'
const worker = new Worker(token);
worker.on("reservationCreated", async function (reservation) {
console.log('reserved', reservation)
await reservation.dequeue()
});
The incoming call reservation comes through and reaches the agent properly.
But I'm not clear how to actually answer the incoming call after this. The documentation says calling dequeue() will perform telephony but seems like there are more needs to be done to actually answer the call?
I also tried to create a Twilio Device. But based on my understanding, that requires a TwiML app, but I'm also not sure how to hook up the TwiML with the TaskRouter; nor I'm not sure I'm in the right path.
I actually figured it out by trying many diff SDK and code examples as the docs's not super clear.
Apparently we'd need to create a Device with its access token having the identity of the worker's contact_uri's client id.
"contact_uri":"client:a_worker_user_name"
When creating device access token:
const token = new AccessToken(
twilioAccountSid,
twilioApiKey,
twilioApiSecret,
{ identity: "a_worker_user_name" }
);

Error in SharePoint oAuth Authentication using Sharepoint Online CSOM and PnP in .net core

I am trying to make sharepoint authentication using oAuth(Azure AD App) using Sharepoint Online CSOM and PnP, but it gives error "The given key was not present in the dictionary.". I have created Azure AD App and added API permission for Sharepoint AllSite.FullControl in that app.
I am using trial sharepoint tenant.
Here is my code snippets:
ClientContext _sharepointContaxt = null;
string Username = [Username];
string Password = [Password];
string AppId="67b1845e-88b1-4e6c-b7db-7f1d3abe3b06";
Uri site = new Uri([Sharepoint_site_url]);
using (var authenticationManager = new AuthenticationManager("67b1845e-88b1-4e6c-b7db-7f1e3aae3a06"))
using (_sharepointContaxt = authenticationManager.GetContext(site, Username, SecurePassword(Password)))
{
Web web = _sharepointContaxt.Web;
_sharepointContaxt.Load(web);
_sharepointContaxt.ExecuteQuery();
}
I faced the same "The given key was not present in the dictionary." issue whenever I occasionally sent Post request to Azure AD in a for loop. I'm not sure if this failure scenario is as the same as yours.
One of my debug way is to check the dictionary and see which "given key" was lost. In AuthenticationManager class, there is a private method called AcquireTokenAsync. This method is to request Azure AD to return SPO accessing token, and save it as a Json format in variable tokenResult, and then use GetProperty("access_token") to get token.
If Azure AD did not return SPO token for some reason, access_token might not be available in the tokenResult, result in the error code you saw.
In this case, error message in tokenResult help you to see the reason why Azure AD did not return the token.

Twilio Invalid Access Token Signature (iOS - Swift)

I am using Twilio's latest SDK they released on CocoaPods as of today. I am trying to implement VOIP feature to my app with Twilio Programmable Voice. My backend is .net which also uses the latest release of Twilio Helper Library for C#.
My client code looks like:
fetchAccessToken { (accessToken: String) in
TwilioVoice.register(withAccessToken: accessToken, deviceToken: deviceToken) { (error) in
if let error = error {
NSLog("An error occurred while registering: \(error.localizedDescription)")
}
else {
NSLog("Successfully registered for VoIP push notifications.")
}
}
}
What I get in the console is as following:
voipTestWithTwilio[2431:517236] [ERROR TwilioVoice] Inside register:deviceToken:completion:, failed to register for Twilio push notifications. Error:Invalid access token signature
voipTestWithTwilio[2431:517236] An error occurred while registering: Invalid access token signature
This is the C# code that actually creates the token:
var grant = new VoiceGrant
{
OutgoingApplicationSid = outgoingApplicationSid
};
var grants = new HashSet<IGrant> { { grant } };
var token = new Token(
accountSid: accountSid,
signingKeySid: apiKey,
secret: apiSecret,
identity: identity,
grants: grants
);
return token.ToJwt();
I have been looking for the issue on the internet, nothing helped so far. I have tried contacting them but have not got any response back. I also tried creating new api keys and even a new project for a couple times on Twilio. Can anybody say something about the issue?
UPDATE
I added push notification sid to VoiceGrant and now I’m getting 403 Forbidden.
On Twilio error codes page it is explained as: “The expiration time provided in the Access Token exceeds the maximum duration allowed.” which is definitely not my case. However, I tried passing expiration parameter in Token constructor with various values which didn’t change the result.
The problem is still persisting.
I solved the issue. It was because my server returned the token with quotation mark.
I remember print(token)'ing on client (iOS) to see whether there is encoding issue or something and all I see was a proper token between quotation marks. Since token is a string value, I didn't pay attention to quotation part of it. That's where I was wrong.

Incomplete Linkedin OAuth 2.0 access token response

My question is about OAuth2 access token response from Linkedin api. When I'm trying to get this token I recieve the following response:
{"access_token":"...","expires_in":...}
But the thing is that according to OAuth2 documentation (in 5.1 paragraph) there should be at least one more required parameter - "token_type".
So the question is: could it be somehow customized so the linkedin API will return this parameter with access token response or it is just a departure from the rule and this parameter won't be returned?
Thanks in advance.
I have run into the same issue. According to LinkedIn Docs:
A successful Access Token request will return a JSON object containing the following fields:
access_token — The access token for the user. This value must be kept secure, as per your agreement to the API Terms of Use.
expires_in — The number of seconds remaining, from the time it was requested, before the token will expire. Currently, all access tokens are issued with a 60 day lifespan.
they respond with
{"access_token":"...","expires_in":...}
which violates the standard.
Currently I am using Spring Security 5.0.3 and to fix the issue, I had to monkeypatch one class:
com.nimbusds.oauth2.sdk.token.BearerAccessToken
I will not post the whole class, only a significant part:
public static BearerAccessToken parse(final JSONObject jsonObject)
throws ParseException {
// Parse and verify type
AccessTokenType tokenType;
try {
tokenType = new AccessTokenType(JSONObjectUtils.getString(jsonObject, "token_type"));
} catch (ParseException ex) {
tokenType = AccessTokenType.BEARER;
}
if (!tokenType.equals(AccessTokenType.BEARER))
throw new ParseException("Token type must be \"Bearer\"");
//...
}
I hoped to get answer from Linkedin member since they stated on their site that stackoverflow is a proper place for asking such questions. But since there is no answer from them and I didn't find any relevant information regarding this question I believe that it is just the way they implemented OAuth 2.0 protocol.

Twilio configuration Profile SID

I am using the Twilio Video API. In my node.js I used this code,
var grant = new VideoGrant();
It requires configurationProfileSid but I can't find docs on how to get it?
I think it is a capability token.
But how can I get it using twilio node js?
Or is there any other way to get it?
Twilio developer evangelist here.
Configuration Profiles used to be required, but have been deprecated. So you no longer need the configurationProfileSid. You can give access to particular rooms though.
Here's an example Node.js application that generates access tokens for a Video application. The important part is the route that generates the token:
app.get('/', function(request, response) {
// Create an access token which we will sign and return to the client,
// containing the grant we just created
var token = new AccessToken(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_API_KEY,
process.env.TWILIO_API_SECRET
);
// Assign identity to the token
token.identity = request.query.identity || 'identity';
// Grant the access token Twilio Video capabilities
var grant = new VideoGrant();
grant.room = request.query.room;
token.addGrant(grant);
// Serialize the token to a JWT string
response.send(token.toJwt());
});
This documentation on access tokens should help too.

Resources