ASP.NET MVC 2.0 application not working on server - c#

I have an MVC 2.0 application that is only loading the Home Index page. Whenever I try to navigate away from the page I get a HTTP Error 404 - File or directory not found.
Internet Information Services (IIS).
The site works find While testing on a localhost but whenever I try to run it on the destination site I keep not being able to navigate away from the Home page.
This is the way I am currently trying to get into the LoginOut Controller and trying to run the login method.
<% var login = Url.Action("Login", "LogInOut"); %>
<form method="post" class="pure-form" action="<% Response.Write(login); %>">
Then the LoginOutController is suppose to run this code. However no code get's run as the page both doesn't redirect and there is no Log file of what has just happened.
[HttpPost]
public ActionResult Login()
{
var username = Request.Form["username"];
var password = Request.Form["password"];
SessionFacade.UserSession = UserQueries.GetUserSession(username, password);
UserSession us = SessionFacade.UserSession;
//redirects to login if us is null
if (us == null)
{
Log.InvalidLogin(us, username);
return RedirectToAction("Index", "Home");
}
else if (us.GetUploader())
{
var uploadedFiles = new SessionFilesUploaded();
Session[SessionValue.SessionFilesUploaded()] = uploadedFiles;
}
Log.UserLogin(us);
//Checks that each user type has an appropriate folder and makes folders that are missing
var folders = UserQueries.GetFolders();
FolderExist.MakeFolder(folders);
return RedirectToAction("Index", "Browser");
}
The URL that I end up getting the 404 error is LogInOut/Login. Which as I said earlier works on my localhost server but doesn't seem to work on the webserver.
Any help would be appreciated

Found out the issue was with the fact that we are running an old server and IIS6. The MVC requests aren't getting processed as ASP.NET and that's what causing the issues. Had to port the code from MVC to webforms.

Related

Authentication/Authorization in ASP.NET Core using Enterprise SingleSignon page and Microsoft SignInManager

Presently I am working on an authentication issue in one of my ASP.NET Core(3.0) application.
To give some background, we have to use an Enterprise Single sign on page to authenticate the users. Once the user got authenticated it redirects back to our application along with user name in a HTTP header called "SM_USER". Then using that information we load corresponding Claim information from DB using Microsoft SignInManger. The application is working fine if the user is accessing the root but it couldn't able to access if they are trying to navigate a specific page directly, like http://website/Controller/Index.
I am suspecting that we may have implemented it wrongly so would like to know how should the below scenario to be implemented?
Our users first get authenticated using an enterprise Login Page(Single sign on) then redirected to our application. user information available on HTTP Headers and the corresponding claims information is available in our DB which we need to use for authorization purpose(we wanted to use Microrosoft SignInManger to load them).
I found the issue after researching it throughly so sharing here in case it useful for someone.
we observed whenever a user try to access a page if the user is not authenticated then it is redirecting Login page(Observed that decorating them with [Authorize] attribute is causing this), where We are using this Login page for local development purpose.
so when the user get redirected to login page and if the environment is not development then below code is executed on the Get method, which takes care of signing the user and creating UserPrincipal. Then after that we redirecting to the page the user requested.
if (!_signInManager.IsSignedIn(User))
{
string userName = HttpContext.Request.Headers["SM_USER"].ToString();
if (userName.Length > 0)
{
var user = await _userManager.FindByNameAsync(userName);
if (user != null)
{
var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme,
claimsPrincipal,
new AuthenticationProperties { IsPersistent = true });
if (string.IsNullOrEmpty(returnUrl)) //returnUrl is a parameter get passed by the system.
{
return RedirectToAction("<Action>", "<Controller>");
}
else
{
return Redirect(returnUrl);
}
}
}
}

using UseCookiesAuthentication to authorize the MVC Controller Action, it works locally, gives issue when the application is deployed in azure

