ASP.NET MVC Logout with Form Authentication - asp.net-mvc-3

I have a Logout action on a controller as so:
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session["UserCredential"] = null;
return RedirectToAction("Index", "Home");
}
This working in google chrome browser. but when I am using my web application with firefox browser (latest version) after login and logout from first time. and when I am doing login again to application and pressing on logout button, I am not able to logout from web application. Request.IsAuthenticated is returning me true value.
For Login I used following action:
[HttpPost]
public JsonResult Login(string userName, string password)
{
User oUser = oRepository.GetUser(userName,password);
Session["UserCredential"] = oUser;
if (oUser != null)
{
if (oUser.IsVerified)
{
string url = Request.Url.AbsolutePath;
FormsAuthentication.SetAuthCookie(userName, false);
return Json(new { res = 1, RedirectUrl = Url.Action("Index", "Home") }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { res = 0, RedirectUrl = "" }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { res = -1, RedirectUrl = "" }, JsonRequestBehavior.AllowGet);
}
Anyone have idea what i have to do to solve my problem with firefox browser.

I am not 100% certain but you could try this.
I've observed that the way FormsAuthentication is implemented in ASP.NET, the SignOut method does not clear the ASPXAUTH cookie. So, on sign-out, what I usually do is, I clear all the cookies in the response myself manually.
You might try doing that. At the very least, in your case, you should clear 2 cookies:
1) The FormsAuth cookie. You can get the name of the cookie by accessing a CookieName (or some such) static field of the FormsAuthentication class.
2) The ASP.NET session cookie. Check the cookie names in the Immediate Window (print the Cookies collection).
To clear the cookies, just add new cookies to the response object's cookie collection with the same names as the older cookies and then set their expiry date to a date in the past.

Related

How to redirect from Identity Area to Admin in ASP.NET CORE 2

I cant redirect from Identity Area:
if (role=="Admin")
{
return RedirectToAction("Index","Home",new { Area=Input.Role ,id=9});
}
To Admin Area Controller-Home,Action-Index.Always redirect me to Index in the Identity Area;
looking at your code I am still scratching my head as to the reason that someone would specify the Role at login. Can you articulate the reasoning behind this?
Simplest answer is inline with the code within the OnPostAsync(); that resides in
//this because of the routes you have in StartUp.cs
[Authorize(Roles ="Admin")]
[Area("admin")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Login.cs Page...
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Username, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
var user = await userManager.GetUserAsync(User); // Claims Principle
if (await userManager.IsInRoleAsync(user, "Admin"))
{
//SIMPLEST ANSWER since you using mixed environment with PAGES
return LocalRedirect("~/admin");
}
//TODO:
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
Check your issues below one by one:
I got error A method 'CakeStore.App.Areas.Admin.Controllers.HomeController.Index (CakeStore.App)' must not define attribute routed actions and non attribute routed actions at the same time, you should not define [HttpGet(Name ="AdminPanel")] and [Route(nameof(Admin) + "/[controller]")] at the same time.
//[HttpGet(Name ="AdminPanel")]
[Area(nameof(Admin))]
[Route(nameof(Admin) + "/[controller]")]
public IActionResult Index()
{
return View();
}
For var role = this.roleManage.GetUrl(Input.Username);, it will retrive the role by username, check whether you got expected role Admin.
return RedirectToAction("Index","Home",new { Area=Input.Role ,id=9});, you did not define id in Index, there is no need to add id route.

SignInStatus always returns Success on TwoFactorAuthentication is enabled in webapi using asp.net identity

I am implementing 2 factor authentication in WebApi, asp.net identity and OWIN. Every time I log in, I get SignInStatus = Success never reaches to SignInStatus = RequiresVerification though user TwoFactorAuthentication is enabled.
Below are some code snippets,
Startup.cs:
private void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
app.UseOAuthBearerTokens(OAuthOptions);
}
Action method for enabling two factor authentication,
[HttpPost]
public async Task<IHttpActionResult> EnableTwoFactorAuthentication()
{
var user = await this.AppUserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
IdentityResult result = await this.AppUserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
await this.AppSignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
}
return Ok();
}
Please suggest a solution.
If you get stuck here, one way to solve the problem is to copy the methods from SignInManager directly into your code and call those instead so you can step through the methods and see why you are getting the wrong status. For me the problem ended up being that I instantiated my UserManager with:
new MyUserManager()
instead of the right way:
HttpContext.GetOwinContext().Get<MyUserManager>()
I was using this as my template for setting it up:
https://github.com/adamtuliper/ASP.NET-Identity-Samples/tree/master/BasicTemplate%20-%20Two%20Factor/BasicTemplate
SignInManager return RequiresVerification if :
dbo.ASpnetUsers has for user set to true TwoFactorEnabled and EmailConfirmed and user email should be confirmed, email not be empty or null.
var result = SignInManager.PasswordSignIn(usernameIdentity, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", returnUrl);
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}

