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.
Related
Title- asp.net-mvc5 Auto logout How to make form auto logout after sometime in asp.net-mvc5 and redirect automatically to login page
You need to create a session variable on the Login method.
The session will be created by Session["Userid"]=Userid;. Then you need to create custom attribute to check session timeout.
Steps you need to follow are:
Create a session variable in login() (Post method)
Create a class file in your MVC project.
Copy and paste below code in that file.
public class SessionTimeOutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Controller controller = filterContext.Controller as Controller;
HttpContext httpContext = HttpContext.Current;
var rd = httpContext.Request.RequestContext.RouteData;
string currentAction = rd.GetRequiredString("action");
string currentController = rd.GetRequiredString("controller");
if (HttpContext.Current.Session["UserId"] == null)
{
filterContext.Result = new RedirectResult("~/Account/Login?ReturnUrl=" + currentController + "/" + currentAction);
return;
}
base.OnActionExecuting(filterContext);
}
}
add [SessionTimeOut] attribute on each controller.
[SessionTimeOut]
public class ControllerName : Controller
{
You should add Statup.cs file.
1. Add Statup Class your project from new item lists.
2. Add following line in ConfigureService.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.EnableEndpointRouting =
false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddAuthorization();
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
// we do this because we trust the network
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
x.Cookie.Name = "WriteSomeThings";
x.Cookie.SecurePolicy = CookieSecurePolicy.Always;
x.Cookie.SameSite = SameSiteMode.Strict;
x.Cookie.HttpOnly = true;
x.Cookie.IsEssential = true;
x.SlidingExpiration = true;
x.ExpireTimeSpan = TimeSpan.FromHours(8);//For Auto Logout
x.LoginPath = "/User/LogOn";
x.LogoutPath = "/User/LogOff";
x.AccessDeniedPath = "/Home/AccessDenied";
});
}
x.ExpireTimeSpan = TimeSpan.FromHours(8) => This line allow us to logout automatically after 8 hours.
If you need full user management check this video
https://youtu.be/912q3TEF25U
Software development template with role-based user management using ASP.NET MVC 5. Try it for free
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.
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 = "/", ...
I have this following mvc application
The problem is when Im trying to assign profile values:
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Email, model.Password);
if (createStatus == MembershipCreateStatus.Success)
{
//Adding role
MembershipService.AddDefaultRole(model.Email);
FormsService.SignIn(model.Email, false /* createPersistentCookie */);
//Add other initial profile data
HttpContext.Profile["FirstName"] = model.FirstName; //PROBLEM
HttpContext.Profile["LastName"] = model.LastName; //PROBLEM
return RedirectToAction("List", new { area = "", controller = "Requests" });
}
else
{
ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
}
Inside FormsService.SignIn(model.Email, false):
public void SignIn(string email, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
}
How come after calling FormsAuthentication.SetAuthCookie, User isn't yet authenticated?
I'm getting an error b.c. im trying to assign some profile value to anonymous user .
Any idea?
When you set a cookie, it's added to the Response, but the IsAuthenticated bool is set from the Request. After setting the authentication and setting up your session variables, you should redirect to another page, like the home page or the original request.
I want to use the Request, Response properties of System.Web.Mvc.Controller class to set and read cookies in the HTTP request and response. The reason to do so is - it obviates the need for writing utility classes that read from requests and populate data in some helper class. I can push all such code in custom base controller (from which all my controllers are derived from).
So I have got following code in my `BaseController'
if (Request != null)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
HttpContext.User = new GenericPrincipal(new GenericIdentity(authCookie.Value), null);
Thread.CurrentPrincipal = HttpContext.User;
}
}
but the Request is always null. How is this populated?
If you have this code in the constructor of your base controller then it is normal. You need to put it in the Initialize method. Also what you are doing shouldn't be done in a controller. Looking at your code you seem to be populating the HttpContext.User property: this should be done in a custom Authorize action filter.
For example:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
var result = base.AuthorizeCore(httpContext);
if (result)
{
var authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
httpContext.User = new GenericPrincipal(new GenericIdentity(authCookie.Value), null);
Thread.CurrentPrincipal = httpContext.User;
}
}
return result;
}
}
and then decorate your base controller with this attribute:
[MyAuthorize]
public abstract class BaseController: Controller
{}
Notice that this attribute requires the user to be authenticated in order to give access to the corresponding action so use it only on controllers/actions that require authentication.