CognitoAuthentication Extension for .NET with Unity (StartWithSrpAuthAsync()) issue - unity3d

After importing the AWS-SDK for .NET dll's including the AWS.Extension.CognitoAuthentication into Unity 2018.2, I am having a problem with the StartWithSrpAuthAsync function taken from AuthenticateWithSrpAsync provided by https://aws.amazon.com/blogs/developer/cognitoauthentication-extension-library-developer-preview/
Code from site:
public async void AuthenticateWithSrpAsync()
{
var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(),
FallbackRegionFactory.GetRegionEndpoint());
CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
CognitoUser user = new CognitoUser("username", "clientID", userPool, provider);
string password = "userPassword";
AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
{
Password = password
}).ConfigureAwait(false);
}
}
I want a button script to take in a username and password from the user and authenticate it with the UserPool I created in Cognito.
Button Script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Amazon;
using Amazon.Runtime;
using Amazon.CognitoIdentityProvider;
using Amazon.Extensions.CognitoAuthentication;
public class test : MonoBehaviour {
public string userName;
public string userPassword;
public string clientID;
public string poolID;
public AuthFlowResponse authResponse;
public CognitoUserPool userPool;
public AmazonCognitoIdentityProviderClient provider;
public CognitoUser user;
void Start()
{
}
public void OnClick()
{
try
{
AuthenticateWithSrpAsync();
}
catch(Exception ex)
{
Debug.Log(ex);
}
}
public async void AuthenticateWithSrpAsync()
{
RegionEndpoint CognitoIdentityRegion = RegionEndpoint.USEast1;
provider = new AmazonCognitoIdentityProviderClient(null, CognitoIdentityRegion);
userPool = new CognitoUserPool(poolID, clientID, provider, null);
user = new CognitoUser(userName, clientID, userPool, provider);
string name = user.Username.ToString();
Debug.Log(name);
authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() {
Password = userPassword
}).ConfigureAwait(false);
Debug.Log(user.SessionTokens.IdToken);
Debug.Log("Success");
}
}
The app client does not require a secret key.
App Client
https://imgur.com/a/NUzBghb
The User status is confirmed/enabled and the email is verified.
User
https://imgur.com/lsnG5tT
What ends up happening is the script runs until it gets to:
authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() {
Password = userPassword
}).ConfigureAwait(false);
Debug.Log(user.SessionTokens.IdToken);
Debug.Log("Success");
And does absolutely nothing afterwards. Neither of the debugs show in the console as well as any Error or warning messages.
Unity Console:
https://imgur.com/Hxpcmoj
I have looked through the StackOverflow questions as well as every other resource I could find on google. I have also replicated this in Unity 2017.3
I'm using .NetFramework 4.6

Try checking the checkbox "Enable username-password(non-SRP)...shown in the image in the link https://imgur.com/a/NUzBghb.

I don't think it is related to Unity as the same code is working fine at my end. Can you try following:
_provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), );

Related

Invalid Credential When Sign In Facebook SDK To Firebase/Unity

I try to implement Facebook Authentication on my Unity project. So, after experimenting a few things i could make the Email Authentication works fine. But, when i tried to implement the Facebook Authentication it said "Invalid Credential". Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Auth;
using Facebook.Unity;
public class facebookAuth : MonoBehaviour
{
private void Awake() {
FB.Init(initCallBack,OnUnityHide);
}
void initCallBack(){
if(!FB.IsInitialized)
FB.ActivateApp();
}
void OnUnityHide(bool show){
if(show)
FB.ActivateApp();
}
public void facebookLogin(){
if(FB.IsLoggedIn){
FB.LogOut();
}
var perms = new List<string>(){"email","public_profile"};
FB.LogInWithReadPermissions(perms,facebookResult);
}
void facebookResult(ILoginResult result){
if(FB.IsLoggedIn){
AccessToken token = result.AccessToken;
Credential credential = FacebookAuthProvider.GetCredential(token.TokenString);
firebaseFacebook(credential);
}
}
void firebaseFacebook(Credential token){
FirebaseAuth.DefaultInstance.SignInWithCredentialAsync(token).ContinueWith(task=>{
if(task.IsCanceled){
Firebase.FirebaseException e = task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
errorMessage("Canceled : ",(AuthError)e.ErrorCode);
}
if(task.IsFaulted){
Firebase.FirebaseException e = task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
errorMessage("Faulted : ",(AuthError)e.ErrorCode);
}
Debug.Log(task.Result.DisplayName + " " + task.Result.UserId);
});
}
void errorMessage(string str, AuthError error)
{
string msg = error.ToString();
print(str+msg);
}
}
Your code looks correct to my reading. Make sure Facebook is enabled in the Firebase Console and the proper credentials have been filled out:
(I forget this all the time, especially if I have to enter things like the App Secret).
If this doesn't help, it would be useful to have any additional logging (or a copy of the error message) if possible.
--Patrick

