Spring Boot, Can't reach a different Controller Class - spring-boot

Request is always made to method(/login) in same Controller.
When you press Save button in Register.html, /login method in UserController.java class works automatically although it must run saveRegisterPage method (/registration/saveRegister) in RegisterController.java class.
What must be done in order to run saveRegisterPage method?
Thank you.
UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String registerPage(Model model) {
model.addAttribute("user", new User());
return "register";
}
#RequestMapping("/")
public String index() {
return "login";
}
#RequestMapping("/login")
public String login() {
return "login";
}
#RequestMapping("/home")
public String home() {
return "home";
}
}
RegisterController.java
#Controller
#RequestMapping(value="/registration")
public class RegisterController {
#Autowired
UserServiceImpl userServiceImpl;
#RequestMapping(value = "/saveRegister", method = RequestMethod.POST)
public String saveRegisterPage(#ModelAttribute("user") User user, BindingResult result, Model model, RedirectAttributes attributes) {
model.addAttribute("user", user);
if (result.hasErrors()) {
return "register";
} else {
userServiceImpl.save(user);
}
return "home";
}
}
home.html
<html>
<head>...</head>
<body>
<div class="container">
<h2>Welcome</h2>
Logout
</div>
</body>
</html>
login.html
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>...</head>
<body>
<div class="container">
<div class="alert alert-danger" role="alert" th:if="${param.error}">
Wrong Username or Passrod
</div>
<form th:action="#{/login}" method="post">
<h1 class="h3 mb-3 font-weight-normal">Signin</h1>
<label>Username</label>
<input type="text" name="username" class="form-control"/>
<label>Password</label>
<input type="password" id="password" name="password" class="form-control"/>
<br/>
<button class="btn btn-lg btn-primary btn-block" type="submit">SignIn</button>
<br/>
<div class="margin-top20 text-center"><a th:href="#{/register}">Go Register</a>
</div>
</form>
</div>
</body>
</html>
register.html
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>....</head>
<body>
<div class="container">
<form autocomplete="off" th:action="#{/registration/saveRegister}" th:object="${user}" method="post">
<label>Name </label>
<input type="text" id="firstName" placeholder="First Name" th:field="*{firstName}"
class="form-control"/><br/>
<label>Last name </label>
<input type="text" id="lastName" placeholder="First Name" th:field="*{lastName}" class="form-control"/><br/>
<label>Email </label>
<input type="text" id="email" placeholder="First Name" th:field="*{email}" class="form-control"/><br/>
<label>Username</label>
<input type="text" id="username" placeholder=" Username" th:field="*{username}" class="form-control"/><br/>
<label>Password</label>
<input type="text" id="password" placeholder=" Password" th:field="*{password}" class="form-control"/><br/>
<button type="submit" class="btn btn-success text-center form-control">Save</button>
</form>
</div>
</body>
</html>
SecurityConfiguration.java
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Autowired
private UserAuthService userAuthService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http
.authorizeRequests()
.antMatchers("/", "/register", "/webjars/**", "/h2-console/**","/webjars/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/home", true).permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/home").permitAll()
.and()
.httpBasic();
http.headers().frameOptions().disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userAuthService).passwordEncoder(encoder());
}
#Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zorogluresul.springexample1</groupId>
<artifactId>springexample1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springexample1</name>
<description>Spring Boot, Web, Thymeleaf, Jpa, Postgresql, Security</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1-1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

