Yahoo BBAuthen with authentication session? - yahoo

I'm trying to use yahoo BBA with my web application, but I'm always get fail with yahoo authentication problem.
Here is my odd code:
YahooLogin.aspx.cs
protected void ImageButtonYahoo_Click(object sender, ImageClickEventArgs e)
{
// Create an instance of Yahoo.Authentication
Yahoo.Authentication auth = new Authentication(strApplicationID, strSecret);
// Redirect the user to the use sign-in page
Response.Redirect(auth.GetUserLogOnAddress().ToString());
}
And end-point url: BBAuth.cs
protected void Page_Load(object sender, EventArgs e)
{
bool success = false;
// Retrieve this user's authentication object we've stored in the session state
Yahoo.Authentication auth = Session["Auth"] as Yahoo.Authentication;
if (auth == null)
{
// We have a problem with the current session, abandon and retry
Session.Abandon();
Response.Redirect("ErrorPage.aspx");
}
// Check if we are returning from login
if (Request.QueryString["token"] != null && Request.QueryString["token"].Length > 0)
{
// Make sure the call is valid
if (auth.IsValidSignedUrl(Request.Url) == true)
{
success = true;
// Save the user token. It is valid for two weeks
auth.Token = Request.QueryString["token"];
}
}
// Redirect if we succeeded
if (success == true)
{
Response.Redirect("Default.aspx");
}
else
{
Response.Redirect("SignInError.aspx");
}
}
Response.Redirect("ErrorPage.aspx"); always execute, someone can tell me what is missing in my code.
Thanks,
Nguyen

add this after auth.token ="-------------------"
auth.UpdateCredentials();
try this.

Related

Implement Salesforce Authentication (OAuth) in Xamarin Forms App

This article explains if anyone wants to integrate mobile app with Salesforce App and require to authenticate the app with salesforce OAuth
iOS Implementation-
Step 1: To implement Deep Link define URL Schemes in info.plist according to connected app : The callback URL
Defining URL Schemes
Step 2- Implement 'OpenUrl' method in AppDelegate to receive the deep link call in your app
public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
{
var deepLinkURL = url;
url = null;
App myApp = App.Current as myApp.App;
if (myApp != null && deepLinkURL != null)
{
LandingPage.DeepLinkURL = deepLinkURL;
}
return true;
}
Step 3- Now you have to check whether user is coming first time or already authenticated:
public async static Task HandleDeepLink()
{
//await SecureStorage.SetAsync(AppConstant.userId, "");
/* Deep Link
* Check if user is same
* user is already loggedIn
* Token expired
*/
try
{
string data = DeepLinkURL.ToString();
if (data.Contains("userId"))
{
// extract and save all the parameters
userId = HttpUtility.ParseQueryString(DeepLinkURL.Query).Get("userId");
// if user not authenticated OR if different user
isSameAsLastUser = await oAuth.ValidateUser(userId);
if (isSameAsLastUser)
{
// is already logged in
var isUserLoggedIn = await oAuth.IsUserLoggedIn();
if (isUserLoggedIn)
{
// navigate to scan
await SecureStorage.SetAsync(AppConstant.uniqueId, uniqueId);
Application.Current.MainPage = new NavigationPage(new MainPage());
}
else
{
Application.Current.MainPage = new NavigationPage(new Authentication());
}
}
else
{
// clear previous values in secure storage
AppConfig.SaveSFParameters("false");
Application.Current.MainPage = new NavigationPage(new Authentication());
}
}
// Handle oAuth
//Extract the Code
else if (data.Contains("code"))
{
var code = HttpUtility.ParseQueryString(DeepLinkURL.Query).Get("code");
/*Exchange the code for an access token
* Save token
* LoggedInTrue
*/
if (CrossConnectivity.Current.IsConnected)
{
var authInfo = await oAuth.GetAccessToken(code);
Console.WriteLine("auth token - " + authInfo.AccessToken);
oAuth.SaveAuthInfo(authInfo);
// save user info | set user logged in to true
AppConfig.SaveSFParameters(userId,"true");
// retrieve all the parameters and pass here
Application.Current.MainPage = new NavigationPage(new MainPage(userId));
}
else
{
Device.BeginInvokeOnMainThread(async () =>
{
await Application.Current.MainPage.DisplayAlert(AppConstant.Alert, Resource.Resources.AlertMissingConnectivity, AppConstant.Ok);
});
}
}
else if (data.Contains("error"))
{
var error = HttpUtility.ParseQueryString(DeepLinkURL.Query).Get("error");
//TODO: where the user should be redirected in case of OAuth error
}
}
catch(Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
Application.Current.MainPage.DisplayAlert("Alert", "There is some error while redirecting user to scan app, Please contact administrator", "Ok");
});
}
}
}
public partial class Authentication : ContentPage
{
protected override void OnAppearing()
{
base.OnAppearing();
if (CrossConnectivity.Current.IsConnected)
{
var authUrl = Common.FormatAuthUrl(AppConfiguration.authEndPointURL,
ResponseTypes.Code, AppConfiguration.clientId,
HttpUtility.UrlEncode(AppConfiguration.redirectUri));
Browser.OpenAsync(new Uri(authUrl), BrowserLaunchMode.SystemPreferred);
}
}
}
Step 4 - Once user is authenticated successfully salesforce returns the authorization code
Step 5- Now you have to make salesforce API call to retrieve the access token by supplying the authorization code
Step 6- Once you receive the access toekn then save access token, refresh token in your app using 'Xamarin SecureStorage'
async public static void SaveAuthInfo(AuthToken authInfo)
{
try
{
await SecureStorage.SetAsync("oauth_token", authInfo.AccessToken);
await SecureStorage.SetAsync("oauth_Id", authInfo.Id);
await SecureStorage.SetAsync("oauth_InstanceUrl", authInfo.InstanceUrl);
await SecureStorage.SetAsync("oauth_RefreshToken", authInfo.RefreshToken);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
// Possible that device doesn't support secure storage on device.
}
}
Step 7 - Now redirect user to landing page