Xamarin.Auth: Using Facebook oauth, how to redirect to my app?

I've just started using Xamarin.Auth and I want to enable Facebook login via oauth.
Here is my config:
public static string ClientId = "client id";
public static string ClientSecret = "client secret";
public static string Scope = "email";
public static string AuthorizeUrl = "https://m.facebook.com/dialog/oauth";
public static string RedirectUrl = "https://www.facebook.com/connect/login_success.html";
public static string AccessTokenUrl = "https://m.facebook.com/dialog/oauth/token";
Code for initiating the authentication:
public class AuthenticationPageRenderer : PageRenderer
{
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear (animated);
var auth = new OAuth2Authenticator (
Constants.ClientId,
Constants.ClientSecret,
Constants.Scope,
new Uri (Constants.AuthorizeUrl),
new Uri (Constants.RedirectUrl),
new Uri (Constants.AccessTokenUrl)
);
auth.Completed += OnAuthenticationCompleted;
PresentViewController (auth.GetUI (), true, null);
}
async void OnAuthenticationCompleted (object sender, AuthenticatorCompletedEventArgs e)
{
Debug.WriteLine ("AUTH Completed!");
if (e.IsAuthenticated) {
}
}
}
Seems to work fine, but instead of redirecting the user to https://www.facebook.com/connect/login_success.html, I want to redirect him back to my app again. Any help much appreciated!
Best,
Sascha
You can "redirect back" to your app again by simply invoking your own method to display the app's page you want to show to your user like this.
async void OnAuthenticationCompleted (object sender, AuthenticatorCompletedEventArgs e)
{
Debug.WriteLine ("AUTH Completed!");
if (e.IsAuthenticated) {
//invoke the method that display the app's page
//that you want to present to user
App.SuccessfulLoginAction.Invoke();
}
}
In your App.cs
public static Action SuccessfulLoginAction
{
get
{
return new Action(() =>
{
//show your app page
var masterDetailPage = Application.Current.MainPage as MasterDetailPage;
masterDetailPage.Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(MainPage)));
masterDetailPage.IsPresented = false;
});
}
}
Assuming that MainPage is the page you wanted to show after successful login. I am using Xamarin.Forms with MasterDetailPage to display pages in my example which maybe different from your app but the concept is the same.
Just call DismissViewController (true, null) in your OnAuthenticationCompleted method. Or use the async equivalent:
async void OnAuthenticationCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
Debug.WriteLine("AUTH Completed!");
await DismissViewControllerAsync(true);
if (e.IsAuthenticated)
{
}
}

How to create a user using microstrategy SDK in java (External Security Module)

