ASP.NET Send Cookies to client Browser - c#

I'm integrating a single sign on over 2 ASP.Net applications. For that matter i have a web service that is called by the main app. when a user logs in. this web service authenticates the user in my second application and brings back the authentication cookies i need to deliver to the client browser so he can navigate freely and logged in both applications.
I was planning to use HttpContext.Current.Response.Cookies.Add(cookie) in order to deliver the new cookies but this seems not to work as no cookies are added what so ever...
Any ideas on what might be going wrong?
here is my code:
var service = new localhost.UserManagement();
service.CookieContainer = new CookieContainer();
if (service.AuthenticateUser("test#user.pt", "test"))
{
var collection = service.CookieContainer.GetCookies(new Uri("http://localhost"));
foreach (Cookie item in collection)
{
HttpContext.Current.Response.Cookies.Add(CookieConverter(item));
}
HttpContext.Current.Response.Flush();
return true;
}
return false;
Note: CookieConverter(item) is used to convert Cookie object i receive to HttpCookie
Thanks
private HttpCookie CookieConverter(Cookie cookie)
{
var result = new HttpCookie(cookie.Name);
result.Value = cookie.Value;
result.Domain = cookie.Domain;
result.Expires = cookie.Expires;
result.Path = cookie.Path;
result.Secure = cookie.Secure;
result.HttpOnly = cookie.HttpOnly;
return result;
}

You should check:
collection is empty? Could you set braeakpoint and check collection?
where is this code located? (.aspx page, web service, http handler?)
try to create minimalistic "Cookie setter" that just add simple cookie in any way

Related

Authorize.net Accept Hosted Customer Profile Page has no button to return

I am using the Authorize.net Accept Hosted "Get Hosted Profile Page" action using redirect instead of iframe. Everything is working so far, redirect is happening, token is getting passed . . . but there is literally no button to proceed and/or go back to my site after the customer is redirected to this page (?). Am I missing something? I am passing a redirect URL in to get my token, so I'd expect there to be something happening.
I'm using the .NET SDK on my backend.
string token = null;
var settings = new settingType[]
{
new settingType
{
settingName = settingNameEnum.hostedProfileReturnUrl.ToString(),
settingValue = model.ReturnUrl.AbsoluteUri
// ^^^ here's why my redirect url goes
}
};
var profileReq = new getHostedProfilePageRequest();
profileReq.customerProfileId = model.CustomerProfileId;
profileReq.hostedProfileSettings = settings;
var controller = new getHostedProfilePageController(profileReq);
controller.Execute();
var resp = controller.GetApiResponse();
// ^^^ this all works fine, token is returned
Here's the page to which I'm redirected at https://test.authorize.net/customer/manage (the sandbox), below. There's no button to advance or go backwards. I've tried clicking everywhere.
How do I get back to my site?

HTTP/HTTPS C# MVC 5 Cookies being sent but not being recollected

Ok basically when my website had no SSL certificate I was able to use my remember me cookies just fine
Response.Cookies["censid"].Value = sessInfo.sid;
Response.Cookies["censid"].Expires = DateTime.UtcNow.AddDays(30);
Response.Cookies["censid"].Domain = "my-domain.com";
It worked just fine in this state. Once the SSL Cert was added it still sends the cookie in site responses but the client does not send the cookie on request, same for HTTP. I then changed the code to what is below and still the issue persists.
Response.Cookies["censid"].Value = sessInfo.sid;
Response.Cookies["censid"].Expires = DateTime.UtcNow.AddDays(30);
Response.Cookies["censid"].Domain = "my-domain.com";
Response.Cookies["censid"].Secure = true;
Here is my code to try and retrieve the set cookie
HttpCookie cookie = Request.Cookies["censid"];
if (cookie != null)
{
string sid = cookie.Value;
UserIdFromSession userid = await UserHandler.validateSessionId(sid);
if (userid.status == SessionResult.SessionSuccess)
{
Session["sid"] = sid;
Session["username"] = UserHandler.getUsernameFromUserId(userid.userId);
return RedirectToAction("Index", "User");
}
}
I still have HTTP enabled so people can access HTTPS and HTTP versions of my website, the cookies are still "set" but when I try to load the site again the cookies are not sent in the request.

Linq2Twitter Single User Authorisation Null Value Exception