I have the MVC application, using the Owin and Asp.Net Identity, and using the useCookieauthentication
During login process, I have added the custom claim, and I gets properly sign-in. ```
[HttpPost]
public async Task<ActionResult> Login(LoginViewModel loginViewModel)
{
var user = UserManager.FindByName(loginViewModel.UserName);
var signInStatus = UserManager.CheckPassword(user, loginViewModel.Password);
if (signInStatus)
{
user.Claims.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim() { ClaimType = "CustomClaim", ClaimValue = loginViewModel.UserName.Trim() });
SignInManager.SignIn(user, true, false);
return Redirect(url);
}
else
{
ModelState.AddModelError("", "Invalid login attempt.");
return View(loginViewModel);
}
}
When I get the callback to my one of Action method, I try to retrieve Claim Custom Claim that I have stored during login process. Locally when I run and debug this code it works correctly as expected. But when I deploy the application to azure I am unable to get the custom claim value.
public ActionResult Index()
{
var claimsPrincipal = System.Web.HttpContext.Current.User as System.Security.Claims.ClaimsPrincipal;
var customClaimValue = claimsPrincipal.Identities.First().Claims.First(x => x.Type.Equals("CustomClaim")).Value;
return View();
}
Couple of things to try, Let me know if it still doesn't work for you, Posting as per my recent experience which i covered in my other answer.
Also please troubleshoot further to understand more on the inner stack details.
As #Joey Cai mentioned in his answer ,Change your **Action to take when request is not authenticated in App Service**
Authentication/Authorization section in the azure portal from LogIn with Azure Active Directory to **Allow Anonymous requests**. As shown on the picture below:
If above option doesn't work out try below:
Try changing the application manifest of the application definition on Azure to set the "oauth2AllowIdTokenImplicitFlow" property to true from false.
Go to the Azure Portal,
Select to Azure Active Directory
Select App Registrations
Select your app.
Click on Manifest
Find the value oauth2AllowIdTokenImplicitFlow and change it's value to true
Click Save
Asp.net UseOpenIdConnectAuthentication not working in Azure
Hope it helps.

Get out the debug before entering the action in ASP.NET Core

I need to return Roles.Claims in ASP.NET Core for dynamic permission.
When I enter this url : https://localhost:44390/api/Role/GetRoleClaims/1008
this action will be executed:
[HttpGet("GetRoleClaims/{id}")]
public Task<Role> GetRoleClaims(int? id)
{
return _roleManag.ClaimsOfRole(id.Value);
}
then execution goes to the service layer and runs this method:
public Task<Role> FindRoleIncludeRoleClaimsAsync(int roleId)
{
return Roles.Include(x => x.Claims).FirstOrDefaultAsync(x => x.Id == roleId);
}
public async Task<Role> ClaimsOfRole(int id)
{
var role = await FindRoleIncludeRoleClaimsAsync(id);
return role;
}
The variable role is filled with the correct data, but it does not get back to the action after this line return role;
It shows the web browser and shows this :
What is the problem? How can I solve this problem?
Your ClaimsOfRole is still an async method and you are missing an await here:
[HttpGet("GetRoleClaims/{id}")]
public async Task<Role> GetRoleClaims(int? id)
{
return await _roleManag.ClaimsOfRole(id.Value);
}
Your Secure Connection Failed error has nothing to do with that code. It may be to do with:
asp.net core recently moved to https by default
https requires a certificate
The default for development is that microsoft has your machine generate a self-signed certificate
Browsers show an error message because the self-signed certificate isn't authorised by a certificate authority.
Options:
Look and see if your website is also served on a port for http:// instead of https
Use a different browser is see if it gives you a 'accept this connection' option
Work down MS's page on e.g. ASP.NET Core 2.1.0-preview1: Improvements for using HTTPS
Either that, or you've just typed in the wrong port. Where did you get 44390 from?

Rewriting Url in ASP.Net MVC

I am struggling over this issue since yesterday.I am working on a web application which includes email service.Email includes 'link' to a certain page of that application.
Now:I have 2 scenarios:
1) If the user is logged in(in the application) already and he hit
the url he got in his email,the link will open perfectly.
2) If the user is not logged in(in the application) then the url
will not open and will redirect itself to the login page with the
functionality added in the BaseController.
*
Now what I want is when the user logs in after hitting the url and on
successfully login the user gets redirect to the link provided in the
Email.
*
for eg: If the user gets an email to the detail page of an employee,So on successfully login the user gets redirect to the Detail page of the employee.
Something like appending the redirecturl to the login page.
I think rewriting url is what I should be doing.
But I dont know how can I use that in this case.Help me out.
The default project template that comes with ASP.NET MVC 5 behaves exactly as you describe.
If you want to redirect to a custom login URL, reconfigure the LoginPath property of the CookieAuthenticationOptions object
LoginPath = new PathString("/Account/Login")
In the default template this is done in the Startup.Auth.cs class.
NOTE: If you are using an old version of ASP.NET MVC, the default project template behaved in the same way. But previously this was implemented using Forms Authentication, so in order to redirect to a custom login URL you would then have to set the loginUrl attribute of the <forms> tag in the Web.config file
By default if a user tries to access the authorized page when he is not authorized the automatically gets redirected to the log in page or the page which is configured in web.config file for the element. And you can see the query string returnUrl having the url that was tried to access initially get appended to the log in url.
To access the return url, include a new parameter as returnUrl and maintain the return url in a hidden field by model data to access on post back for redirection.
If the user is authenticated then on post back then redirect the user to the specified page what he intended to go for.
I don't remember exactly but few month ago I implemented similar functionality and i had to save returnUrl explicitly (due to MVC bug or something) - Refer this link
AccountController.cs - Snapshot
[HttpGet]
[AllowAnonymous]
public ActionResult Login(string returnUrl, string userName)
{
// You login method logic....
// Add this line to save the returnUrl value
ViewBag.ReturnUrl = returnUrl;
}
Login.cshtml - Snapshot
#using (Html.BeginForm("Login", "Account", FormMethod.Post ,new {ReturnUrl = ViewBag.ReturnUrl}))
{
<input type="hidden" name="ReturnUrl" value="#Request.QueryString["ReturnUrl"]" />
// .....
}
See if this helps in your case.

Web Security not working in Chrome and Firefox

I am currently using Web Security. User can log in using this code
if (WebSecurity.Login(loginRequest.EmailAddress, loginRequest.Password))
{
FormsAuthentication.SetAuthCookie(loginRequest.EmailAddress, false);
var userDetails = new string[2];
userDetails[0] = loginRequest.EmailAddress;
var currentUSerRole = Roles.GetRolesForUser(loginRequest.EmailAddress);
userDetails[1] = currentUSerRole[0].ToString();
return response = Request.CreateResponse(HttpStatusCode.Accepted, userDetails);
}
The login code works, but IsAuthentcated always returns false and CurrentUsername always return -1 and all Websecurity methods are not worked well when I run my application on Chrome and Firefox browsers. But it's working good on IE Browser.
What did I missed? Is it any cors issue? or anything else? I found a lot of answers from Google, but they haven't helped me.
Any One Help Me
As per My knowledge
FormsAuthentication.SetAuthCookie(string, bool); can be used to login/logout a particular user with the string a username and bool value as true/false for log in/out.
FormsAuthentication.SetAuthCookie("user", true); will log in the user and the WebSecurity will have its userID.
FormsAuthentication.SetAuthCookie("admin", false); will log out admin and will remove its userID from WebSecurity.
so you should try FormsAuthentication.SetAuthCookie("user", true);

Categories