Agora Always token expired when using unity Token generators - unity3d

I make video chatting use agora
https://docs.agora.io/en/video-calling/develop/integrate-token-generation?platform=unity
I made it by following the guide above.
Play UnityEditor and Create a token with a token generator and start join channel.
But Channel Join is fail and I receive "Error code:109 msg:channel key expired"
It's a new token make by token generator, but I don't know why it's being expired.
sombody help me. thx.
private string appId = "my_agora_consone_appId";
private string appCertificate = "my_agora_consone_appCertificate ";
private string channelName = "vdch57";
private string uid = UserInfo.Instance.userKey.ToString();
private string userAccount = "User account";
private int expirationTimeInSeconds = 3600;
public string MakeToken(string channelName)
{
AccessToken token = new AccessToken(appId, appCertificate, channelName, uid);
string token2 = SignalingToken.getToken(appId, appCertificate, userAccount, expirationTimeInSeconds);
token.addPrivilege(Privileges.kJoinChannel, Convert.ToUInt32(expirationTimeInSeconds));
string result = token.build();
return result;
}

Related

Is there a way to register a data asset in Azure Data Catalog via api without user-login?

My app gets a token and can make api calls to the ADC like searching. But the request for registration of new asset fails, because the field "LastRegisterdBy" must not be null/empty and has to correspond to current user.
However the token does not contain any user information (AccessToken().Result.UserInfo.DisplayableId is null).
I mostly followed the get started get-started project MS provides (https://github.com/Azure-Samples/data-catalog-dotnet-get-started/blob/master/Program.cs)
But i use
AcquireTokenAsync(resourceUri, clientCredential).ConfigureAwait(false)
instead of
AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always)).
This so nobody has to enter his credentials. The goal is to run the code in ssis package, which will execute on a weekly basis to catch any updates in the data automatically.
This is the outline of my code:
class Program
{
static string clientIDFromAzureAppRegistration = "";
static string clientSecret = "";
static AuthenticationResult authResult = null;
static string catalogName = "catalog";
static void Main(string[] args)
{
var authResult = AccessToken();
string upn = authResult.Result.UserInfo.DisplayableId;
var id = RegisterDataAsset(authResult, SampleJson("test", upn));
}
static async Task<AuthenticationResult> AccessToken()
{
if (authResult == null)
{
//Resource Uri for Data Catalog API
string resourceUri = "https://api.azuredatacatalog.com";
//To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID
string clientId = clientIDFromAzureAppRegistration;
string clientS = clientSecret;
// Create an instance of AuthenticationContext to acquire an Azure access token
var authority = "https://login.microsoftonline.com/52497ec2-0945-4f55-8021-79766363dd96";
var authContext = new AuthenticationContext(authority);
var clientCredential = new ClientCredential(clientId, clientS);
// Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
// AcquireToken takes a Client Id that Azure AD creates when you register your client app.
authResult = await authContext.AcquireTokenAsync(resourceUri, clientCredential).ConfigureAwait(false);
}
return authResult;
}
static string RegisterDataAsset(Task<AuthenticationResult> authResult, string json){
...
}
static HttpWebResponse SetRequestAndGetResponse(HttpWebRequest request, Task<AuthenticationResult> authResult, string payload = null){
...
}
static string SampleJson(string name, string upn){
...}
With upn = authResult.Result.UserInfo.DisplayableId; i get:
{"error":{"code":"InvalidPropertyValue","message":"Invalid input value for one of the properties. Path: 'properties.lastRegisteredBy.upn'. Details: Value cannot be null, empty or consists entirely of whitespaces."}}
Wit upn = "test#user":
{"error":{"code":"InvalidLastRegisteredBy","message":"LastRegisteredBy is different from the current user."}}
I found the solution, its quite simple:
The user-name of the app is: clientIDFromAzureAppRegistration + "#" + tenantId.

Creating a Signed URL for Google Cloud Storage

We have an ERP application running on GCP .
For downloading data spanning more than three months or so ,we're uploading a file on GCS. Now i want to create a signed url so that to give limited access to the end users .
I have been trying this. But i get this error :
Signature does not match. Please check your Google secret key.
Can anyone tell how to go about this?
private static final int EXPIRATION_TIME = 5;
private static final String BASE_URL = "https://storage.googleapis.com";
private static final String httpVerb = "GET";
/*
* private static final String BUCKET = "my_bucket"; private static final String
* FOLDER = "folder";
*/
private final AppIdentityService identityService = AppIdentityServiceFactory.getAppIdentityService();
public String getSignedUrl(String bucket, final String fileName, String contentTpe) throws Exception {
final long expiration = expiration();
final String unsigned = stringToSign(bucket, expiration, fileName, contentTpe);
final String signature = sign(unsigned);
return new StringBuilder(BASE_URL).append("/").append(bucket).append("/").append(fileName)
.append("?GoogleAccessId=").append(clientId()).append("&Expires=").append(expiration)
.append("&Signature=").append(URLEncoder.encode(signature, "UTF-8")).toString();
}
private static long expiration() {
final long unitMil = 1000l;
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, EXPIRATION_TIME);
final long expiration = calendar.getTimeInMillis() / unitMil;
return expiration;
}
private String stringToSign(String bucket, final long expiration, String filename, String contentType) {
final String contentMD5 = "";
final String canonicalizedExtensionHeaders = "";
final String canonicalizedResource = "/" + bucket + "/" + filename;
final String stringToSign = httpVerb + "\n"+ contentMD5 + "\n" + contentType + "\n" + expiration + "\n"
+ canonicalizedExtensionHeaders + canonicalizedResource;
return stringToSign;
}
protected String sign(final String stringToSign) throws UnsupportedEncodingException {
final SigningResult signingResult = identityService.signForApp(stringToSign.getBytes());
final String encodedSignature = new String(Base64.encodeBase64(signingResult.getSignature()), "UTF-8");
return encodedSignature;
}
protected String clientId() {
return identityService.getServiceAccountName();
}
URL signing code is a bit tricky because by its nature it can be difficult to know what you've gotten wrong, other than just seeing that it's wrong. There are a few general tips that make it easier:
First, if possible, consider using URL signing functions in the google-cloud libraries. For example, the Java google-cloud library provides a Storage.signURL method, and you can use it like this:
URL signedUrl = storage.signUrl(
BlobInfo.newBuilder(bucketName, blobName).build(),
2, TimeUnit.DAYS);
Second, if you look at the error message, you'll notice that there's a <StringToSign> section. This section contains the exact string that GCS would calculate a signature for. Make sure that the string you're signing matches this string exactly. If it doesn't, that's your problem.
In your code's particular case, I didn't find the problem, but it might be that you're including a content-type line when signing the string, but GET requests don't provide a Content-Type header. It's just an idea, though, since I don't see your invocation of getSignedUrl.

