Spring Session: Update Logged in user object in redis immediately - spring

I have two web applications (A and B).
The first web application (A) is used as a reverse proxy using spring-cloud.
I'm using spring-session to store the sessions in a redis database for both applications.
The problem
When I modify a field (e.g name) of the current (logged in) user, the current logged in user object is not updated immediately and as a result, when I'm trying to retrieve current logged in user in a next call (via #AuthenticationPrincipal) I get a non-updated user object.
My custom user details object:
public class CustomUserDetails extends my.package.User implements org.springframework.security.core.userdetails.UserDetails, java.io.Serializable {
// ...
}
How can I update the current user object immediately?

Recently I've had the similar issue and I resolved it in the following manner:
1.Created a custom Authentication class
public class MyCustomAuthentication implements Authentication {
private UserDetails userDetails;
public MyCustomAuthentication(UserDetails userDetails) {
this.userDetails = userDetails;
}
...
#Override
public Object getDetails() { return userDetails; }
#Override
public Object getPrincipal() { return userDetails; }
#Override
public boolean isAuthenticated() { return true; }
...
}
update userDetails object with some fresh data (I guess, 'name' in your case)
Set new authentication created from userDetails in SecurityContextHolder
SecurityContextHolder.getContext().setAuthentication(new MyCustomAuthentication(userDetails));
Hope you will find that helpful.

Related

Thymeleaf get current logged in username as String

I am new to Thymeleaf and currently working on a user management tool with Springboot. First of all the account need to be logged in to see the personal data. My problem is, to get the current logged in username, which is an email in my case and call the Rest-API with the url "/{email}" with Getmapping?
My idea was to Get the securitycontextholder.getcontext().getprincipal() and pass it to a Request call . Finally display the data
this is my GetMappping from the controller layer
#GetMapping("/{email}")
public ResponseEntity getApplicantByEmail(#PathVariable String email){
return new ResponseEntity(applicantService.getApplicantByEmail(email), HttpStatus.OK);
}
You can make the current user available to the Thymeleaf model by introducing #ControllerAdvice:
#ControllerAdvice
public class CurrentUserAdvice {
#ModelAttribute("currentEmailAddress")
public String emailAddress(Authentication authentication) {
return authentication.getName();
}
}
This will make the model attribute currentEmailAddress available in Thymeleaf templates.
If you have a custom domain object as the principal in Authentication, you can make the entire user available in the model using the same pattern:
#ControllerAdvice
public class CurrentUserAdvice {
#ModelAttribute("currentUser")
public MyUser user(#AuthenticationPrincipal MyUser user) {
return user;
}
}

Accessing UserDetails object from controller in Spring using Spring security [duplicate]

This question already has answers here:
How to get active user's UserDetails
(9 answers)
Closed 5 years ago.
I would like to access some user details from session. I am using spring security and custom authentication by overriding loadUserByUsername(String username) method.
I am returning a user and would like to access it from within my controller. I tried the principal object but i can not reach to the companyId field of my ESecurityUser object.
Any help would be appreciated..
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
ESecurityUser user = new ESecurityUser();
user.setUsername("hello");
user.setPassword("world");
user.setCompanyId(199);
Set<EAuthority> authorities = new HashSet<EAuthority>();
EAuthority authority = new EAuthority();
authority.setAuthority("ROLE_ADMIN");
authorities.add(authority);
user.setAuthorities(authorities);;
return user;
}
Sample Controller Code
#RequestMapping("")
public String toPeriodicAdReport(#ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper,
Model model,Principal principal) {
//What to write here so that i can access to authenticated user`s companyId field..
return "Test";
}
You can use the annotation #AuthenticationPrincipal to directly access ESecurityUser.
#RequestMapping("")
public String toPeriodicAdReport(#ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper,
Model model, #AuthenticationPrincipal ESecurityUser principal) {
principal.getCompanyId();
return "Test";
}
You were not far...
The Principal that the SpringMVC machinery passed to a controller method is the Authentication token that identifies the user. You must use its getDetails() method to extract the ESecurityUser that you returned from your loadUserByUsername
Your code could become:
#RequestMapping("")
public String toPeriodicAdReport(#ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper,
Model model,Principal principal) {
ESecurityUser user = (ESecurityUser) ((Authentication) principal).getDetails();
// stuff...
return "Test";
}
ESecurityUser e = (ESecurityUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
This is working for me..

AuthenticationProvider & Bean #PostConstruct ordering

For a login page, I have an authentication method as:
#Component(value = "customSpringAuthentication")
public class CustomSpringAuthentication implements AuthenticationProvider {
#SuppressWarnings({ "serial", "deprecation" })
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
...
return authUser;
}
}
Also I have a bean, which is called after authentication:
#Component(value = "loggedinUserBean")
#Scope("session")
public class LoggedinUserBean {
private AuthUser authUser;
private boolean isAdminUser = false;
#PostConstruct
public void initModel() {
....
authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication();
....
}
}
My question is when I am trying to access "authUser" in initmodel()method, it is null.
I know that authenticate method did not return null. But somewhat I realized that initmodel() works few miliseconds before authenticate returns. So that it can't get authetication object properly. How can I ensure/define ordering that without authenticate() returns loggedinuser is not initalized?
To actually answer your question, the initModel() method will be run immediately after your LoggedinUserBean object is created. This doesn't mean that its initialised. Initialisation and creation are two separate things. When an object is created, the JVM allocates memory for that object and all its fields. All the fields are null because they don't have values but the memory is set aside for you to populate the fields. Initialisation means that authUser will not be null because you have given it a value and you will only give it a value when authenticate() is called. As long as you aren't setting authUser anywhere else, then you are fine.
TL;DR: Its already guaranteed by Spring Security that your authUser is null until the user successfully authenticates using one of your authentication providers. If authUser remains null after then entire springSecurityFilterChain has been tried then the login attempt has failed.

