How to retrive logged in user data in spring mvc and hibernate - spring

I need to get current loggedin user's details along entertain session.Is there any poissible to do it in Spring and hibernate
I am new to spring and hibernate...Help me guys.

There are serveral ways in which you can accomplish this. In a controller you can inject a Pricipal as a parameter.
#RequestMapping()
public void getPricipal(Principal principal) {
Customer c = (Customer) pricipal;
}
You should also be able to inject the UserDetails directly as well. Spring will resolve it for you. Your Customer class must implement UserDetails
#RequestMapping()
public void getPricipal(Customer customer) {
}
As for having all details, you should be able to access the firstname, lastname etc, if you've implemented your own UserDetailsService where you return your custom UserDetails (Customer).

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;
}
}

Protecting method calls in Spring multiactionController using methodNameResolver

I am using Spring 3 and implemented MVC using simpleUrlMapping. I am having CustomerController class. In CustomerController I am having three methods:
View customer
Add customer
Delete customer
The above actions are getting called using method name resolver.
My requirement over here depending upon the logged in user and privilege I want to protect the corresponding method calls.
Delete customer method should be called by the privilege user and not by all the user.
I am using Spring Security as well. Is there any way to protect the delete customer method with Spring security?
options:
#RequestMapping
public void deleteCustomer(HttpServletRequest request) {
if(request.isUserInRole("ROLE_ADMIN"){
// do deletion
};
}
or use #EnableGlobalMethodSecurity
#PreAuthorize("hasRole('ROLE_ADMIN')")
#RequestMapping
public void deleteCustomer(HttpServletRequest request) {

Spring social oauth how to get sign in provider in SocialUserDetailsService?

In my Spring Social app, I'm trying to integrate certain Social Login functionalities. After being redirected from, for example Twitter, Spring calls the following to look up the user.
public class SimpleSocialUserDetailsService implements SocialUserDetailsService {
#Override
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException {
/*
Commented
*/
}
However, since I will have multiple social login providers, the userId alone is not enough for me to look up the user in my database. I need at least the sign in provider or access token.
Is there anyway to get the sign in provider, or more information, in SocialUserDetailsService? Any other way to solve my problem would be great!
Spring Social is rather Agnostic to the Sign in Providers when properly implemented. I believe you are confused on the flow of Spring Social. At the point you describe spring social has already looked up the connections table and presumably found a record, so it looks up your user table for the user matching with userId (as referenced in the connections table) This is usually associated with the username.
This connection <-> User matching is done in the SocialAuthenticationProvider before calling the SocialUserDetails loadUserByUserId method.
So the SocialAuthenticationProvider already does what you ask for by querying the usersConnectionRepository and comparing the provider connection to find the appropriate user.
Now for your case you would can go ahead and override the user service that you have setup. As long as the userId used on the doPostSignUp call matches the one you look up in the loadUserByUserId, the proper user will be retrieved.
This is a sample:
Wherever your signup logic is executed, you call the doPostSignup and pass the desired user id (Username or another uniquely identifiable String)
ProviderSignInUtils.doPostSignUp(variableForNewUserObject.getId().toString(), request);
Now you Override the loadUserByUserId in SimpleSocialUserDetailsService
#Autowired
private UserDetailsService userDetailsService;
#Override
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException {
UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
return (SocialUserDetails) userDetails;
}

Get User details from Session in Spring Security

I am new to Spring MVC and Spring Security. I have performed log-in and registration functionality using Spring security and MVC. I am not able to find any way for session management .
I want to access some user details on all the pages like (email, name,id,role etc).
I want to save these to session object so I can get these on any of the page.
I get the following way for session in spring
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
auth.getPrincipal();
But from the object returned by this I can get only username and password details.
But I need to access more details of that user.
Is there any way to do this by saving it to session and the get on the jsp page?
or is there any OOTB way in spring to get this done?
Please help me to get solution for this.
Thanks in advance.
I want to get my model class object to be returned from SecurityContextHolder.getContext().getAuthentication().getDetails(); For this what I need to configure.
Regards,
Pranav
You need to make your model class implement the UserDetails interface
class MyUserModel implements UserDetails {
//All fields and setter/getters
//All interface methods implementation
}
Then in your spring controller you can do this:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object myUser = (auth != null) ? auth.getPrincipal() : null;
if (myUser instanceof MyUserModel) {
MyUserModel user = (MyUserModel) myUser;
//get details from model object
}
You can use this to get the UserDetails (or any implementation with your custom details).
UserDetails userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
If there are not available, you can load the user details from the UserDetailsService.
In both cases, I think you have to save them yourself in a session scope bean.

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