How to get user email, public_profile from facebook access_token

I'm building a windows phone 8.1 app that allow user to login facebook account.
There is my code:
string productId = "myproductid";
string facebookAppId = "myfacebookappid";
string redirectUri = "msft-"+productId+"://authorize";
string scope = "public_profile,email"; // What you want to fetch from the facebook user
string responseType = "token"; // Other response types possible
UriBuilder authUri = new UriBuilder("https://www.facebook.com/dialog/oauth");
authUri.Query = "client_id=" + facebookAppId + "&redirect_uri=" + redirectUri + "&scope=" + scope + "&response_type=" + responseType;
var success = await Windows.System.Launcher.LaunchUriAsync(uriToLaunch);
And code in App.xaml.cs:
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
if (args.Kind == ActivationKind.WebAuthenticationBrokerContinuation)
{
App.MobileService.LoginComplete(args as WebAuthenticationBrokerContinuationEventArgs);
}
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(eventArgs.Uri.Fragment);
string fbAccessToken = decoder.GetFirstValueByName("#access_token");
/* Now you can use the access token to interact with the Facebook API */
}
}
But how to get user's email and profile from "fbAccessToken"?
Thanks.
You can use the graph APIs of facebook
graph.facebook.com/me?access_token={0}
Please refer this link - https://developers.facebook.com/docs/graph-api/using-graph-api/v2.3
Add scope/Extended Permission to get user profile etc.,
string scope ="user_about_me,read_stream,publish_actions,user_birthday,offline_access,email"

OAuthRequestValidator Access Token and Access Token Secret

