I want to retrieve user info after authentication with Twitter. For this purpose I'm using LINQ to Twitter library. It's possible to do with this code:
var usersResponse =
(from user in context.User
where user.Type == UserType.Lookup &&
user.ScreenName == "MRade90"
select user).ToList();
var users =
(from user in usersResponse
select new User
{
Name = user.Identifier.ScreenName,
StatusText = user.Status.Text,
PictureUrl = new Uri(user.ProfileImageUrl)
}).FirstOrDefault();
But this is hardcoded with ScreenName set to MRade90. Is it possible to do the same thing for currently authenticated user?
I found it. The current user credentials can be accessed from Credentials property of WinRtAuthorizer class. For example you can use ScreenName like here:
string screenName = auth.Credentials.ScreenName;
I am using
var users =
(from user in twitterCtx1.User
where user.Type == UserType.Lookup &&
//user.UserID == list1
list1.Contains(user.UserID)
select user)
.ToList();
However, I am not able to extract the user IDs and work . Any inputs where I might be going wrong.
Thanks
This is how I do this,
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
AccessToken = twitterToken.Token,
AccessTokenSecret = twitterToken.TokenSecret
}
};
var twitterCtx = new TwitterContext(auth);
var acc = (from user in twitterCtx.Account where user.Type == AccountType.VerifyCredentials select user).FirstOrDefault();
Related
How can I create a Cognito user with the account status confirmed using c#? After a user is created the account status displays FORCE_CHANGE_PASSWORD. Another thing is I need to create user without email address.
AmazonCognitoIdentityProviderClient cognitoProvider =
new AmazonCognitoIdentityProviderClient(region);
string userName = "user";
string tempPassword = "Temp#3434";
string newPassword = "RealPass#2019";
AdminCreateUserRequest adminUserCreateRequest = new AdminCreateUserRequest()
{
UserPoolId = poolId,
Username = userName,
TemporaryPassword = tempPassword
};
AdminCreateUserResponse signUpResponse = await cognitoProvider.AdminCreateUserAsync(adminUserCreateRequest);
Admin InitiateRequest
Dictionary<string, string> initialParams = new Dictionary<string, string>();
initialParams.Add("USERNAME", userName);
initialParams.Add("PASSWORD", tempPassword);
AdminInitiateAuthRequest initialRequest = new AdminInitiateAuthRequest()
{
AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
AuthParameters = initialParams,
ClientId = appClientId_tenantApi,
UserPoolId = poolId
};
AdminInitiateAuthResponse resInitAuth = await cognitoProvider.AdminInitiateAuthAsync(initialRequest);
InitiateAuthRresponse has email as a required attribute.
{[requiredAttributes, ["userAttributes.email"]]}
But the documentation doesn't say so.
For ADMIN_NO_SRP_AUTH: USERNAME (required), SECRET_HASH (if app client is configured with client secret), PASSWORD (required), DEVICE_KEY
Admin Respond to challenge
var authParameters = new Dictionary<string, string>();
authParameters.Add("USERNAME", userName);
authParameters.Add("NEW_PASSWORD", newPassword);
AdminRespondToAuthChallengeRequest adminAuthRequest = new AdminRespondToAuthChallengeRequest()
{
UserPoolId = poolId,
ClientId = appClientId_tenantApi,
ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED,
ChallengeResponses = authParameters,
Session = session
};
cognitoProvider.AdminRespondToAuthChallengeAsync(adminAuthRequest);
I am thinking I may missed some user settings in Cognito to avoid email. Any one have similar experience ? or is this not possible to create user without email ?
During the creation of the user pool, under general settings;attributes as in the photocognito creation on aws one is required to choose the attributes that must be present, i believe in your case the email was selected by default hence the challenge request response you got.
The admin create user request requires the client to confirm the email for purposes of verification that the user owns the email.
A hack for the same would be to allow users to sign themselves up on your cognito configuration, then sign someone up then follow with a username and password, then proceed to confirm them as an admin
var signup = await cognitoClient.SignUpAsync(new SignUpRequest
{
Username = person.Username,
ClientId = cognitoOptions.ClientId,
Password = person.IdNumber,
});
var confirm = await cognitoClient.AdminConfirmSignUpAsync(new AdminConfirmSignUpRequest
{
Username = person.Username,
UserPoolId = cognitoOptions.UserPoolId
});
In case if anyone still looking for answer
Initalize Provider.
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient("*************", "************", Amazon.RegionEndpoint.USWest);
Create user
AdminCreateUserResponse adminCreateUserResponse = await provider.AdminCreateUserAsync(new AdminCreateUserRequest
{
Username = "TestUser",
TemporaryPassword = "TempPassword#1",
UserPoolId = "us-west-**********"
});
Authenticate user
CognitoUserPool userPool = new CognitoUserPool("us-west-***", "***", provider);
CognitoUser user = new CognitoUser("TestUser", "******", userPool, provider, "**********");
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = "TempPassword#1"
};
AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
Vaidate user authentication result and get the user AccessToken
if (authResponse.AuthenticationResult == null)
{
if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
{
//Console.WriteLine("Enter your desired new password:");
string newPassword = "NewPWD#1";// Console.ReadLine();
Dictionary<string, string> att = new Dictionary<string, string>();
att.Add("userAttributes.email", "testemail#xyz.com");
user.Attributes.Add("preferred_username", "TestUser1");
And update the new password using Accesstoken ( post update the User status will be confirmed)
authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
{
SessionID = authResponse.SessionID,
NewPassword = newPassword,
},att);
accessToken = authResponse.AuthenticationResult.AccessToken;
}
I'm trying to get tweets from Twitter but it's not working with me, here is the code:
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore()
{
ConsumerKey = ConfigurationManager.AppSettings["***"],
ConsumerSecret = ConfigurationManager.AppSettings["***"],
AccessToken = ConfigurationManager.AppSettings["***"],
AccessTokenSecret = ConfigurationManager.AppSettings["***"]
}
};
var context = new TwitterContext(auth);
var tweets =
from tw in context.Status
where
tw.Type == StatusType.User &&
tw.ScreenName == "***"
select tw;
// handle exceptions, twitter service might be down
try
{
// map to list
tweets
.Take(3)
.Select(t =>
new Tweets
{
//Username = t.ScreenName,
//FullName = t.User.Name,
TweetText = t.Text,
//FormattedText = ParseTweet(t.Text)
})
.ToList();
}
catch (Exception) { }
every time it fail when I'm trying to read the tweets, the exception is
LinqToTwitter.TwitterQueryException: Bad Authentication data
But I'm sure that the credentials are correct.
and also is it possible to read the posts of another twitter account? like a company account or a celebrate account?
LINQ to Twitter is async, so you should change your query like this:
var tweets =
await
(from tw in context.Status
where
tw.Type == StatusType.User &&
tw.ScreenName == "***"
select tw)
.ToListAsync();
Also, hit a breakpoint after instantiating auth and inspect Credentials to make sure you've populated them correctly.
I want to get the username or user id of the currently logged in user in a UWP app. Below is the code that I am using but it returns null.
var current = users.Where(p => p.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated && p.Type == UserType.LocalUser).FirstOrDefault();
var data = await current.GetPropertyAsync(KnownUserProperties.AccountName);
Username = (string)data;
var users = await User.FindAllAsync(UserType.LocalUser);
var user = (string) await users.FirstOrDefault().GetPropertyAsync(KnownUserProperties.AccountName);
var domain = "";
var host = "";
if (string.IsNullOrEmpty(user))
{
var domainWithUser = (string) await users.FirstOrDefault().GetPropertyAsync(KnownUserProperties.DomainName);
domain = domainWithUser.Split('\\')[0];
user = domainWithUser.Split('\\')[1];
}
This helped me. reference http://codegur.com/33736983/get-environment-variables-in-net-core-uwp
I have two sub-sites in my sharepoint site,SampleSite1 and SampleSite2 under Parentsite called MainSite.
http://xyz.sharepoint.com/sites/MainSite/ - SiteUrl
http://xyz.sharepoint.com/sites/MainSite/SampleSite1 - Subsite1's Url
http://xyz.sharepoint.com/sites/MainSite/SampleSite2 - Subsite2's Url
Each of the Sites have two groups superUser and NormalUser respectively.
The credential uses SiteUrl of MainSite.
SecureString password = new SecureString();
string pwd = "Pass123";
string UserName = "abc#xyz.com";
password = convertToSecureString(pwd);
ClientContext clientContext = new ClientContext("http://xyz.sharepoint.com/sites/MainSite/");
clientContext.Credentials = new SharePointOnlineCredentials(UserName, password);
Incase of adding user to subsite's groups like NormalUser,Can we use the same sharepoint context with above siteUrl to access and perform operations(add/remove user) in groups present under subsites?
If Yes,how can we do it?I already have built code to add or remove user from a sharepoint site group based on some requirement.
public void AddUserToDMSite(string useremail, string securityGroupName)
{
GroupCollection collGroup = SPContext.Web.SiteGroups;
Group oGroup1 = collGroup.GetByName("UserList");
Group oGroup2 = collGroup.GetByName(securityGroupName);
UserCollection oUserCollection1 = oGroup1.Users;
UserCollection oUserCollection2 = oGroup2.Users;
SPContext.Load(oUserCollection1);
SPContext.Load(oUserCollection2);
SPContext.ExecuteQuery();
var uname = oGroup1.Users.GetByEmail(useremail);
var userCheck = oUserCollection2.Where(u => u.Email == useremail).FirstOrDefault();
if (userCheck == null)
{
Microsoft.SharePoint.Client.User oUser2 = oGroup2.Users.AddUser(uname);
}
SPContext.ExecuteQuery();
}
For subsites you can proceed as follows:
Web oWebsite = clientContext.Web;
clientContext.Load(oWebsite, website => website.Webs);
clientContext.ExecuteQuery();
foreach (Web orWebsite in oWebsite.Webs)
{
AddUserToDMSite(useremail, securityGroupName, orWebSite)
}
and change AddUserToDMSite to work with either sites and subsites as:
public void AddUserToDMSite(string useremail, string securityGroupName, Web aWeb)
{
GroupCollection collGroup = aWeb.SiteGroups;
Group oGroup1 = collGroup.GetByName("UserList");
Group oGroup2 = collGroup.GetByName(securityGroupName);
UserCollection oUserCollection1 = oGroup1.Users;
UserCollection oUserCollection2 = oGroup2.Users;
SPContext.Load(oUserCollection1);
SPContext.Load(oUserCollection2);
SPContext.ExecuteQuery();
var uname = oGroup1.Users.GetByEmail(useremail);
var userCheck = oUserCollection2.Where(u => u.Email == useremail).FirstOrDefault();
if (userCheck == null)
{
Microsoft.SharePoint.Client.User oUser2 = oGroup2.Users.AddUser(uname);
}
SPContext.ExecuteQuery();
}
I am using the Google Analytics Api to get web property information from my Analytics account.
When I log into analaytics though, I only have one website, but through the api I get several (old and deleted sites)
My code is like this:
var provider = new WebServerClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = _appId,
ClientSecret = _appSecret
};
var auth = new OAuth2Authenticator<WebServerClient>(provider, x => new AuthorizationState { AccessToken = token });
var analyticsService = new AnalyticsService(auth);
var accounts = analyticsService.Management.Accounts.List().Fetch();
foreach (var account in accounts.Items)
{
var webProperties = analyticsService.Management.Webproperties.List(account.Id).Fetch();
// todo: determine if web property is still in use?
}
From code how can I tell which ones are still active?
So after a bit more digging.
It seems there is no flag or anything like that indicating it has been removed, but if you keep digging into the result set you will notice that at the profile level, a profile that doesn't have child items seems to be a deleted one.
Which makes sense I guess there wouldn't be a profile associated with those that have been removed.
var provider = new WebServerClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = _appId,
ClientSecret = _appSecret
};
var auth = new OAuth2Authenticator<WebServerClient>(provider, x => new AuthorizationState { AccessToken = token });
var analyticsService = new AnalyticsService(auth);
var accounts = analyticsService.Management.Accounts.List().Fetch();
var result = new List<Profile>();
foreach (var account in accounts.Items)
{
var webProperties = analyticsService.Management.Webproperties.List(account.Id).Fetch();
foreach (var webProperty in webProperties.Items)
{
var profiles = analyticsService.Management.Profiles.List(account.Id, webProperty.Id).Fetch();
if (profiles.Items != null && profiles.Items.Any())
{
// these are the ones we want
result.AddRange(profiles.Items);
}
}
}
}