HttpClient always do Basic Authentication check after provide an authorization header?

The web api control, UserControl, has two methods, RetrieveUserID which needs Basic Authorization check
[HttpGet]
[Route("RetrieveUserID/{strUsername}")]
[Authorize]
public string RetrieveUserID(string strUsername)
{
//retrieve userID and return it
......
return strUserID;
}
Another method, FailAuthenticationReason, is used if fail to retrieve userID, it returns the detail fail info such as wrong username, wrong password, account is locked out, etc. which doesn't need to do any authentication check
[HttpGet]
[Route("FailAuthenticationReason/{strUsername}")]
public string FailAuthenticationReason(string strUsername)
{
//retrieve detail failed reason
......
return strFailedReason;
}//End of
It works well when I use a browser to check them. But when I use it in my app, after I provide the authorization header and fail to retrieve userID because of incorrect username and/or password, it also do the authorization check when it call FailAuthenticationReason
var authData = string.Format("{0}:{1}", entUsername.Text,entPassword.Text);
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
App.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
var uri = new Uri(string.Format(App.strWebAPIURI + "/RetrieveUserID/{0}", entUsername.Text));
try
{
var response = await App.httpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
......
}
else
{
//Fail to pass authorization
uri = new Uri(string.Format(App.strWebAPIURI + "/FailAuthenticationReason/{0}", entUsername.Text));
response = await App.httpClient.GetAsync(uri);
......
}
How can the program call FailAuthenticationReason without the authorization check?

Destroy HttpSession on logout Spring

I'm working on a spring web project and created HttpSession for validating login and access of jsp pages. I haven't used the standard spring technique of security. However i'm setting the session on the time of login and matching this session on each webService call.
Now on Logout i want to redirest the user on login screen and destroy the session so that nothing can be accessible without relogin. I don't know how to destroy the session.
// Here is code of setting the session
StaffModel record1 = (StaffModel) data.get("records"); // separating records
if(record1 != null)
{
SessionData sessionData = new SessionData();
sessionData.setMobileNo(record1.getMobileNo());
sessionData.setCityName(record1.getCity());
sessionData.setUserName(record1.getFirstName());
sessionData.setUserRole(record1.getRole());
sessionData.setSessionID(UUID.randomUUID());
sessionObj.setAttribute("SessionData" , sessionData); // setting session Data
}
// in jsp i'm accessing these sessions
<script>
var sessionData;
var sUserName;
var sMobileNo;
var sUserRole;
var sCityName;
var sSessionId;
function sessionCall()
{
sUserName = '<% SessionData obj = (SessionData)session.getAttribute("SessionData");
out.print(obj.getUserName());
%>';
sMobileNo = <% out.print(obj.getMobileNo()); %>;
sUserRole = '<% out.print(obj.getUserRole()); %>';
sSessionId = '<% out.print(obj.getSessionID()); %>'
sCityName = '<% out.print(obj.getCityName()); %>';
sessionData =
{
"mobileNo" : sMobileNo,
"cityName" : sCityName,
"userName" : sUserName,
"userRole" : sUserRole,
"sessionID": sSessionId
};
document.getElementById("staffName").innerHTML=sUserName;
document.getElementById("staffRole").innerHTML=sUserRole;
}
</script>
Problem : on click of logout button destroy the HttpSession
Help Please
// Do this on your controller
#RequestMapping(value = "/logout")
public String logout(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
return "redirect:/"; //Where you go after logout here.
}
// do this on your jsp page
Logout
You can always add HttpSession session as a parameter in a Controller method. Do it and try:
session.invalidate();
P.S.: Seems like using Spring Security would be way easier for you, you should think about changing your configuration.

Cookie becomes session on postback

I have a cookie which is set when a user accesses the page /auth/ of my MVC3 application.
When a user posts the form data back to the server I modify the cookie by changing the value it has assigned. I then use Response.Cookies.Set(mycookie); to change the cookie to the value of mycookie.
The issue I am having is that when the page is first loaded 'get' request the cookie appears as a cookie. Upon receiving the post response back the cookie now appears as a session with a completely different expiry date.
CODE::
[HttpGet]
public ActionResult Auth()
{
var cookie = Request.Cookies.Get(login_cookie);
if (cookie == null || string.IsNullOrEmpty(cookie.Value))
{
Response.Cookies.Add(new HttpCookie(login_cookie) { Expires = DateTime.Now.AddMinutes(5), Value = "0", HttpOnly = true, });
}
.....
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Login loginform)
{
int attempts = 0;
HttpCookie login_cookie_data = Request.Cookies.Get(login_cookie);
....
Response.Cookies.Set(login_cookie_data);
return View();
}
Resolved
Issues was with machine. I restart and it sorted all issues.
Add the root path when creating your cookie in the cookie constructor.
... new HttpCookie(login_cookie) { Path = "/", ...

Resources