How to know who is(are) the currently logged in user(s) - spring-mvc

How to know who is(are) the currently logged in user(s) in a spring MVC web application so that we can present the jsp views accordingly

Use below code to get logged in User details.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof User) {
return ((User) principal);
}
}
And in JSP page you can get logged in user details like below.
${pageContext['request'].userPrincipal.principal.id}

Related

how to get to know the details about who is currently logged in user in spring mvc

Say i have a User whose entry is in the Real_User table and now as soon as the user is authenticated, how to pull the details of the user from the Real_User table.
The Table is like this Real_User ( email(PK) , firstName, lastName , password, enabled , role )
I wish to know all the details from the above mentioned table after authentication is done so that i can prepare the views accordingly.
You will get the id from the user principal object and that id you can pass to your findById(id) method and can get the user details.
You can create a method to get Current logged in user.
public User getCurrentUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof User) {
return ((User) principal);
}
}
return null;
}

Integrate Hangfire Dashboard With ASP.NET Application based Login

My ASP.NET project uses a login screen which allows the users to enter credentials in order to sign in to the web application. At that point, the User object is set in the Session object. The User object contains information about the role of the user logged in. Now, I want the hangfire dashboard to be a link inside the application visible once the user logs in. And upon clicking the link, based on if the user's role is appropriate, I want to show or restrict the dashboard. How do I do this? I am not able to access the session object in the OWIN startup.cs class.
You can restrict access to the dashboard using an IAuthorizationFilter defined like this:
public class DashboardAuthorizationFilter : IAuthorizationFilter
{
public bool Authorize(IDictionary<string, object> owinEnvironment)
{
// In case you need an OWIN context, use the next line,
// `OwinContext` class is the part of the `Microsoft.Owin` package.
//var context = new OwinContext(owinEnvironment);
var ok = false;
if (HttpContext.Current != null && HttpContext.Current.User != null)
{
ok = IsAuthorizedForDashboard(HttpContext.Current.User);
}
return ok;
}
}
Where IsAuthorizedForDashboard is a function you will need to create.
Then register the filter like this:
app.UseHangfireDashboard(DashboardPath,
new DashboardOptions {
AuthorizationFilters = new List<IAuthorizationFilter> {
new DashboardAuthorizationFilter() }
});

ASP.net identity - external login - won't log out

In my application, all my authentication happens with Google - ie - all my users are Google Accounts.
I don't need users to need to register in my app, just sign in using a Google account. However, I do want to manage Roles for the users with ASP.net Identity (I think)
With that in mind, on successful external authentication, I create an ASP.net Identity user (if one doesn't exist)
So, I've got my ExternalLoginCallback as follows:
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var authenticationManager = Request.GetOwinContext().Authentication;
var loginInfo = await authenticationManager.GetExternalLoginInfoAsync();
//successfully authenticated with google, so sign them in to our app
var id = new ClaimsIdentity(loginInfo.ExternalIdentity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(id);
//Now we need to see if the user exists in our database
var user = UserManager.FindByName(loginInfo.Email);
if (user == null)
{
//user doesn't exist, so the user needs to be created
user = new ApplicationUser { UserName = loginInfo.Email, Email = loginInfo.Email };
await UserManager.CreateAsync(user);
//add the google login to the newly created user
await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
}
return RedirectToLocal(returnUrl);
}
Idea being, I can now manage users, add roles, check if users are in roles, etc....
Firstly, is this a sensible approach? Or have I over complicated it?
One issue I'm having, however, is with logging out of my application
My Logout action looks like:
public ActionResult LogOut()
{
HttpContext.GetOwinContext().Authentication.SignOut();
return RedirectToAction("Index", "Home");
}
My Index action is decorated with the [Authorize] attribute -
However, when I 'logout' - it redirects to Home.Index - but I still seem to be logged in?
According to this ASPNet Identity Work Item, this is by design, and you need to call directly to Google's API in order to log the user out.
completing the post Logout link with return URL (OAuth)
Here is a solution that work for me :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return Redirect("https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=https://[url-of-your-site]");
}

Implement OAuth in mvc 3. How to store user's details in database

I'm trying to use OAUth in my existing mvc3 Application. I was able to authenticate the user using the below code
[System.Web.Http.AllowAnonymous]
//This action method is executed after the authentication from Facebook
public ActionResult ExternalLoginCallback(string returnUrl)
{
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
//Here i'm setting the Authentication cookie
FormsAuthentication.SetAuthCookie(result.UserName, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
The above code works fine . However my mvc3 application uses asp.net membership. My entire application uses Guid id's which come from the database but i'm unable to figure out how to maintain the database for the OAuth Authenticated Users so that i can generate guid id.If i'm going in a wrong direction correct me. Any help on this is highly appreciated.
Well as you are using asp.net membership.
Following is the way to register user
MembershipUser newUser = Membership.CreateUser(username, Password,Email);
Get user ID
newUser.ProviderUserKey

Storing User Information in Session with aspNetMembershipProvider

I'm developing an application in .NET mvc2. I'm using aspnetMembershipProvider for User registration and related activities. I need some custom information about user that I stored in a separate table (sysUser for example) and linked it to aspnetUser table through foreign key.
After login I need to fetch user's credentials from sysUser table and push it to the session. For this Account controller's Logon method seemed best to me and I pasted following code in my Logon ActionResult
if (!ValidateLogOn(userName, password))
{
return View();
}
FormsAuth.SignIn(userName, rememberMe);
ApplicationRepository _ApplicationRepository = new ApplicationRepository();
MembershipUser aspUser = Membership.GetUser(userName);
SessionUser CurrentUser = _ApplicationRepository.GetUserCredentials(aspUser.ProviderUserKey.ToString());
//Session["CurrentUser"] = CurrentUser;
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
The code is working perfectly for me and put my desired information in the session but the thing is that if a user selects Remember me and on his next visit he won't have to Log in and I would not find my desired information in the Session. Where should I put my code that stores the user information in the session?
FormsAuthentication.SetAuthCookie(userName, saveLogin);
MSDN Documentation for SetAuthCookie Method

Resources