I'm working on a REST API Project where users log in and make calls. In order to do that, i create a cookie where i encrypt the username. My server is deployed and something really weird is going on. From time to time i just don't receive the cookies in the response. In this case I just have to make any modification in the web.config file and it starts working again... I really don't understand why... Any ideas ?
Here's my login code :
[Route("login", Order = 1)]
[HttpPost]
[HttpGet]
public async Task<HttpResponseMessage> Login([FromUri] string userId, [FromUri] string userPassword)
{
try
{
Tuple<string, string> result = userService.Authenticate(userId, userPassword);
string sessionIds = result.Item1;
string message = result.Item2;
CookieHeaderValue cookie = CreateSessionsCookie(sessionIds);
cookie.Secure = true;
// Store username for later use
CookieHeaderValue userCookie = new CookieHeaderValue(Strings.Id, Encryption.Protect(userId, Strings.Id));
userCookie.Secure = true;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, JsonConvert.DeserializeObject(message));
response.Headers.AddCookies(new CookieHeaderValue[] { cookie, userCookie });
return response;
}
catch (Exception ex)
{
return HandleException(ex);
}
}
It is a bit of an anti-pattern to use a cookie for a restful web service. Just include the username in the header instead.
As to why this is timing out I suspect it has to do with your session timing out.
Related
I am working on a WebApp (Razor Pages) that work also as API Gateway. The WebApp get some data from another project (part of the same solution) that is a WebAPI.
The problem is that when I do an HTTPRequest to the WebAPI, if the request is not too long, the WebAPI will process it, but when I try to send a longer request (long in characters) it will reject it and send back a 404.
The WebApp is a basic CMS. So the app will provide to the user, the creation of Web pages. I am using a restful request model so a request will look like this:
string baseURL = #"https://localhost:5001";
public async Task<string> CreatePageAsync(string pageTitle, string pageBody, int? pageOrder, string userID)
{
if (pageTitle != null && pageBody != null && pageOrder != null && userID != null)
{
string fullURL = baseURL + $"/api/pages/create/page/title/{pageTitle}/body/{pageBody}/order/{pageOrder}/user/{userID}";
var request = new HttpRequestMessage(HttpMethod.Post, fullURL);
HttpResponseMessage response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
return "error";
}
}
return "ok";
}
As you can imagine, the "pageBody" property is the one responsible for the length of the request. So, when I test the WebAPI with short words, it works just fine, but if I copy an article from the internet (Just text) and use it as the body (simulating the user's content), if it is a long one, it will return a 404.
On the other end, the WebAPI looks like this:
[HttpPost("Create/page/title/{pageTitle}/body/{pageBody}/order/{pageOrder}/user/{userID}")]
//[ValidateAntiForgeryToken]
public async Task<string> CreatePage(string pageTitle, string pageBody, int pageOrder, string userID) //[Bind("pageName,pageHead,pageBody,userID")]
{
if (ModelState.IsValid)
{
DateTime now = DateTime.Now;
WebPage newPage = new WebPage()
{
PageID = _globalServices.GuidFromString(_globalServices.GetSeed()),
PageDateCreated = now,
PageDateUpdated = now,
PageOrder = pageOrder,
PageTitle = pageTitle,
PageBody = pageBody,
UserID = userID
};
try
{
await _pagesDBContext.Pages.AddAsync(newPage);
await _pagesDBContext.SaveChangesAsync();
}
catch (Exception e)
{
string message = "ERROR: Could not save to the database.\n";
return message + e.Message;
}
return "Page saved";
}
return "ERROR: Model invalid";
}
I am sending the request as simple text. I don't know if there is a better way.
Any ideas?
I don't have enough rep to comment but it looks like the maximum characters you can send in a GET request is 2,048.
I'm operating an ASP.NET MVC application that leverages Microsoft OpenID Connect.
(manual : https://learn.microsoft.com/ko-kr/azure/active-directory/develop/tutorial-v2-asp-webapp)
We began our service in October 2019, and had no problems with it until now. After the last successful log in, we are facing authorization failure in the redirected part and cannot verify the Claim (User.Identity) information, hence resulting in an infinite loop issue.
I hope I can get assistance with this problem.
After logging in successfully, I store the authentication information so that I can share the token value in the RESTful API which is configured separately.
In the earlier version, the token value was stored in the Token table and was stored in the session.
But when I started to used the session from the second attempt, the problem started to occur so I started not to use the session.
At this point, I tried several login attempts and saw that it worked well without a problem.
Initially, the application was properly working, but as time passed by, I can no longer retrieve the authentication information and an infinite loop occurs once again.
Code:
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties{ RedirectUri = "/Auth/SignedIn" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
this.RemoveSessionToken();
HttpContext.GetOwinContext().Authentication.SignOut(
OpenIdConnectAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
}
public async Task<ActionResult> SignedIn()
{
var IsLoggedIn = Request.IsAuthenticated;
var claims = (System.Security.Claims.ClaimsIdentity) ClaimsPrincipal.Current.Identity;
if (IsLoggedIn)
{
var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
//string sessionToken = Session.SessionID;
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(ipAddress))
ipAddress = Request.ServerVariables["REMOTE_ADDR"];
var dbContext = new GetOfficeEduUsersEntities();
var token = new T_APIToken();
string office365Id = userClaims?.FindFirst("preferred_username")?.Value;
token.TokenID = office365Id;
token.IssuerID = office365Id;
token.IssueDT = DateTime.Now;
token.ExpireDT = DateTime.Now.AddMinutes(180);
dbContext.T_APIToken.Add(token);
dbContext.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
{
//Error
return RedirectToAction("SignedIn");
}
}
Let me put the problem with a bit of structure.
Context
We have a web application build with Web Forms and hosted in an Azure Web App that authenticates the users against an Azure Active Directory using the OWIN + OpenId Connect standards.
The authentication process works like a charm and users are able to access the application without any problem.
So, whats the issue?
After struggling for many days with it I'm unable to pass any query string parameter to the application through the authentication process. For example, if I try to access the application for the first time through the URL: https://myapp.azurewebsites.net/Default.aspx?param=value. The reason I need to pass this parameter is that it triggers some specific actions in the main page.
The problem is that after the authentication redirects to the webapp's main page the original query string parameters of the request are gone.
The code
The startup class looks like this:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = Constants.ADTenant.ClientId,
Authority = Constants.ADTenant.Authority,
PostLogoutRedirectUri = Constants.ADTenant.PostLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = context =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(Constants.ADTenant.ClientId,
Constants.ADTenant.AppKey);
string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
Constants.ADTenant.ObjectIdClaimType).Value;
AuthenticationContext authContext = new AuthenticationContext(Constants.ADTenant.Authority,
new NaiveSessionCache(userObjectID));
if (HttpContext.Current != null)
{
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential,
Constants.ADTenant.GraphResourceId);
AuthenticationHelper.token = result.AccessToken;
AuthenticationHelper.refreshToken = result.RefreshToken;
}
return Task.FromResult(0);
}
}
});
And it works properly!
What I already tried
I've got access to the original request Url by adding an overwrite of the RedirectToIdentityProvider notification:
RedirectToIdentityProvider = (context) =>
{
// Ensure the URI is picked up dynamically from the request;
string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + context.Request.Uri.PathAndQuery;
context.ProtocolMessage.RedirectUri = appBaseUrl;
return Task.FromResult(0);
}
With this I tried to force the redirect to the main page including the original query string parameter, but then the redirection after authentication breaks and gets stuck in an infinite loop.
I've also tried with changing the redirect url of the application configuration in Azure AD without luck. Also tried to store the query string parameters somewhere else, but the Session is not accessible that early in the process.
Does anyone know what am I doing wrong? Or I'm just asking for something impossible? Any help would be appreciated.
Thank you very much in advance!
I recently had a need to do the exact same thing. My solution may not be the most sophisticated, but simple isn't always bad either.
I have two Authentication Filters...
The first filter is applied to all controllers that could potentially be hit with query string parameters prior to authorization. It checks if the principal is authenticated. If false it caches the complete url string in a cookie. If true it looks for any cookies present and clears them, just for cleanup.
public class AuthCheckActionFilter : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
if (!filterContext.Principal.Identity.IsAuthenticated)
{
HttpCookie cookie = new HttpCookie("OnAuthenticateAction");
cookie.Value = filterContext.HttpContext.Request.Url.OriginalString;
filterContext.HttpContext.Response.Cookies.Add(cookie);
}
else
{
if (filterContext.HttpContext.Request.Cookies.AllKeys.Contains("OnAuthenticateAction"))
{
HttpCookie cookie = filterContext.HttpContext.Request.Cookies["OnAuthenticateAction"];
cookie.Expires = DateTime.Now.AddDays(-1);
filterContext.HttpContext.Response.Cookies.Add(cookie);
}
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
}
}
The second filter is applied only to the default landing page, or in other words where the identity server is redirecting after login. This second filter looks for a cookie and if it exists it calls response.Redirect on cookie value.
public class AutoRedirectFilter : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
if(filterContext.Principal.Identity.IsAuthenticated)
{
if(filterContext.HttpContext.Request.Cookies.AllKeys.Contains("OnAuthenticateAction"))
{
HttpCookie cookie = filterContext.HttpContext.Request.Cookies["OnAuthenticateAction"];
filterContext.HttpContext.Response.Redirect(cookie.Value);
}
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
}
}
I've got an existing C# project with the following POST method:
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
}
Which uses:
OAuthWebSecurity.Login(provider, ...);
I'm kinda new to OAuth, and haven't done anything with it in this C# project. I do however implemented Google-authorization on an Android App, and I want to use the following class/method for the HttpPost:
public class TaskPostAPI extends AsyncTask<String, Void, String>
{
GoogleApiClient googleAPI;
public TaskPostAPI(GoogleApiClient googleAPI){
this.googleAPI = googleAPI;
}
#Override
protected String doInBackground(String... urls){
String response = "";
for(String url : urls){
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
try{
List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(2); //(3);
//nvPairs.add(new BasicNameValuePair("personName", Plus.PeopleApi.getCurrentPerson(googleAPI).getDisplayName()));
//nvPairs.add(new BasicNameValuePair("personGooglePlusProfile", Plus.PeopleApi.getCurrentPerson(googleAPI).getUrl()));
//nvPairs.add(new BasicNameValuePair("personEmail", Plus.AccountApi.getAccountName(googleAPI)));
nvPairs.add(new BasicNameValuePair("provider", ???));
URL u = new URL(url);
nvPairs.add(new BasicNameValuePair("returnUrl", u.getProtocol() + "://" + u.getHost()));
post.setEntity(new UrlEncodedFormEntity(nvPairs));
HttpResponse execute = client.execute(post);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while((s = buffer.readLine()) != null)
response += s;
}
catch(Exception ex){
ex.printStackTrace();
}
}
return response;
}
}
So my question: What should I put at the POST-method's ???. So what is the Provider? In my Android App I log in using Google, and got the GoogleApiClient and Person (com.google.android.gms.plus.model.people.Person).
At this website I see the following url: https://accounts.google.com/o/oauth2/auth. Is this the url I should use as provider? Or should I add parameters to this url? Or should I use a completely different string as provider?
PS: If someone can send me a link to a list of provider-urls (like Google's, Facebook's, Twitter's, etc.) and how to use them for the C# OAuthWebSecurity I would appreciate it.
Thanks in advance for the responses.
Ok it turns out it was very simple.. The provider is just "Google", nothing more, nothing less.. This provider name I found at the RegisterClient method in de C# project:
OAuthWebSecurity.RegisterClient(client, "Google", extraData);
Now the POST works, except for the message "The required anti-forgery cookie "__RequestVerificationToken" is not present.", but at least I can continue. And adding a Cookie to a HttpPost isn't that hard I believe when using a CookieManager.
i'm using ASP.NET MVC5 with the latest Identity and Signalr on the server and have .NET client app. Currently i have working auth logic implemented but i don't get it how can i get auth failure in .NET desktop client?
Here is my .NET desktop client auth code:
private static async Task<bool> AuthenticateUser(string siteUrl, string email, string password)
{
try
{
var handler = new HttpClientHandler { CookieContainer = new CookieContainer() };
using (var httpClient = new HttpClient(handler))
{
var loginUrl = siteUrl + "Account/Login";
_writer.WriteLine("Sending http GET to {0}", loginUrl);
var response = await httpClient.GetAsync(loginUrl);
var content = await response.Content.ReadAsStringAsync();
_verificationToken = ParseRequestVerificationToken(content);
content = _verificationToken + "&UserName="+email+"&Password="+password+"&RememberMe=false";
_writer.WriteLine("Sending http POST to {0}", loginUrl);
response = await httpClient.PostAsync(loginUrl, new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded"));
content = await response.Content.ReadAsStringAsync();
_verificationToken = ParseRequestVerificationToken(content);
_connection.CookieContainer = handler.CookieContainer;
return true;
}
}
catch (Exception ex)
{
Logger.Log(ex, "Auth");
return false;
}
}
where _connection is a hub connection which receives cookie needed for hub auth. The problem is that httpCLient.PostAsync() always return valid result and i don't get it how i can implement auth failure detection.
Here is server login code:
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
On failure it just adds error string on the page.
Please advice what is the better way to implement auth result.
This is strange that i got no single answer for this question. I've come to an intermediate solution:
Add unique hidden tags for login and index pages (on failure login page is displayed again, on success - index page)
<div style="display: none;" id="#SharedData.Constants.INDEX_PAGE_TAG"></div>
In .NET client check content string for the specific tag presence.
I don't think this the preformance-wise solution but at least it works...