You should add RegisterController's requestMapping /registration into antMatchers like this:
.antMatchers("/", "/register", "/registration/*", "/webjars/**", "/h2-console/**","/webjars/").permitAll()
It contains /* at the end of the /registration/* in order to allow all requests in RegisterController. If you write it like /registration/register, it also runs saveRegisterPage method in RegisterController.

Try this Resul
import java.io.IOException;
import java.util.List;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/")
public class UserController {
#GetMapping("/register")
public String registerPage(Model model) {
model.addAttribute("user", new Fragment3());
return "register";
}
#GetMapping //main page
public String index() {
return "login";
}
#GetMapping("/login") //logging out from home
public String logout() {
return "login";
}
#PostMapping("/home")
public String home() {
return "home";
}
}
---------------------------------------------------------------------------
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/registration")
public class RegisterController {
#Autowired
UserServiceImpl userServiceImpl;
#PostMapping("/saveRegister")
public String saveRegisterPage(#ModelAttribute("user") User user, BindingResult result, Model model, RedirectAttributes attributes) {
model.addAttribute("user", user);
if (result.hasErrors()) {
return "register";
} else {
userServiceImpl.save(user);
}
return "home";
}
}`
most changes are at the backend
although do replace 2 lines in home.html for the logout.
<h2>Welcome</h2>
<a th:href="#{/login}" class="btn btn-danger">Logout</a>

Related

Spring controller not able to resolve Thymeleaf template

The controller class is not able to resolve any path except the root.
I have tried putting simple html code in index.html but controller couldn't resolve it. Contoller is able to resolve only this part
#RequestMapping("/")
public String home() {
return "redirect:/index";
}
Controller code:
package com.controller;
import java.util.HashSet;
import java.util.Set;
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.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.userFront.domain.User;
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "redirect:/index";
}
#RequestMapping("/index")
public String index() {
return "index";
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String signup(Model model) {
User user = new User();
model.addAttribute("user", user);
return "signup";
}
//
}
pom.xml code: I hope some dependancies are not missing:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.userFront</groupId>
<artifactId>userFront</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>userFront</name>
<description>User front for online banking app</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Code for index.html:
I have tried putting basic html code but wasn't successful in resolving it
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="common/header :: common-header"/>
<body>
<!-- Login Section -->
<img class="img-responsive" src="/images/banner.png" alt="banner"/>
<div class="container">
<div class="row ">
<div class="main-center ">
<div class="bg-danger" th:if="${param.error}">
Invalid username and secret.
</div>
<div class="bg-danger" th:if="${param.logout}">
You have been logged out.
</div>
<form class="form-signin" th:action="#{/index}" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<div class="form-group">
<label for="username" class="sr-only">Username</label>
<input type="text" roleId="username" class="form-control" placeholder="Username" name="username"
id="username"
required="required" autofocus="autofocus"/>
</div>
<div class="form-group">
<label for="password" class="sr-only">Password</label>
<input type="password" roleId="inputPassword" class="form-control" placeholder="Password"
id="password"
name="password" required="required"/>
</div>
<div class="form-group">
<input type="checkbox" name="remember-me" id="remember-me"/> Remember me
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
<hr />
<div class="form-group ">
<a type="submit" class="btn btn-info btn-lg btn-block login-button" th:href="#{/signup}">Sign up!</a>
</div>
</div>
</div>
</div>
<div th:replace="common/header :: body-bottom-scripts"/>
</body>
</html>
I found some of the configuration missed in your pom.xml and configuration level, follow the below steps hope this will help.
1. pom.xml
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
.....
</plugins>
</build>
2. Templates: resources folder path
src/main/resources/templates/index.html
Controller: Not require to redirect
#GetMapping({"/", "/index"})
public String index() {
return "index";
}

sec:authorize always returning same view in browser for both isAuthenticated() and isAnonymous() in thymeleaf view

home Controller
package com.book.controller;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.book.entity.User;
import com.book.security.entity.PasswordResetToken;
import com.book.security.entity.Role;
import com.book.security.entity.UserRole;
import com.book.security.impl.MailConstructor;
import com.book.security.impl.SecurityUtility;
import com.book.security.impl.UserSecurityService;
import com.book.security.repo.UserService;
#Controller
public class HomeController {
#Autowired
private JavaMailSender mailSender;
#Autowired
private MailConstructor mailConstructor;
#Autowired
private UserService userService;
#Autowired
private UserSecurityService userSecurityService;
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/login")
public String login(Model model) {
model.addAttribute("classActiveLogin", true);
return "myAccount";
}
#RequestMapping("/forgetPassword")
public String forgetPassword(HttpServletRequest request, #ModelAttribute("email") String email, Model model) {
model.addAttribute("classActiveForgetPassword", true);
User user = userService.findByEmail(email);
if (user == null) {
model.addAttribute("emailNotExist", true);
return "myAccount";
}
String password = SecurityUtility.randomPassword();
String encryptedPassword = SecurityUtility.passwordEncoder().encode(password);
user.setPassword(encryptedPassword);
userService.save(user);
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token);
String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
SimpleMailMessage emails = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user,
password);
mailSender.send(emails);
model.addAttribute("emailSent", "true");
return "myAccount";
}
#RequestMapping(value = "/newUser", method = RequestMethod.POST)
public String newUserPost(HttpServletRequest request, #ModelAttribute("email") String userEmail,
#ModelAttribute("username") String username, Model model) throws Exception {
model.addAttribute("classActiveNewAccount", true);
model.addAttribute("email", userEmail);
model.addAttribute("username", username);
if (userService.findByUsername(username) != null) {
model.addAttribute("usernameExists", true);
return "myAccount";
}
if (userService.findByEmail(userEmail) != null) {
model.addAttribute("emailExists", true);
return "myAccount";
}
User user = new User();
user.setUsername(username);
user.setEmail(userEmail);
String password = SecurityUtility.randomPassword();
String encryptedPassword = SecurityUtility.passwordEncoder().encode(password);
user.setPassword(encryptedPassword);
Role role = new Role();
role.setRoleId(1);
role.setName("ROLE_USER");
Set<UserRole> userRoles = new HashSet<>();
userRoles.add(new UserRole(user, role));
userService.createUser(user, userRoles);
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token);
String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
SimpleMailMessage email = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user,
password);
mailSender.send(email);
model.addAttribute("emailSent", "true");
return "myAccount";
}
#RequestMapping("/newUser")
public String newUser(Locale locale, #RequestParam("token") String token, Model model) {
PasswordResetToken passToken = userService.getPasswordResetToken(token);
if (passToken == null) {
String message = "Invalid Token.";
model.addAttribute("message", message);
return "redirect:/badRequest";
} else {
User user = passToken.getUser();
String username = user.getUsername();
UserDetails userDetails = userSecurityService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails,
userDetails.getPassword(), userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
model.addAttribute("user", user);
model.addAttribute("classActiveEdit", true);
return "myProfile";
}
}
}
Header.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head th:fragment="common-header">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Le's Bookstore</title>
<!-- Bootstrap core CSS -->
<link href="/css/bootstrap.min.css" rel="stylesheet" />
<link href="/css/non-responsive.css" rel="stylesheet" />
<!-- Custom styles for this template -->
<link href="/css/style.css" rel="stylesheet" />
<link rel="icon" href="/image/applie-touch-icon.png" />
</head>
<body>
<div th:fragment="navbar">
<div class="page-top"
style="width: 100%; height: 20px; background-color: #f46b42;"></div>
<!-- Static navbar -->
<nav class="navbar navbar-default navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">LE'S BOOKSTORE</a>
</div>
<div id="navbar">
<ul class="nav navbar-nav navbar-left">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">BOOKS <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Browse the bookshelf</li>
<li>Store hours & Directions</li>
<li>FAQ</li>
</ul></li>
<form class="navbar-form" role="search">
<div class="form-group">
<input type="text" name="keyword" class="form-control"
placeholder="Book title" />
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>SHOPPING CART</li>
<li sec:authorize="isAnonymous()"><a th:href="#{/login}">MY ACCOUNT</a></li>
<li sec:authorize="isAuthenticated()"><a th:href="#{/myProfile}">MY ACCOUNT</a></li>
<li sec:authorize="isAuthenticated()"><a th:href="#{/logout}">LOGOUT</a></li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
<!--/.container-fluid -->
</nav>
</div>
<div th:fragment="body-bottom-scripts">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</div>
</body>
</html>
SecurityConfig
package com.book.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.util.matcher.AntPathRequestMatcher;
import com.book.security.impl.SecurityUtility;
import com.book.security.impl.UserSecurityService;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserSecurityService userSecurityService;
private BCryptPasswordEncoder passwordEncoder() {
return SecurityUtility.passwordEncoder();
}
private static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/image/**",
"/",
"/newUser",
"/forgetPassword",
"/login",
"/fonts/**"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(PUBLIC_MATCHERS).permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable().cors().disable()
.formLogin().failureUrl("/login?error")
.defaultSuccessUrl("/")
.loginPage("/login").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.rakib.springboot</groupId>
<artifactId>book-shop</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>book-shop</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-complete</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Problem:
sec:authorize returning true for both isAuthenticated() and isAnonymous() in thymeleaf view. i try to hide my_Profile, Log in when user log in and when log out then show only Log in.
BUT ITS not working ....
enter image description here
not working in both condition. please help me sir to continue the project.
SHOPPING CART
MY ACCOUNT
MY ACCOUNT
LOGOUT
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
When you upgrade your security version 5 and it will be fixed.
Try changing this
<li sec:authorize="isAnonymous()"><a th:href="#{/login}">MY ACCOUNT</a></li>
For this
<li sec:authorize="!isAuthenticated()"><a th:href="#{/login}">MY ACCOUNT</a></li>

Setting up a custom login page with spring security woes

Currently trying to create a simple login with spring Security but am getting an error that I am assume is because of something I am doing wrong with resolver view or controller. Just can't seem to figure out what. I get the following error
"There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [home]: would dispatch back to the current handler URL [/home] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)"
My Config:
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
public void configureGlobal(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/loginpage")
.permitAll().and()
.logout();
}
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/resources/templates");
resolver.setSuffix(".html");
return resolver;
}
public void addViewController(ViewControllerRegistry registry){
registry.addViewController("/home").setViewName("home");
registry.addViewController("/loginpage").setViewName("loginpage");
}
}
Controller:
#Controller
public class loginController {
#RequestMapping("/home")
public String homePage(Model model){
return "home";
}
#GetMapping("/loginpage")
public String loginGetter(Model model){
return "loginpage";
}
}
Login page:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<div th:if="${param.error}">
Something is wrong
</div>
<div th:if="${param.logout}">
You have logged out
</div>
<div>
<form action="#{loginpage}" method="post">
<div><label>Username: <input type="text" name="username"/></in></label></div>
<div><label>Password: <input type="text" name="password"/></label></div>
<div><input type="submit" value="Sign in"/></in></div>
</form>
</div>
</body>
</html>
My Pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ronone</groupId>
<artifactId>SecurityTutorial</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring3 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
</dependencies>
</project>
Try this :
#EnableWebSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{ ...}
Annotating a class with the #Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.

HTTP Status 404 the requested ressource is not available / Spring boot

I wanted to test the code in
http://spring.io/guides/gs/handling-form-submission/ but when i run the application , i have http status 404, the requested ressource is not available
I don't know why , could you help ?
package controller;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HelloController implements ErrorController{
private static final String PATH = "/error";
#RequestMapping(value = PATH)
public String error() {
return "Error";
}
#Override
public String getErrorPath() {
return PATH;
}
#RequestMapping(value="/greeting", method=RequestMethod.GET)
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
#RequestMapping(value="/greeting", method=RequestMethod.POST)
public String greetingSubmit(#ModelAttribute Greeting greeting, Model model) {
model.addAttribute("greeting", greeting);
return "result";
}
}
package controller;
public class Greeting {
private long id;
private String content;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
#EnableAutoConfiguration(exclude=ErrorMvcAutoConfiguration.class)
#SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/greeting}" th:object="${greeting}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Message: <input type="text" th:field="*{content}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Result</h1>
<p th:text="'id: ' + ${greeting.id}" />
<p th:text="'content: ' + ${greeting.content}" />
Submit another message
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>Test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>demo.TestApplication</start-class>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
![The architecture of the application ![\]\[1\]][1]
[1]: http://i.stack.imgur.com/bgSzx.png

Spring Security with JDBC Annotation only

I am trying to create a Spring Boot Application using the Spring Security. I took the following example from http://spring.io/guides/gs/securing-web/. They use an "In Memory Authentification". I want to do the same but use a JDBC-Authentification.
Here is my WebSecurityConfig class:
package hello;
import org.springframework.beans.factory.annotation.Autowired;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
auth
.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select * from users where username=?")
.authoritiesByUsernameQuery("select * from user_roles where username=?");
}
}
I also set up a MySQL Database "test" and two tables "users" and "user_roles".
When I run the application and try to sign in I dont't get any Exceptions, but the application somehow can't find the user.
Can someone help me? What am I doing wrong?
Login page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="#{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-securing-web</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- tag::security[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- end::security[] -->
<!-- JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Your user has to have at least one role assigned. If the user has no role, then the authentication fails (even if you want to be able to login without any specific roles). Also make sure, that the enabled flag of the user is true.
It is recommended that your Datasource is solved as a separated Bean instead of instantiate it in your configureGlobal Method:
#Bean
public DataSource dataSource() {
// create and return a new JDBC DataSource ...
}
You can make use the Bean as you made in your configureGlobal Method:
auth.jdbcAuthentication().dataSource(dataSource)

Resources