My goal is to create user using microstrategy SDK and assign filters and groups to the user.
I have a java class CreateUser & SSOESM from SDK. Do I have to create a plugin of the create user class and deploy it in microstrategy intelligence server.
public class CreateUser {
public static WebIServerSession sessionInfo;
public static final String loginName = "NewUser";
public static final String password= "";
public static final String fullName= "New User";
public static final String description="New User Created Programattically";
/* The following information is required to login and manipulate the User management API */
/* iServerName is the IServer we are connecting to */
public static final String iServerName = "localhost";
/* projectName is the project name we are connecting to */
public static final String projectName = "";
/* loginName is the user name we use to login the project */
public static final String adminLoginName = "administrator";
/* loginPasswd is the password we use to login the project */
public static final String adminLoginPasswd = "";
public static void main(String[] args) {
sessionInfo = getServerSession(iServerName, projectName, adminLoginName, adminLoginPasswd);
UserBean user = null;
try {
//Instantiate a new user
user = (UserBean)BeanFactory.getInstance().newBean("UserBean");
user.setSessionInfo(sessionInfo);
user.InitAsNew();
//Fetch properties for the user
WebUser ua = (WebUser) user.getUserEntityObject();
WebStandardLoginInfo loginInfo = ua.getStandardLoginInfo();
//Set basic user information
ua.setLoginName(loginName);
ua.setFullName(fullName);
user.getObjectInfo().setDescription(description);
loginInfo.setPassword(password);
//Set other properties
Calendar cal = Calendar.getInstance();
cal.set(2012, 11, 21);
Date d = cal.getTime();
loginInfo.setPasswordExpirationDate(d); //Password expires on November 21, 2012
loginInfo.setPasswordExpirationFrequency(90); //90 days to expire
loginInfo.setPasswordExpiresAutomatically(true); //If set to false, password never expires
loginInfo.setStandardAuthAllowed(true); //The user can log in using standard auth
user.save();
} catch (WebBeanException ex) {
System.out.println("Error creating a user: " + ex.getMessage());
}
}
public static WebIServerSession getServerSession(String serverName, String Project, String loginName, String password) {
WebIServerSession sessionInfo = null;
try {
WebObjectsFactory woFact = WebObjectsFactory.getInstance();
sessionInfo = woFact.getIServerSession();
sessionInfo.setServerName(serverName);
sessionInfo.setProjectName(Project);
sessionInfo.setLogin(loginName);
sessionInfo.setPassword(password);
sessionInfo.setApplicationType(EnumDSSXMLApplicationType.DssXmlApplicationCustomApp);
//Create a new session
sessionInfo.getSessionID();
} catch (WebObjectsException ex) {
System.out.println("Error creating a sesion");
}
return sessionInfo;
}
}
My goal is when a user try to logon the user should be created on the fly using the sdk classes.
I have to create a plugin and configure the plugin to use the java class you have created as an ESM.
https://lw.microstrategy.com/msdz/MSDZ_World2015/docs/projects/WebSDK/output/HTML5/Content/topics/esm/specifying_the_custom_esm_to_use.htm
With that said its important to understand that the actions you are performing are very expensive. They may degrade the user experience if you are attempting to provide a fast SSO experience. Depending on the implementation you have it may be better to create a custom task, which can be fired when the user authenticates with the third party application. This task can perform all the actions you are describing, and then return a session state. Which can be used in any subsequent connections to MicroStrategy Web.

unity 3D - How to fill a form and send it to an email address

I have an app for Android and iOS.
I'd like to fill a form and send it to an email address.
Basically, it's to get some feedback.
But first, is it possible?
Thanks a lot.
Assuming you are using C#, yes this is possible.
This SO question might help you. One of the answers claim to have a working code as follows:
I just successfully sent an email from Unity 3D using the following code:
using System.Net;
using System.Net.Mail;
using UnityEngine;
public class SendMail : MonoBehaviour {
public string sender = "me#mymailaccount.com";
public string receiver = "me#mymailaccount.com";
public string smtpPassword = "mysmtppassword";
public string smtpHost = "mail.mymailacount.com";
// Use this for initialization
private void Start() {
using (var mail = new MailMessage {
From = new MailAddress(sender),
Subject = "test subject",
Body = "Hello there!"
}) {
mail.To.Add(receiver);
var smtpServer = new SmtpClient(smtpHost) {
Port = 25,
Credentials = (ICredentialsByHost)new NetworkCredential(sender, smtpPassword)
};
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
smtpServer.Send(mail);
}
}
}

Uploading image to Google Drive using GWT-Google Picker

I am trying to upload an image to Google Drive using Google Picker user interface. So far i have been unsuccessful.
This is the code that i am using :
private void onCreatePicker(ViewId viewId) {
final Picker picker = PickerBuilder.create()
.setTitle("Subir imagen a Google Drive")
.addView(viewId)
.addView(DocsUploadView())
.setLocale("es")
.setOAuthToken(token_oauth2)
.setDeveloperKey(DEVELOPER_KEY)
.setCallback(buildPickerCallback(viewId))
.build();
picker.setVisible(true);
}
private JavaScriptObject DocsUploadView() {
return com.ip.gae.gartla.shared.DocsUploadView.create();
}
I request your help on what could i be missing.
Thank you for your time,
Regards,
UPDATE: It seems that my application scope was wrong. In order to generate the correct oAuth2Token, you must declare the scope which you want to generate the token for:
The following its the method I am using to generate the token:
private void tokenOauth2() {
AuthRequest req = new AuthRequest(AUTH_URL, CLIENT_ID)
.withScopes(GOOGLE_DRIVE_SCOPE); // Can specify multiple scopes here
Auth.get().login(req, new Callback<String, Throwable>() {
#Override
public void onSuccess(String token) {
token_oauth2 = token;
}
#Override
public void onFailure(Throwable caught) {
// The authentication process failed for some reason, see caught.getMessage()
}
});
}
And here it is the GOOGLE_DRIVE_SCOPE variable that i am using:
String GOOGLE_DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
So, for now this is working for me. I have attached the solution so if someone finds it out interesting enough. :-)