Spring boot SecurityContextHolder: principal is changing - spring-boot

I have encountered an issue with the SecurityContextHolder.
Given an Thymeleaf Template where userdetails can be changed and submitted. As admin I am entering the /edit Controller. So far everything is fine:
#RequestMapping(value="/user/{username}/edit", method= RequestMethod.GET)
public ModelAndView edit(#PathVariable String username, ModelMap model) {
User user = userService.findUser(username);
User loggedInUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
....
}
In the loggedInUser variable I see the admin user. That works as expected:
When the form is submitted. I check the pricipal object again. Now it suddenly changed to the user I am currently editing.
Form snippet
<form class="form-horizontal" role="form" th:action="#{/users/save}" method="post" th:object="${user}">
<input type="hidden" id="old_username" name="old_username" th:value="${user.username}" required>
<input type="text" class="form-control" id="username" th:field="${user.username}" required>
....
</form
Receiving POST Controller:
#RequestMapping(value="/users/save", method= RequestMethod.POST)
public String save(User user, HttpServletRequest request, RedirectAttributes redir) {
User loggedInUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
....
Here the loggedInUser changed to the user being edited:
What is going on?

Related

I'm getting error for user field in registration form

java.lang.IllegalStateException: Neither BindingResult nor plain
target object for bean name 'user' available as request attribute at
org.springframework.web.servlet.support.BindStatus.(BindStatus.java:153)
~[spring-webmvc-5.3.13.jar:5.3.13] at
org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903)
~[spring-webmvc-5.3.13.jar:5.3.13] at
org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227)
~[thymeleaf-spring5-3.0.12.RELEASE.jar:3.0.12.RELEASE]
HTML
<form action="#" th:action="#{/process_register}" th:object="${user}" method="post">
<h4 class="mb-4 pb-3">Sign Up</h4>
<div class="form-group">Username
<input type="text" th:field="*{username}" class="form-style">
</div>
<div class="form-group mt-2">Password
<input type="password" th:field="*{password}" class="form-style">
</div>
...</form>
Controller:
#GetMapping("/register")
public String showRegistrationForm(Model model) {
model.addAttribute("user", new User());
return "signup_form";
}
#PostMapping("/process_register")
public String processRegister(Model theModel, User user) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userService.save(user);
return "Wellcome";
}
Most likely your forgot to add user object to Model in a controller method that landed you on this form page. To make sure that doesn't happen best is to just add model attributing method to controller that always takes care of this:
#ModelAttribute("user")
public User user() {
return new User();
}
Also please make sure User class have getters, setters and no arg constructor defined - that is important for Thymeleaf

Concept of Two-Way data binding in Spring MVC

This is my login.jsp file.
<form:form method="POST" action="checklogin" modelAttribute="log">
<form:label path="username">UserName: </form:label>
<form:input path="username" id="username" /><br /><br />
<br />
<form:label path="pswd">Password: </form:label>
<form:password path="pswd" id="password" /><br /> <br />
<br />
<input type="submit" id="btnLogin" value=login class="login" />
</form:form>
This is my controller
#RequestMapping(value = "/checklogin", method=RequestMethod.POST)
public String chklogin(#ModelAttribute Login login, Model mod) {
if (login.getUsername().equals("subro") && login.getpswd().equals("ss")) {
mod.addAttribute("log",login);
return "Home";
}
else {
return "Login";
}
}
Still I am getting the error as
Neither BindingResult nor plain target object for bean name 'log' available as request attribute
Change
#ModelAttribute Login login
To
#ModelAttribute Login log
Two way data binding in spring allows user inputs to be dynamically bound to the beans. It is two-way in a sense that it can get the inputs from the beans and it can post the user inputs to the beans using GET and POST api.
Using the #ModelAttribute annotation you can bind the user inputs with the beans.
#RequestMapping(value = "/login", method=RequestMethod.GET)
public String login(#ModelAttribute Login log){ //one-way binding
return "Login";
}
#RequestMapping(value = "/checklogin", method=RequestMethod.POST)
public String chklogin(#ModelAttribute Login log, Model mod) { //two-way binding
if (login.getUsername().equals("subro") && login.getpswd().equals("ss")) {
mod.addAttribute("log",login);
return "Home";
}
else return "Error";
}
Earlier I haven't written the login method which is mapped with the url /login.
When you are getting an error as "Neither BindingResult nor plain target object for bean name 'log' available as request attribute", it means that the beans ('log' in my case) is not able to bind with the view page.

How do I access a variable in the request scope in JSP from a Spring MVC controller?