I am trying to add an account to QuickBooks Online using Intuit IPP:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0200_DevKits_for_Intuit_Partner_Platform/0100_IPP_.NET_DevKit/Query_Filters/QuickBooks_Online
How do I get the access token and the access token secret? Here is my code:
class Program
{
static string appToken = "xxx";
static string oAuthConsumerKey = "xxx";
static string oAuthConsumerSecret = "xxx";
static void Main(string[] args)
{
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(appToken, "", oAuthConsumerKey, oAuthConsumerSecret);
ServiceContext context = new ServiceContext(oauthValidator, appToken, "1234", IntuitServicesType.QBD);
DataServices dataServices = new DataServices(context);
Account account = new Account();
account.Desc = "TEST PLEASE DELETE";
string guid = Guid.NewGuid().ToString("N");
guid = guid.Substring(0, 30);
account.Name = guid;
account.Type = Intuit.Ipp.Data.Qbd.AccountTypeEnum.Liability;
account.TypeSpecified = true;
account.Subtype = "Accounts Payable";
Account resultAccount = dataServices.Add(account) as Account;
}
}
I figured it out. Look at step 6 here:
http://ippblog.intuit.com/blog/2012/09/ode-to-oauth-and-rest-apis-and-how-i-love-thee-not.html
Joseph,
For Future reference and for others the documentation for your question is located here:
IPP Oauth Documentation
regards,
Jarred

DotNetOpenAuth Claimed Identifier from Facebook is never the same

I'm using DotNetOpenAuth v3.5.0.10357 and each time a user authenticates against Facebook I get a different claimed identifier back. The token looks to be encrypted so I assume DNOA is somehow encrypting the token along with the expiry. Can anyone confirm this? Or am I using it wrong:
public ActionResult FacebookLogOn(string returnUrl)
{
IAuthorizationState authorization = m_FacebookClient.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
return new FacebookAuthenticationResult(m_FacebookClient, returnUrl);
}
else
{
// TODO: can we check response status codes to see if request was successful?
var baseTokenUrl = "https://graph.facebook.com/me?access_token=";
var requestUrl = String.Format("{0}{1}", baseTokenUrl, Uri.EscapeDataString(authorization.AccessToken));
var claimedIdentifier = String.Format("{0}{1}", baseTokenUrl, authorization.AccessToken.Split('|')[0]);
var request = WebRequest.Create(requestUrl);
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
var token = RelyingPartyLogic.User.ProcessUserLogin(graph, claimedIdentifier);
this.FormsAuth.SignIn(token.ClaimedIdentifier, false);
}
}
return RedirectAfterLogin(returnUrl);
}
}
Here's the code for FacebookAuthenticationResult:
public class FacebookAuthenticationResult : ActionResult
{
private FacebookClient m_Client;
private OutgoingWebResponse m_Response;
public FacebookAuthenticationResult(FacebookClient client, string returnUrl)
{
m_Client = client;
var authorizationState = new AuthorizationState(new String[] { "email" });
if (!String.IsNullOrEmpty(returnUrl))
{
var currentUri = HttpContext.Current.Request.Url;
var path = HttpUtility.UrlDecode(returnUrl);
authorizationState.Callback = new Uri(String.Format("{0}?returnUrl={1}", currentUri.AbsoluteUri, path));
}
m_Response = m_Client.PrepareRequestUserAuthorization(authorizationState);
}
public FacebookAuthenticationResult(FacebookClient client) : this(client, null) { }
public override void ExecuteResult(ControllerContext context)
{
m_Response.Send();
}
}
Also, I am using the RelyingPartyLogic project included in the DNOA samples, but I added an overload for ProcessUserLogin that's specific to facebook:
public static AuthenticationToken ProcessUserLogin(FacebookGraph claim, string claimedIdentifier)
{
string name = claim.Name;
string email = claim.Email;
if (String.IsNullOrEmpty(name))
name = String.Format("{0} {1}", claim.FirstName, claim.LastName).TrimEnd();
return ProcessUserLogin(claimedIdentifier, "http://facebook.com", email, name, claim.Verified);
}
It looks as though FacebookClient inherits from WebServerClient but I looked for the source on GitHub and I don't see a branch or a tag related (or at least not labeled) with the corresponding v3.5 version.
Facebook does not support OpenID. Claimed Identifier is an OpenID term. Facebook uses OAuth 2.0, so you're mixing up OpenID and OAuth.
Facebook sends a different access token every time, which is normal for the OAuth protocol. You have to use the access token to query Facebook for the user id that is consistent on every visit.
I think you need to add the offline_access permission in the token request as well, see https://developers.facebook.com/docs/reference/api/permissions/