Display user name in Spring - spring

I can login and logout, and display a list of users on a page doing this:
<li th:each="user : ${users}">
<span th:text="${user.firstname}+' '+${user.lastname}"></span>
</li>
I would now simply like to display the name of the currently logged in user, but I am not sure how. I would like to add it to a header fragment so every page shows clearly who the user logged in is.
LoginForm.java:
package com.demo.spring.domain;
import org.hibernate.validator.constraints.NotEmpty;
public class LoginForm {
public String getAccountname() {
return accountname;
}
public void setAccountname(String accountname) {
this.accountname = accountname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#NotEmpty
String accountname;
#NotEmpty
String password;
}
login.html:
<h3>User Login</h3>
<form action="#" th:action="#{/user/login}" th:object="${user}" method="post">
<!--<input type="hidden" th:field="*{id}"/>-->
<p>Account Name:</p> <input type="text" th:field="*{accountname}"/>
<p>Password:</p> <input type="password" th:field="*{password}"/>
<p/><input type="submit" value="Login"/>
</form>
<div th:if="${message!=null}">
<br/>
<span th:text="${message}"/>
</div>
UserController code for logging in:
package com.demo.spring.controller;
import com.demo.spring.domain.LoginForm;
import com.demo.spring.domain.User;
import com.demo.spring.domain.UserSearchForm;
import com.demo.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
#Controller
#RequestMapping(value = "/user")
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginView(Model model)
{
LoginForm user = new LoginForm();
model.addAttribute("user", user);
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, #Valid #ModelAttribute("user") LoginForm user, BindingResult bindingResult, HttpSession session)
{
if(bindingResult.hasErrors())
{
model.addAttribute("user", user);
model.addAttribute("message", "Please provide information in each field");
return "login";
}
if (userService.validateLogin(user)==false)
{
model.addAttribute("user", user);
model.addAttribute("message", "Your accountname and/or password are incorrect");
return "login";
}
session.setAttribute("login", true);
return "redirect:/";
}
UserService
package com.demo.spring.service;
import com.demo.spring.domain.LoginForm;
import com.demo.spring.domain.UserSearchForm;
import com.demo.spring.domain.User;
import com.demo.spring.domain.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class UserService {
public boolean validateLogin(LoginForm user)
{
List<User> users = userRepository.checkUserInput(user.getAccountname(),user.getPassword());
return users !=null && users.size()>0;
}

We put the logged in users' name in the session
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, #Valid #ModelAttribute("user") LoginForm user, BindingResult bindingResult, HttpSession session)
{
...
session.setAttribute("accountName", user.getAccountName());
session.setAttribute("login", true);
return "redirect:/";
}
Once put in the session, the session variables can simply be accessed as ${session.accountName}. So you can use <span th:text="${session.accountName}"></span> in your header fragment.

Related

I have create basic login page but not work that page. Why display whitelable error page?

I have created a basic login page but it does not work that page display only the Whitelabel error and does not create a table in the database. (without encoding)
Not indicate the error.
I am a beginner at coding.
Who can support finding that error? and explain
LoginController
package Controller;
import domain.login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import repository.LoginRepository;
import service.LoginService;
import java.util.Objects;
#Controller
public class LoginController {
#Autowired
private LoginService loginService;
#GetMapping("/login")
public ModelAndView login() {
ModelAndView mav = new ModelAndView("login");
mav.addObject("user", new login());
return mav;
}
#PostMapping("/login")
public String login(#ModelAttribute("user") login user){
login oauthUser = loginService.login(user.getUsername(), user.getPassword());
System.out.print(oauthUser);
if(Objects.nonNull(oauthUser)) {
return "redirect:/";
} else {
return "redirect:/login";
}
}
}
domain (login)
package domain;
import javax.persistence.*;
#Entity
#Table(name="login")
public class login {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
public login(){
}
public login(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
LoginRepository
package repository;
import domain.login;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface LoginRepository extends JpaRepository<login, Long>{
login findByUsernameAndPassword(String username, String password);
}
LoginService
package service;
import domain.login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.LoginRepository;
#Service
public class LoginService {
#Autowired
private LoginRepository repo;
public login login(String username, String password) {
login user = repo.findByUsernameAndPassword(username, password);
return user;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to Home Page</title>
</head>
<body>
<h1>Welcome To Home Page</h1>
</body>
</html>
login.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
</head>
<body>
<h1>login page</h1>
<form th:action="#{/login}" th:object="${user}" method="post">
<div class="form-group">
<label>User Name</label>
<input type="text" th:field="*{username}">
</div>
<div class="form-group">
<lable>Password</lable>
<input type="text" th:field="*{password}">
</div>
<button type="submit">Login</button>
</form>
</body>
</html>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/login?useSSL=false&serverTimezone=UTC&useLegacyDatetimecode=false
spring.datasource.username=root
spring.datasource.password=123123
#Hibernate
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
#Hibernate auto ddl
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE

How to combine spring boot oauth2 with custom user accounts?

This here is my first post to stack overflow (after plenty of reading), so I'm going to do my best to get it right. I've been looking up this problem for weeks and haven't found an answer to it, but I happily admit that there's a possibility I'm not looking up the right terms. I'm self-taught, so I sometimes miss things.
I have a Spring Boot application with custom user accounts stored in a postgres database. I would like to add OAuth2 support to that application. I have been able to successfully add OAuth2 login, but I would like to intercept that OAuth2 user information and use it to access one of my custom user accounts.
User signs into Github OAuth -> Server accesses OAuth details and retrieves matching user account info from my user database.
My ideal workflow would be to intercept the OAuth2 details and retrieve the custom info from my DB before the user is redirected to the protected page or back to the index.
Hopefully I managed to include all of the relevant code snippets below. In case I missed anything, the full project can be seen on this here github repository: https://github.com/Ahimsaka/shorturl2.
Web Security Config
package com.github.ahimsaka.shorturl.security;
import com.github.ahimsaka.shorturl.service.impl.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
auth.userDetailsService(userDetailsService());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().ignoringAntMatchers("/url", "/user/registration", "/user/resetPassword", "/user/savePassword", "login/oauth2/code/github")
.and()
.authorizeRequests()
.antMatchers("/user").hasAnyAuthority("USER", "ADMIN")
.antMatchers("/user/registration", "/u/*", "/login*", "/forgotPassword",
"/user/resetPassword", "user/savePassword").permitAll()
.antMatchers(HttpMethod.POST, "/url").permitAll()
.antMatchers("/delete/**").hasAnyAuthority("ADMIN", "USER")
.antMatchers("/admin").hasAuthority("ADMIN")
.antMatchers("/u/*").permitAll()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/user", true)
.permitAll()
.and()
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.oauth2Login();
}
}
Index With Github Login Link
<!DOCTYPE html>
<html xmlns:th="http:/www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
</head>
<body>
Index
<div sec:authorize="isAuthenticated()">
Welcome <b><span sec:authentication="name">Username</span></b>
<i><span sec:authentication="principal.authorities">Roles</span></i>
<form th:action="#{/logout}" method="post">
    <input type="submit" value="Logout" />
</div>
<div sec:authorize="isAuthenticated() == false">
<input type="button" value="Login" />
With GitHub: click here
</div>
<div align="center">
<h1>Shorten My URL</h1>
<br />
<form action="#" th:action="#{/url}"
method="post">
<table border="0" cellpadding="10">
<tr>
<td>URL:</td>
<td><input type="text" name="url"/></td>
</tr>
<tr>
<td colspan="2"><button type="submit">Save</button></td>
</tr>
</table>
</form>
<div sec:authorize="hasAuthority('ADMIN')">Admin</div>
<div sec:authorize="hasAuthority('USER')">User</div>
</div>
</body>
</html>
Registration Controller - Where I would LIKE the Magic to Happen
package com.github.ahimsaka.shorturl.controller;
import com.github.ahimsaka.shorturl.dto.PasswordDto;
import com.github.ahimsaka.shorturl.dto.UserDto;
import com.github.ahimsaka.shorturl.entity.User;
import com.github.ahimsaka.shorturl.entity.VerificationToken;
import com.github.ahimsaka.shorturl.exception.UserAlreadyExistException;
import com.github.ahimsaka.shorturl.exception.UserNotFoundException;
import com.github.ahimsaka.shorturl.exception.util.GenericResponse;
import com.github.ahimsaka.shorturl.registration.OnRegistrationCompleteEvent;
import com.github.ahimsaka.shorturl.service.UserSecurityService;
import com.github.ahimsaka.shorturl.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.reactive.result.view.RedirectView;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.http.HttpRequest;
import java.util.Calendar;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
#RestController
public class RegistrationController {
private final Logger log = LoggerFactory.getLogger(RegistrationController.class);
private UserService userService;
private ApplicationEventPublisher applicationEventPublisher;
private MessageSource messages;
private JavaMailSender mailSender;
private UserSecurityService userSecurityService;
RegistrationController(UserService userService, ApplicationEventPublisher applicationEventPublisher,
MessageSource messages, JavaMailSender mailSender, UserSecurityService userSecurityService) {
this.userService = userService;
this.messages = messages;
this.applicationEventPublisher = applicationEventPublisher;
this.mailSender = mailSender;
this.userSecurityService = userSecurityService;
}
#GetMapping("/user/registration")
public ModelAndView showRegistrationForm() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("registration");
UserDto userDto = new UserDto();
modelAndView.getModel().put("user", userDto);
return modelAndView;
}
#PostMapping("/user/registration")
public ModelAndView registerUserAccount(#ModelAttribute("user") #Valid UserDto userDto,
HttpServletRequest request, Errors errors) {
try {
User registered = userService.registerNewUserAccount(userDto);
String appUrl = request.getContextPath();
applicationEventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl));
} catch (UserAlreadyExistException uaeEx) {
ModelAndView mav = new ModelAndView("registration", "user", userDto);
mav.addObject("message", "An account for that username/email already exists.");
return mav;
} catch (RuntimeException ex) {
return new ModelAndView("emailError", "user", userDto);
}
return new ModelAndView("successRegister", "user", userDto);
}
#GetMapping("/registrationConfirm")
public ModelAndView confirmRegistration(WebRequest request,
#RequestParam("token") String token) {
ModelAndView mav = new ModelAndView();
Locale locale = request.getLocale();
VerificationToken verificationToken = userService.getVerificationToken(token);
if (verificationToken == null) {
String message = messages.getMessage("auth.message.invalidToken", null, locale);
mav.setViewName("badUser");
mav.getModel().put("message", message);
return mav;
}
User user = verificationToken.getUser();
Calendar cal = Calendar.getInstance();
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
String messageValue = messages.getMessage("auth.message.expired", null, locale);
mav.setViewName("badUser");
mav.getModel().put("message", messageValue);
mav.getModel().put("token", token);
mav.getModel().put("expired", true);
return mav;
}
user.setEnabled(true);
userService.saveRegisteredUser(user);;
mav.setViewName("login");
mav.getModel().put("message", messages.getMessage("message.accountVerified", null, locale));
return mav;
}
#GetMapping("/user/resendRegistrationToken")
public GenericResponse resendRegistrationToken(HttpServletRequest request,
#RequestParam("token") String existingToken) {
VerificationToken newToken = userService.generateNewVerificationToken(existingToken);
User user = userService.getUser(newToken.getToken());
SimpleMailMessage email = constructResendVerificationTokenEmail(getAppUrl(request), request.getLocale(), newToken, user);
mailSender.send(email);
return new GenericResponse(messages.getMessage("message.resendToken", null, request.getLocale()));
}
#PostMapping("/user/resetPassword")
public ModelAndView resetPassword(HttpServletRequest request, #RequestParam("email") String userEmail) {
User user = userService.findByUsername(userEmail);
if (user == null) {
throw new UserNotFoundException();
}
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token);
mailSender.send(constructResetTokenEmail(getAppUrl(request), request.getLocale(), token, user));
ModelAndView mav = new ModelAndView("login");
mav.getModel().put("message", messages.getMessage("message.resetPasswordEmail", null, request.getLocale()));
return mav;
}
#GetMapping("/user/changePassword")
public ModelAndView showChangePasswordPage(Locale locale, #RequestParam("token") String token) {
ModelAndView mav = new ModelAndView();
String result = userSecurityService.validatePasswordResetToken(token);
if (result != null) {
String message = messages.getMessage("auth.message." + result, null, locale);
mav.getModel().put("message", message);
mav.setViewName("login");
} else {
mav.getModel().put("password", new PasswordDto());
mav.getModel().put("token", token);
mav.setViewName("updatePassword");
}
return mav;
}
#PostMapping("/user/savePassword")
public ModelAndView savePassword(HttpServletRequest request,
#ModelAttribute("password") #Valid PasswordDto passwordDto) {
ModelAndView mav = new ModelAndView();
String result = userSecurityService.validatePasswordResetToken(passwordDto.getToken());
if (result != null) {
mav.setViewName("updatePassword");
mav.getModel().put("message", messages.getMessage("auth.message." + result, null, request.getLocale()));
return mav;
}
Optional user = userService.getUserByPasswordResetToken(passwordDto.getToken());
if (user.isPresent()) {
userService.changeUserPassword((User) user.get(), passwordDto.getNewPassword(), passwordDto.getToken());
mav.setViewName("login");
mav.getModel().put("message", messages.getMessage("message.resetPasswordSuc", null, request.getLocale()));
} else {
mav.setViewName("updatePassword");
mav.getModel().put("message", messages.getMessage("auth.message.invalid", null, request.getLocale()));
}
return mav;
}
#GetMapping("/forgotPassword")
private ModelAndView forgotPasswordPage() {
return new ModelAndView("forgotPassword");
}
#GetMapping("login/oauth2/code/github")
// This does nothing but I haven't removed it yet.
private ModelAndView oauthUserSignIn(HttpServletRequest request, Authentication authentication) {
return new ModelAndView("user");
}
// NON API
private SimpleMailMessage constructResendVerificationTokenEmail (String contextPath, Locale locale, VerificationToken newToken, User user){
String url = contextPath + "/registrationConfirm?token=" + newToken.getToken();
String message = messages.getMessage("message.resendToken", null, locale);
return constructEmail("Resend Registration Token", message + " \r\n" + url, user);
}
private SimpleMailMessage constructResetTokenEmail(String contextPath, Locale locale, String token, User user) {
String url = contextPath + "/user/changePassword?token=" + token;
String message = messages.getMessage("message.resetPassword", null, locale);
return constructEmail("Reset Password", message + " \r\n" + url, user);
}
private SimpleMailMessage constructEmail(String subject, String body, User user) {
SimpleMailMessage email = new SimpleMailMessage();
email.setSubject(subject);
email.setText(body);
email.setTo(user.getUsername());
return email;
}
private String getAppUrl(HttpServletRequest request) {
return "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
}

SpringBoot tokenRepository,JdbcTokenRepository not save in table persistence_logins

Login work, but table persitence_logins remain empty.
I Follow the documentation here :
https://courses.baeldung.com/courses/learn-spring-security-the-starter-class/lectures/924437
Don't know how to change.
I need to Override something else ?
persistent_logins
username varchar(64) not null,
series varchar(64) primary key,
token varchar(65) not null,
last_used timestamp not null
SECURITY CONFIG
package com.example.java.configuration;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.sql.DriverManager;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Autowired
private DataSource dataSource;
private final String USERS_QUERY = "select email, password, active from user where email=?";
private final String ROLES_QUERY = "select u.email, r.role from user u inner join user_role ur on (u.id = ur.user_id) inner join role r on (ur.role_id=r.role_id) where u.email=?";
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.usersByUsernameQuery(USERS_QUERY)
.authoritiesByUsernameQuery(ROLES_QUERY)
.dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/signup").permitAll()
.antMatchers("/dottore").hasAuthority("DOTTORE")
.antMatchers("/home/**").hasAnyAuthority("USER").anyRequest()
.authenticated().and().csrf().disable()
.formLogin().loginPage("/login").usernameParameter("email").passwordParameter("password")
.failureUrl("/login?error=true")
.defaultSuccessUrl("/home/home")
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.and().rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60*60)
.and().exceptionHandling().accessDeniedPage("/access_denied");
}
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
db.setDataSource(dataSource);
return db;
}
}
APPLICATION PROPERTIES
#Peristence
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=pass
# hibernate configurations
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialet= org.hibernate.dialect.MySQL5Dialect
# thumeleaf configurations
spring.thymeleaf.mode= LEGACYHTML5
spring.thymeleaf.cache=false
USER CONTROLLER:
package com.example.java.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.example.java.model.User;
import com.example.java.service.UserService;
import sun.jvm.hotspot.runtime.Threads;
import java.util.concurrent.TimeUnit;
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping("/")
public ModelAndView main(){
ModelAndView model = new ModelAndView();
model.setViewName("user/login");
return model;
}
#RequestMapping(value= {"/login"}, method=RequestMethod.GET)
public ModelAndView login() {
ModelAndView model = new ModelAndView();
model.setViewName("user/login");
return model;
}
#RequestMapping(value= {"/signup"}, method=RequestMethod.GET)
public ModelAndView signup() {
ModelAndView model = new ModelAndView();
User user = new User();
model.addObject("user", user);
model.setViewName("user/signup");
return model;
}
#RequestMapping(value= {"/signup"}, method=RequestMethod.POST)
public ModelAndView createUser(#Valid User user, BindingResult bindingResult) throws InterruptedException {
ModelAndView model = new ModelAndView();
User userExists = userService.findUserByEmail(user.getEmail());
if(userExists != null) {
bindingResult.rejectValue("email", "error.user", "This email already exists!");
}
if(bindingResult.hasErrors()) {
model.setViewName("user/signup");
} else {
userService.saveUser(user);
model.addObject("msg", "User has been registered successfully!");
model.addObject("user", new User());
model.setViewName("user/signup");
}
return model;
}
#RequestMapping(value= {"/home/home"}, method=RequestMethod.GET)
public ModelAndView home() {
ModelAndView model = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
model.addObject("userName", user.getNome() + " " + user.getCognome());
model.setViewName("home/home");
return model;
}
#RequestMapping(value= {"/access_denied"}, method=RequestMethod.GET)
public ModelAndView accessDenied() {
ModelAndView model = new ModelAndView();
model.setViewName("errors/access_denied");
return model;
}
}
EDIT:
RESOLVED.
In security config I put:
.and().rememberMe().rememberMeParameter("my-remember-me")
And in login.html
<input type="checkbox" class="form-check-input" name="my-remember-me" id="remember-me" />

