How to create persistent header in MVC web API - asp.net

I am working on angularJS project right now, and on login of a user want to set my custom header value with UserID and name to be presistent. IS it possible to presist header enven after browser restart?
one of my last tries was this code:
var tokenIdentity = new AuthCacheManager().Authenticate(loginName, password);
// HttpContext.Current.Response.AppendHeader("Last-Update", "AuthToken");
response = Request.CreateResponse(HttpStatusCode.OK, tokenIdentity);
response.Content = new StringContent("asdasd", Encoding.GetEncoding("ISO-8859-1"), "text/xml");
response.Headers.Add("AuthToken", tokenIdentity.ToString());
response.Content.Headers.Expires = DateTimeOffset.Now.AddMinutes(10.0);
response.Content.Headers.Add("Content-Length", "{ab:a}");
response.Headers.Add("Connection", "Keep-Alive");
response.Headers.Add("Keep-Alive", "timeout = 20000 max = 100");
return response;
But it didn't work at all.
Does anyone know how to make a header persistent since what i am doing now is only alive for one request?

Related

Accessing the Microsoft Graph after OpenId Connect Azure AD Callback

Fundamentally all I need to do is grab a users profile photo after successful login (asp.net 4.8) since it doesn't seem that I can request the photo to come over with the login claims.
This is the callback handler
SecurityTokenValidatedNotification<Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification
This is how I get the Identity from that callback and it's all there looking good
var identity = notification.AuthenticationTicket.Identity;
So I'm trying to callback with RestSharp
var client = new RestSharp.RestClient("https://graph.microsoft.com");
var request = new RestSharp.RestRequest($"/v1.0/users/{email}/photo/$value", RestSharp.Method.GET);
var callbackResult = client.Execute(request);
Debugger.Break();
if (callbackResult.StatusCode == HttpStatusCode.OK)
{
Debugger.Break();
}
But it keeps (I suppose OBVIOUSLY) coming back as unauthorized. Is there some token or something I can use now that the user has authenticated to add a header or querystring or something that will just get me the extra data easily?

How to set url or email or special character to cookie in Asp.net core 3.0?

I want to set cookie using asp.net core. i use this code to add cookie
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Append("email", "hello#gmail.com", options);
But in cookie email is not store as it is . its like hello%gmail.com . I can store the url and email into cookie.
Any help. Thank you
As far as I know, if you store the cookie in the response, it will use url encrypt the cookie by default.
When you checked the client cookie, it will store as below:
This will not affect reading cookie in your asp.net core backend codes.
The source codes will decrypt the cookie value by default to let you see the result.
More details, you could refer to below example:
var re = Request.Cookies["email"];
Result:
I try to read the cookie using Javascript and it seems it not show as it should
If you want to read the cookie from js, you should use decodeURIComponent
method to decode it.
More details, you could refer to below codes:
$(document).ready(function () {
var read_cookies = document.cookie;
var split_read_cookie = read_cookies.split(";");
for (i = 0; i < split_read_cookie.length; i++) {
var value = split_read_cookie[i];
value = value.split("=");
if (value[0] == " email" ) {
alert(value[1]);
alert(decodeURIComponent(value[1]));
}
}
});
Result:

Not getting WeChat Follow response

I have a Debugging Official Account with WeChat. I have entered my public URL and Token into the field provided http://admin.wechat.com/debug/sandbox and also attempted debugging the request with http://admin.wechat.com/debug/
My ASP.Net [.Net4.5] Web API application's POST Method looks like the following :
public HttpResponseMessage PostMessage([FromBody]Strikemedia.Api.WeChat.TextMessage value)
{
if (value == null)
{
var richMediaMessage = new RichMediaMessage();
richMediaMessage.touser = value.FromuserName;
//Create Article
var item = new Article()
{
title = "Didn't receive anything back",
description = "Mind entering 'test'",
picurl = "URL",
url = "URL"
};
var articles = new List<Article>();
articles.Add(item);
richMediaMessage.articles = articles;
richMediaMessage.articleCount = articles.Count;
return Request.CreateResponse(HttpStatusCode.OK, richMediaMessage, "application/json");
}
var exploded = value.Content.Split(' ')[0];
var richMedia = new RichMediaMessage();
richMedia.touser = value.FromuserName;
//Create Article
var article = new Article() {
title = response.KeywordDescription,
description = response.Response,
picurl = "URL",
url = "URL"
};
var _articles = new List<Article>();
_articles.Add(article);
richMedia.articles = _articles;
richMedia.articleCount = _articles.Count;
//Return response
var resp = Request.CreateResponse(HttpStatusCode.OK, richMedia, "application/json");
//resp.RequestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
return resp;
}
It needs to respond with a RichMessageType in JSON format and is received in XML format
Am i missing something or have i overlooked something?
Can you confirm that you have submitted the URL and token into admin.wechat.com and that the URL and token was accepted?
Also note you get XML and you respond with XML no json response.
Have you had a look at: http://youtu.be/kB20Zf51QWU
And then this
http://youtu.be/_2FSzD2B2F0
This is the documentation for the XML can be found when you google "wechat guide to message api"
So if you still not receiving a success message when submitting your app on admin.wechat.com then you can send me your test URL here. To find this URL check your access logs to see exactly what URL wechat is calling. Then post it here. Please note that when you hit the URL as wechat will you should only see the "echostr" printed on the screen (when viewing the source in your browser). No XML no HTML just the echostr.
Also make sure there are no spaces or newlines after or before the "echostr". When you view the source it should only be one line which is the echostr GET param's value.
The XML response only comes in later when you actually start responding to messages from users. For now Wechat is just confirming if your security is setup correctly.
Also note if your server is load balanced you will have to skip the signature validation and build your own validation when a echostr GET parameter gets passed through and only echo the "echostr" param to screen.