I've been developing an internal ASP.NET web forms application for our business and one of the requirements is to display our Twitter feed on our portal home page to all users.
For this I've decided that it is best to use LinqToTwitter Single User Authorisation to get the statuses for everyone without them having to authenticate their own accounts.
My main problem at the minute is that when we use the auth object to get the TwitterContext, it returns with an error on the TwitterContext saying
Value cannot be null
on every internal context object.
I've gone through our twitter application settings at http://dev.twitter.com and I have our correct consumer key/token and access key/token. The permission for the application is set to Read-Only. There is no callback URL specified on the http://dev.twitter.com website as it is currently on our internal system (so it wouldn't be able to get back anyway). Is this where it is going wrong? Do I need to forward some ports and allow the callback to get through to our development machines?
Here's the code for prudence. As far as I can see, there is nothing wrong with it. I know that it is set to .FirstOrDefault, this was just for seeing whether it is actually getting anything (which it isn't).
Thanks for any help you can give! :)
private async Task GetTweets()
{
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
AccessToken = ConfigurationManager.AppSettings["accessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"],
}
};
try
{
using (TwitterContext twitterContext = new TwitterContext(auth))
{
var searchResponse = await (from c in twitterContext.Status
where c.Type == StatusType.User
&& c.ScreenName == "my_screenname"
select c).ToListAsync();
Tb_home_news.Text = searchResponse.FirstOrDefault().Text;
}
}
catch (Exception ex)
{
Tb_home_news.Text = ex.Message;
}
}
If you're creating a Web app, you do need to add a URL to your Twitter App page. It isn't used for the callback, but might help avoid 401's in the future if you're using AspNetAuthorizer.
It looks like you have a NullReferenceException somewhere. What does ex.ToString() say?
Double check CredentialStore after initialization to make sure that all 4 credentials are populated. AccessToken and AccessTokenSecret come from your Twitter app page.
Does searchResponse contain any values? Calling FirstOrDefault on an empty collection will return null.

Lost session/cookie when login as another user

I am building dnn module which allow logged in user to log in as another user.
But I have some wired issue here.
This is how I log out current user and login as another user:
UserInfo userInfo = UserController.GetUserById(portalId, userId);
if (userInfo != null)
{
DataCache.ClearUserCache(this.PortalSettings.PortalId, Context.User.Identity.Name);
if (Session["super_userId"] == null)
{
Session["super_userId"] = this.UserId;
Session["super_username"] = this.UserInfo.Username;
}
HttpCookie impersonatorCookie = new HttpCookie("cookieName");
impersonatorCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(impersonatorCookie);
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
PortalSecurity objPortalSecurity = new PortalSecurity();
objPortalSecurity.SignOut();
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
Response.Redirect(Request.RawUrl, true);
}
And in PageLoad() I try to read value from this cookie but it doesn't read anything:
try
{
string super_userId = Request.Cookies["cookieName"]["super_userId"];
string super_username = Request.Cookies["cookieName"]["super_username"];
if (!String.IsNullOrEmpty(super_userId))
{
this.Visible = true;
this.lblSuperUsername.Text = Session["super_username"].ToString();
this.txtPassword.Enabled = true;
this.btnBackToMyAccount.Enabled = true;
}
...
I also have tried to do the same with session but nothing works, and I can't figure why?
As I find here, there can be problems with setting cookies in a request that gets redirected, and here is stated that cookies won't get set with a redirect when their domain is not /.
So you can try to not redirect using HTTP headers, but show a "Logged In" page instead that contains a "Home" link and a meta refresh or Javascript redirect.
By the way, setting a UserID in a cookie is not really the way to go. What if I change that cookie value to 1?
I suggest when you set a new cookie to always set the Domain, and probably and the Expires.
Response.Cookies[cookieName].Domain = RootURL;
Response.Cookies[cookieName].Expires = DateTime.UtcNow.AddDays(cDaysToKeep);
The domain is very importan to be the url with out the subdomain, eg only the mydomain.com with out the www. because if a cookie is set from www.mydomain.com and you try to read it from mydomain.com or vice versa, then the cookie will not be read and you may lost it / overwrite it.
So I suggest to make a function that when you set a cookie, you set at least 3 parametres, the Domain, the Expires, and the Value.
Similar questions and answers :
Multiple applications using same login database logging each other out
asp.net forms authentication logged out when logged into another instance
Put these two statements
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
after
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
May be the UserLogin method is resetting the Session variables.
Hope it Helps :)

Authenticate using openID without login through provider

I create web application to connect to MySpace Offsite App and I want to authenticate I used the following code
var openid = new OpenIdRelyingParty();
IAuthenticationRequest request = openid.CreateRequest("http://www.myspace.com/thabet084");
request.AddExtension(new OAuthRequest("ConsumerKey"));
request.RedirectToProvider();
var response = openid.GetResponse();
OAuthResponse oauthExtension = new OAuthResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
oauthExtension = response.GetExtension<OAuthResponse>();
var user_authorized_request_token = oauthExtension.RequestToken;
break;
}
}
OffsiteContext context = new OffsiteContext("ConsumerKey", "ConsumerSecret");
var accessToken = (AccessToken)context.GetAccessToken(oauthExtension.RequestToken, "", "");
and I used the following refrences DotNetOpenAuth.dll and MySpaceID.SDK.dll
My problems are:
I always found that responce=null
I don't need user to login through provider MySpace so i need to remove RedirectToProvider();
My application in brief is to send status from mywebsite to MySpace account Just click on button to send
All ideas are welcome
BR,
Mohammed Thabet Zaky
If you don't want to authenticate the user then OpenID isn't what you want at all. In fact, OAuth probably isn't either. If you just want to send the user to MySpace to confirm a status message, you can very likely do that with just a crafted URL the way Twitter does -- no special protocol or library required at all.

Categories