How to pass #SessionAttributes value between controllers

My first controller is Login
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpSession;
import java.io.IOException;
#Controller
#SessionAttributes("session")
public class LoginController extends GlobalController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String indexAction() throws IOException {
return "login";
}
#RequestMapping(value = "/", method= RequestMethod.POST)
public String indexAction(#RequestParam String username, #RequestParam String password,HttpSession session) {
String page = "login";
if(username != "" && password != ""){
try {
if(userService.authenticationUser(username,password) == "success"){
page = "redirect:/main";
session.setAttribute("test","Salom");
//this.httpSession =session;
//System.out.println(session.getAttribute("test"));
}
else page = "login";
}
catch (Exception e){
e.fillInStackTrace();
}
}
else page = "login";
return page;
}
}
My second Controller is Test
package com.springboot.app.controllers.reports;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpSession;
#SessionAttributes("session")
public class TestController {
#RequestMapping(value = "/test",method = RequestMethod.GET)
public String index(){
#SessionAttributes("session")HttpSession session;
return "";
}
}
---------------------------------------------------------------------------- How to pass #SessionAttributes("session") from login Controller to Test controller or how to store #SessionAttributes("session") in variable
#SessionAttributes is not intended to be used (and will not work also) to store objects in the session between different controllers. The controller annotated with #SessionAttributes must also tell that it is finished (so controllerA not ControllerB). The model message from controller a is still not available for controller B.
see this conversation
you can pass from LoginController to TestController:
e.g. Username = name
LoginController:
import org.springframework.ui.ModelMap;
#Controller
#SessionAttributes("name")
public class LoginController{
#RequestMapping(value="/login", method = RequestMethod.POST)
public String showWelcomePage(ModelMap model, #RequestParam String name, #RequestParam String password){
boolean isValidUser = service.validateUser(name, password);
if (!isValidUser) {
model.put("errorMessage", "Invalid Credentials");
return "login";
}
model.put("name", name);
model.put("password", password);
return "welcome";
TestController:
#SessionAttributes("name")
public void showUsername(ModelMap model){
System.out.println("Username is: " + (String) model.get("name");
}
}
hope there is no typo!

Why is not null error message displaying before form submission?

I've created basic form validation in Spring using annotations. For unknown reason it is displaying the NotNull error message I specified in the User class before the form is submitted. Any ideas why?
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="springForm" %>
<%# page session="false" %>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Home</title>
</head>
<body>
<springForm:form method="POST" action="#" commandName="user" >
<table>
<tr>
<td>UserName:</td>
<td><springForm:input path="userName" /></td>
<td><springForm:errors path="userName" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Save Changes" />
</td>
</tr>
</table>
</springForm:form>
</body>
</html>
package com.journaldev.spring;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
public class User {
private int id;
#NotNull #Size(min=2, max=30)
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public User(){
}
}
package com.journaldev.spring;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
public String home(Model model, #Valid User user,
BindingResult bindingResult) {
return "home";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Locale locale, Model model) {
return "login";
}
#RequestMapping(value = "/home", method = RequestMethod.POST)
public String login(#Validated User user, Model model) {
model.addAttribute("userName", user.getUserName());
return "user";
}
}
You have same method on "/" for GET and POST with #Valid and BindingResult. Create separate method for GET without parameters you don't need there.

Resources