Authorization header is not send for the subsequent request from Flex Application

I am trying to access html files protected by basic authentication. Below is the code to do that but I still get the authentication dialog. I checked the fiddler and found that for the first request authorization header is present but for the subsequent requests which is requested to load the .js, css & images the authorization header is not added. This is the reason I am getting the auth dialog.
Is there a way to add authorization header to the subsequent requests as well?
var loader:HTMLLoader = new HTMLLoader();
var be:Base64Encoder = new Base64Encoder();
be.insertNewLines = false;
be.encode("madhur" + ":" + "sharma");
var urlRequest:URLRequest = new URLRequest("http://bazinga/myHtmlFiles/index.html");
urlRequest.requestHeaders.push(new URLRequestHeader("Authorization","Basic "+ be.toString()));
page.htmlLoader.load(urlRequest);
Thanks a lot
The above solution didn't worked for me. Below is the alternate solution.
URLRequestDefaults.authenticate = false;
URLRequestDefaults.setLoginCredentialsForHost("bazinga.xyz.com", "madhur", "sharma");
var req:URLRequest = new URLRequest("http://bazinga.xyz.com/MyHtml/index.html");
htmlControl.htmlLoader.load(urlRequest);
See related question URLRequestDefaults.setLoginCredentialsForHost not setting the user & pwd in authorization header

RIA Services, Forms Authentication and extra cookies

I have an Silverlight 4 RIA Services application with custom Forms Authentication. The custom authentication service works like a charm.
The problems is I want to serialize the user object in a cookie which is then sent with each subsequent request.
I create the cookie and add it to the response cookie collection but on the next request the only cookies in the cookie collection are ASPXAUT and ASPX_SESSIONId, of the custom cookie not a trace.
This is the cookie management class:
public class CookieManager:ISessionManager
{
public object this[string key]
{
get
{
var context = getCurrentContext();
var cookie = context.Request.Cookies[key];
if (cookie == null) return null;
return deserialize(cookie.Value);
}
set
{
var context = getCurrentContext();
string cookieValue = serialize(value);
HttpCookie cookie = new HttpCookie(key, cookieValue);
cookie.Expires = DateTime.Now.AddDays(10000);
cookie.HttpOnly = false;
context.Response.Cookies.Remove(key);
context.Response.Cookies.Add(cookie);
}
}
public void Abandon()
{
var context = getCurrentContext();
context.Response.Cookies.Clear();
}
public void Clear()
{
Abandon();
}
private HttpContext getCurrentContext()
{
return HttpContext.Current;
}
private string serialize(object value)
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Context = new StreamingContext(StreamingContextStates.Clone);
formatter.Serialize(stream, value);
StreamReader reader = new StreamReader(stream);
stream.Position = 0;
string result = reader.ReadToEnd();
reader.Close();
stream.Close();
return HttpUtility.UrlEncodeUnicode(result);
}
public object deserialize(string value)
{
value = HttpUtility.UrlDecode(value);
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(value);
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream);
}
}
It reads and saves cookies.
Now my problem is this:
What I need to enable in silverlight or in the ASP.NET (WCF) application in order for extra cookies to be sent with each request along side the authentication cookie.
EDIT:
I've inspected the HTTP request/response stack and those extra cookies are sent from the server with the WCF RIA Services response but not returned by the next service call from the client.
If I understand your edit above correctly, you've already inspected the HTTP requests and found the desired cookie present in the HTTP Set-Cookie header of the response, but missing in the Cookie header of the next request. Is this correct? If not, please clarify.
If so, the problem sounds like one of three things:
the client is not successfully saving the cookie, due to many possible reasons including:
cookie not properly formatted (unlikley)
cookie is too long
there's a client- or server-side policy (e.g. P3P) preventing saving persistent cookies.
The client is saving the cookie OK, but is not sending it back, even without Silverlight. This could be caused by, for example, a security issue where the hostname of the first request is different from the second.
The client is saving the cookie and can send it back over regular HTML pages, but not via HTTP requests sent by Silverlight.
To see if #1 is the problem, look (using your browser's ability to view cookies) at the cookies saved by your browser for that site. Is the expected cookie saved? If it is, then you can eliminate #1 as the problem. If it's not saved, start looking
To see if #2 is the problem, try creating a server-side page with no silverlight on it-- just a simple HTML page. When you visit that page with your browser, is the cookie sent as expected? If yes, then #2 is not your problem.
If #1 and #2 are not the problem, that leaves #3. Silverlight's HTTP handling is complicated, not least because you have to choose between having HTTP client requests handled by the browser or by Silverlight. Read the Silverlight cookies documentation carefully and see if any of the info therein will help you figure out the problem. Consider trying to use the "Client HTTP" setting, or if you're already using this, consider switching back to the "browser HTTP" setting and see if your problem goes away. Note that the Client HTTP setting apparently has a problem with losing new cookies after an HTTP redirect. See this thread for more info. There's a workaround discussed in that thread: using CookieContainer.
BTW, could you edit your question to include all the HTTP headers of the request and the subsequent request? This may help diagnosis.

Resources