Sign in Issues with SkyDrive API for Windows Phone App

I am creating a WP7 app with SkyDrive Access to it. I am using the SkyDrive API for it. When I am trying to login, it is showing 'Inalid Request' Error. Can anyone tell me what is wrong with my code?
private void login_Click()
{
LiveAuthClient auth = new LiveAuthClient("signInButton1.ClientId");
auth.LoginCompleted +=
new EventHandler<LoginCompletedEventArgs>(MoreScopes_LoginCompleted);
auth.LoginAsync(new string[] { "wl.signin", "wl.basic", "wl.skydrive", "wl.skydrive_update " });
}
void MoreScopes_LoginCompleted(object sender, LoginCompletedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
LiveConnectSession session = e.Session;
LiveConnectClient client = new LiveConnectClient(session);
infoTextBlock.Text = "Signed in.";
}
else if (e.Error != null)
{
infoTextBlock.Text = "Error signing in: " + e.Error.ToString();
}
}
private void signInButton1_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
login_Click();
}
Check this:
LiveAuthClient auth = new LiveAuthClient("signInButton1.ClientId");
it should be:
LiveAuthClient auth = new LiveAuthClient(signInButton1.ClientId);

Twitter, OAuth, Hammock, TweetSharp and Windows Phone 7

I've been trying for days to get OAuth working with Twitter in my Windows Phone app, but all the information I find is out dated or difficult to follow. I eventually got somewhere when I found this blog post http://samjarawan.blogspot.co.uk/2010/09/building-real-windows-phone-7-twitter_18.html which got me all the way to getting the access token, at which point it failed.
My code is almost identical to the one in the blog post, pretty much just changed the consumer key and consumer secret. Even their app doesn't work. It displays the Twitter login screen fine, and successfully authenticates, but in the RequestAccessToken function, it fails at this point:
if (String.IsNullOrEmpty(twitteruser.AccessToken) || String.IsNullOrEmpty(twitteruser.AccessTokenSecret))
{
Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
return;
}
The really annoying thing is the message box only shows the Unicode replacement character (�) and nothing else. I also checked the response.StatusCode and it is OK, so there is no error as far as I can tell.
If someone could help me out with this, that would be great. I've seen other tutorials which require the user type in a PIN, but I haven't been able to get any of those to work either.
EDIT: I've just tried getting TweetSharp to work, but once again it fails to get the access token. Here is the code I'm using for TweetSharp:
public partial class TwitterAuthorisationPage : PhoneApplicationPage
{
private const string consumerKey = "myKey";
private const string consumerSecret = "mySecret"; // These are the correct values for my app
private const string requestTokenUri = "https://api.twitter.com/oauth/request_token";
private const string oAuthVersion = "1.0a";
private const string authorizeUri = "https://api.twitter.com/oauth/authorize";
private const string accessTokenUri = "https://api.twitter.com/oauth/access_token";
private const string callbackUri = "http://bing.com";
private TwitterService twitterService = new TwitterService(consumerKey, consumerSecret);
private OAuthRequestToken _requestToken = null;
public TwitterAuthorisationPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
twitterService.GetRequestToken((requestToken, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
_requestToken = requestToken;
Dispatcher.BeginInvoke(() => BrowserControl.Navigate(twitterService.GetAuthorizationUri(requestToken)));
}
else
{
Dispatcher.BeginInvoke(() => MessageBox.Show("Failed to connect to Twitter. Please try again.\n" + response.StatusDescription));
}
});
}
private void ConfirmButton_Click(object sender, RoutedEventArgs e)
{
twitterService.GetAccessToken(_requestToken, PINEntry.Text, (accessToken, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
//These lines just print ?
System.Diagnostics.Debug.WriteLine(accessToken.Token);
System.Diagnostics.Debug.WriteLine(accessToken.TokenSecret);
twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
twitterService.VerifyCredentials((user, verifyResponse) =>
{
if (verifyResponse.StatusCode == HttpStatusCode.OK)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(user.Name));
}
else
{
// Fails here
Dispatcher.BeginInvoke(() => MessageBox.Show("Failed to connect to Twitter. Please try again.1\n" + verifyResponse.StatusDescription));
}
});
}
else
{
Dispatcher.BeginInvoke(() => MessageBox.Show("Failed to connect to Twitter. Please try again.0\n" + response.StatusDescription));
}
});
}
}
EDIT 2: Could it be to do with this? https://dev.twitter.com/blog/ssl-upgrade-for-twitterapi
I worked it out! It turns out Twitter was returning the access token Gzipped. Using the method described in the blog post, I had to change the second RestClient to be constructed like so:
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true,
SilverlightAcceptEncodingHeader = "gzip",
DecompressionMethods = DecompressionMethods.GZip
};
And now it works!
I am having the same problem but I didn't understand your solution, could you explain a bit more where you changed the rest client?
-----EDIT----
I finally was able to make it work with TweetSharp.
I downloaded the source code and added the lines you mentioned to the rest client configuration it uses and the compiled the project again.
Since i cannot push my changes to that github, I upload the dll here. TweetSharp recompiled dll
This is the code I use which with it works
// Step 1 - Retrieve an OAuth Request Token
Service.GetRequestToken((requestToken, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
Request = requestToken;
Uri uri = Service.GetAuthorizationUri(requestToken);
Dispatcher.BeginInvoke(() =>
{
Browser.Navigate(uri);
}
);
}
});
//Step 2, get the pincode
string html = Browser.SaveToString(); //gets the DOM as a string
Regex expression = new Regex(#"<code>(?<word>\w+)</code>");
Match match = expression.Match(html);
string pin = match.Groups["word"].Value;
if (pin != "")
{
loginTwitter(pin); //we login with the pin extracted
}
//step 3, get access tokens from twitter
private void loginTwitter(string pin)
{
Service.GetAccessToken(Request, pin, processAccessToken);
}
public void processAccessToken(OAuthAccessToken access, TwitterResponse Response){
if (Response.StatusCode == HttpStatusCode.OK)
{
if (access != null)
{
Access = access; // Store it for reuse
Service.AuthenticateWith(access.Token, access.TokenSecret);
}
}
}

setting HttpContext.Current.User

I am developing an asp.net mvc 3.0 application which has a simple authentication process. User fills a form which is sent to server by ajax call and gets response, but the problem here is that using the following method :
FormsAuthentication.SetAuthCookie(person.LoginName,false);
is not enough to fill 'HttpContext.Current.User' and it needs the below method to be run :
FormsAuthentication.RedirectFromLoginPage("...");
Problem here is that as i mentioned, the loggin form uses an ajax form, and get responses with json, so redirecting is not possible.
How could I fill 'HttpContext.Current.User' ?
Thanks.
Update :
Here is register method :
[HttpPost]
public ActionResult Register(Person person)
{
var q = da.Persons.Where(x => x.LoginName == person.LoginName.ToLower()).FirstOrDefault();
if (q != null)
{
ModelState.AddModelError("", "Username is repettive, try other one");
return Json(new object[] { false, this.RenderPartialViewToString("RegisterControl", person) });
}
else
{
if (person.LoginName.ToLower() == "admin")
{
person.IsAdmin = true;
person.IsActive = true;
}
da.Persons.Add(person);
da.SaveChanges();
FormsAuthentication.SetAuthCookie(person.LoginName,false);
return Json(new object[] { true, "You have registered successfully!" });
}
}
FormsAuthentication doesn't support immediate setting of user's identity, but you should be able to fake it by something like this:
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(person.LoginName),
new string[] { /* fill roles if any */ } );
Here is the version I ended up using, which is based on the answer by #AdamTuliper-MSFT. It is only meant to be used right after logging in, but before redirect, to allow other code to access HttpContext.User.
Don't do anything if already authenticated
Doesn't modify the cookie, since this should only be used for the lifetime of this request
Shorten some things, and a little safer with userdata (should never be null, but...)
Call this after you call SetAuthCookie(), like below:
// in login function
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
AuthenticateThisRequest();
private void AuthenticateThisRequest()
{
//NOTE: if the user is already logged in (e.g. under a different user account)
// then this will NOT reset the identity information. Be aware of this if
// you allow already-logged in users to "re-login" as different accounts
// without first logging out.
if (HttpContext.User.Identity.IsAuthenticated) return;
var name = FormsAuthentication.FormsCookieName;
var cookie = Response.Cookies[name];
if (cookie != null)
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null && !ticket.Expired)
{
string[] roles = (ticket.UserData as string ?? "").Split(',');
HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket), roles);
}
}
}
Edit: Remove call to Request.Cookies, as #AdamTuplier-MSFT mentioned.
You need to manually set it. Rather than reinventing the wheel, note the section here on updating the current principal for the request - thats your option here.
How to set Request.IsAuthenticated to true when not using FormsAuthentication.RedirectFromLoginPage?
public void RenewCurrentUser()
{
System.Web.HttpCookie authCookie =
System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = null;
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
FormsAuthenticationTicket newAuthTicket = authTicket;
if (FormsAuthentication.SlidingExpiration)
{
newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
}
string userData = newAuthTicket.UserData;
string[] roles = userData.Split(',');
System.Web.HttpContext.Current.User =
new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), roles);
}
}
}

ASP.NET Custom Pricipal and Cookies (tickets)

If i create a custom principal with five custom properties (example, phoneNumber), does the principal data get trasmitted inside of the cookie or does the data stay in the server?
void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
// Get Forms Identity From Current User
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
// Get Forms Ticket From Identity object
FormsAuthenticationTicket ticket = id.Ticket;
// Create a new Generic Principal Instance and assign to Current User
IFGPrincipal siteUser = new IFGPrincipal(Context.User.Identity, new string[] { }, 2);
HttpContext.Current.User = siteUser;
}
}
}
}

Resources