Spring session based javax constraint validation

What I'm trying to accomplish is to access my Spring Session within a custom constraint
Sample scenario:
Custom constraint #UniqueEmail verifies that the email is not already in use in the system. This validation is performed on the edit endpoint and should be ignore if the user didn't change the email, 1st: because there's no need for it and 2nd: because querying the db for that email will actually return a result, which is the user itself, although there's no way of telling it without accessing the session
This works:
If I use model attributes with custom editor though #InitBinder I can set a property in the to-be-validated bean before the validation occurs like so
#InitBinder(value="myModelObj")
protected void initBinder(WebDataBinder binder, HttpSession session) {
User user = (User) session.getAttribute("user");
binder.registerCustomEditor(User.class, "user", new UidPropertyEditor(user));
}
#RequestMapping(...)
public String updateUser(#Valid #ModelAttribute("myModelObj") MyModelObj form){
...
}
MyModelObj has an attribute which will be replaced with the actual session user. Problems:
There must be a property in the bean to hold the user, even though it is not editable through the web form
The web form must submit this property as well, in my case using an input[type="hidden"] field (user can change it at will, we never trust what the user sends)
This does not work
The new endpoints have to use #RequestBody rather than #ModelAttribute, which means that (afaik) #InitBinder won't work anymore, hence losing access to the session object.
How (if possible) can I access the session from within the custom constraint?
public class EmailIsUniqueStringValidator implements ConstraintValidator<EmailIsUnique, String> {
#Autowired
private UserDAO userDAO;
HttpSession session; //Somehow initialized
#Override
public void boolean isValid(String email, ConstraintValidatorContext context) {
User user = (User) session.getAttribute("user");
if(user.getEmail().equals(email)){
return true; // No need to validate
}
else if(userDAO.emailInUse(email)) {
return false;
}
}
Non-ideal approach:
What I'm doing now is performing the session-dependant validations in the controller manually, which means I have 2 points where validation is performed.
There are some other interesting options in this post too, but if there was a way to access the session...
Thanks in advance
This can be achieved using RequestContextHolder like so:
public class EmailIsUniqueStringValidator implements ConstraintValidator<EmailIsUnique, String> {
#Autowired
private UserDAO userDAO;
HttpSession session;
#Override
public void boolean isValid(String email, ConstraintValidatorContext context) {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
session = attr.getRequest().getSession();
User user = (User) session.getAttribute("user");
if(user.getEmail().equals(email)){
return true; // No need to validate
}
else if(userDAO.emailInUse(email)) {
return false;
}
}

How to integrate spring security and spring social to have the same execution flow in both cases?

I am using spring security for the authentication purposes in my project wherein after successful authentication, I get the principal object inside which the various details are stored.
This principal object is passed to various methods which allow the entries to be reflected in the database against the current user. In short, principal helps me in giving principal.getName() everywhere i need it.
But now when I login through spring social then I do not have principal object of Principal in hand, instead I have implemented MyPrincipal class --->
public class MyPrincipal implements Principal {
public String name;
public boolean flag;
public boolean isflag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public void setName(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
Then in the social login handler, I am adding the current username and flag value to myPrincipal object, and forwarding the user to the same home page where the spring security forwards in case of normal login.
MyPrincipal myPrincipal = new MyPrincipal();
myPrincipal.name = username;
myPrincipal.socialFlag = true;
modelMap.addAttribute("myPrincipal", myPrincipal);
return new ModelAndView("forward:/home");
Adding this object in session by annotating class with
#SessionAttributes({"myPrincipal"})
Now from here on-wards I want the flow to be handed over to the home page with all the functionality working for the user correctly. But each method is taking Principal principal as argument, just like this -->
#RequestMapping(value = {"/home"}, method = RequestMethod.POST)
#ResponseBody
public ModelAndView test(ModelMap modelMap, Principal principal) {
String name = principal.getName();
}
There are two different things going around in both cases-
Normal login is giving me principal directly but social login is giving me it in session attributes.
I do not want to pass principal as parameters even in case of normal spring security login, instead here also I want to put it in session attribute.
How can I do this and where to make the changes when I have implemented my own authentication provider.
I don't think I fully understand...However, in general it shouldn't be necessary to pass principal instances around. Use org.springframework.security.core.context.SecurityContextHolder.getContext() to get a hold of the context then call SecurityContext.getAuthentication().getPrincipal() or SecurityContext.getAuthentication().getDetails().

Resources