I have the following in my controller
#GetMapping("/login")
public String login(#RequestParam(name="userId", required=true) String userId) {
if (userId.matches("^\\d+$")) {
return "login";
And I have the following in my login.jsp
User: <input type="text" name="userId" value="${userId}"><br>
However for the URL https://localhost:8443/login?userId=751061, the browser returns
User: <input type="text" name="userId" value=""><br>
How can I access the userId from the request? I tried ${requestScope.userId} also.
I've rebuilt the app with mvn spring-boot:run.
I had to add
public String login(#RequestParam(name="userId", required=true) String userId,
HttpServletRequest request) {
...
request.setAttribute("userId", userId);
Then it was accessible. Rails really spoils you.
https://memorynotfound.com/servlet-attributes-example/

Request method 'GET' not supported Spring Booth with Thymeleaf

I am building a very simple crud app using Spring boot, Jpa and Thymeleaf, but I am stuck at a "Request method 'GET' not supported" problem. I get this error whenever I want to access the /add page through which I can add a new student. The snippets associated with this error are as below:
Thymeleaf form:
<h1>Form</h1>
<form action="#" th:action="#{/add}" th:object="${addStudent}"
method="post">
<p>Full name: <input type="text" th:field="*{fname}" /></p>
<p>Major: <input type="text" th:field="*{major}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
Controller addNewStudentMethod
#PostMapping("/add")
public String addNewStudent( #ModelAttribute StudentEntity studentEntity, Model model) {
model.addAttribute("addStudent",studentRepository.save(studentEntity) );
return "/allstudents";
}
The error I get:
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
Thanks,
In your controller you only have a method which has mapped to POST request "/add". You have to have a GET request mapped to a different method OR change the #PostMapping("/add") to #RequestMapping("/add").
Please note:
#PostMapping is for mapping POST request only.
#GetMapping is for mapping GET request only.
#RequestMapping maps all request types
You have some issues with how you have it set up. What you may want is:
#GetMapping("/add")
public String addNewStudent(Model model) {
model.addAttribute("studentEntity", new StudentEntity()); //create a new bean so that your form can bind the input fields to it
return "add"; //let's say add.html this is the name of your form
}
#PostMapping("/add")
public String addNewStudent( #ModelAttribute StudentEntity studentEntity, Model model) {
//call any service methods to do any processing here
studentRepository.save(studentEntity);
return "redirect:/allstudents"; //this would be your confirmation page
}
Your add.html form would have something like:
<form th:object="${studentEntity}" th:action="#{/add}" method="post" action="allstudents.html">
<!-- input fields here --->
</form>
Note that the th:object is what you added to the model in the #GetMapping method.
change your Controller methods's #PostMapping("/any-url") to either #GetMapping("/any-url") or #RequestMapping("/any-url")
In simple words, change your above controller's method to
#RequestMapping("/add")
public String addNewStudent( #ModelAttribute StudentEntity studentEntity, Model model) {
model.addAttribute("addStudent",studentRepository.save(studentEntity) );
return "/allstudents";
}

Request parameter with thymeleaf

In a Spring Boot web app, User wants to reset his password, so he enters Reset password page. Now I want to let him type his email address, push Reset and I want to redirect to myapp/resetPassword?email=HIS_EMAIL to handle password reset.
MY code:
#RequestMapping(value = "/resetPassword", method = RequestMethod.GET)
public String resetPasswordForm(Model model){
model.addAttribute("email", new String());
return "resetPassword";
}
#RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
public String resetPassword(#RequestParam("email") String email) {
User user = userService.findUserByEmail(email);
//playing with logic
return "redirect:/";
}
How can I achieve it on my thymeleaf page? I tried something like this:
<form th:action="#{/resetPassword(email=${email})}" method="post">
<input type="email" th:field="${email}" th:placeholder="Email" />
<div class="clearfix">
<button type="submit">Reset</button>
</div>
</form>
Unfortunately my email is always null. Can somebody help?
"th:field" is for Entity-Beans only. This should work:
#GetMapping(value = "/resetPassword")
public String resetPassword(#RequestParam(value="email",required=false) String email) {
if(email==null)
return "resetPassword";
User user = userService.findUserByEmail(email);
//playing with logic
return "redirect:/";
}
<form th:action="#{/resetPassword}" method="get">
<input type="email" th:name="email" th:placeholder="Email" />
<div class="clearfix">
<button type="submit">Reset</button>
</div>
</form>
And don't forget: Thymeleaf is not Javascript. It is rendered on Server. Things like #{/resetPassword(email=${email})} would output e.g. /resetPassword?email=anValueYouAddedToModelInController

Resources