Reputation: 35
I have a problem with Spring Security, when i access to my registration page and i click on the register button, it redirects me automatically to the login page. In the console Chrome a status code 302 is indicated. I tried several things but without success...
here is my security config:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailsService")
private UserDetailsService customUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/registration").permitAll()
.anyRequest()
.authenticated()
.and().formLogin()
.loginPage("/login")
.usernameParameter("email")
.defaultSuccessUrl("/consultAccount").permitAll()
.and()// logout
.logout().deleteCookies("JSESSIONID")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
@Override
protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
authManagerBuilder.userDetailsService(customUserDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
CustomUserDetailsService.java
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
if (email.trim().isEmpty()) {
throw new UsernameNotFoundException("email is empty");
}
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException("User " + email + " not found");
}
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority("USER"));
grantedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
return new org.springframework.security.core.userdetails.User(
user.getEmail(), user.getPassword(), grantedAuthorities);
}
}
my controller:
@Controller
public class BankController {
@Autowired
private BankService bankService;
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@RequestMapping(value = "/login")
public String login() {
return "login";
}
@RequestMapping("/account")
public String index() {
return "account";
}
@RequestMapping("/registration")
public String registration(Model model) {
User user = new User();
model.addAttribute("user", user);
return "registration";
}
@RequestMapping("/welcome")
public String welcome() {
return "welcome";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerUser(@Valid User user,
BindingResult bindingResult,
RedirectAttributes RedirectAttributes) {
String originalPassword = user.getPassword();
if (bindingResult.hasErrors()) return "registration";
try {
userService.saveUser(user);
securityService.autoLogin(user.getEmail(), originalPassword);
} catch (Exception e) {
RedirectAttributes.addFlashAttribute("exception", e.getMessage());
return "redirect:/registration";
}
return "redirect:/welcome";
}
login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">
<title>Authentification</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div class="container">
<br/><br/>
<form th:action="@{/login}" method="POST" class="form-signin" style="width:30%;margin:auto">
<h3 class="form-signin-heading" align="center">Pay My Buddy</h3>
<br/>
<div align="center" th:if="${param.error}">
<p style="font-size: 20; color: #FF1C19;">Username or password is invalid</p>
</div>
<input type="text" id="email" name="email" th:placeholder="email"
class="form-control" /> <br/>
<input type="password" th:placeholder="Password"
id="password" name="password" class="form-control" /> <br />
<button class="btn btn-lg btn-primary btn-block" name="Submit" value="Login" type="Submit" th:text="Login"></button>
<h4 class="text-center"><a href="/registration">Create an account</a></h4>
</form>
</div>
</body>
</html>
registration.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8">
<title>Create an account</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form th:action="@{/register}" method="post" class="form-signin" role="form" style="width:30%;margin:auto">
<h3 class="form-signin-heading" align="center">Registration Form</h3><br/>
<input type="text" th:value="${user.firstName}" placeholder="Name" name="firstName" class="form-control" />
<span th:errors="${user.firstName}" class="text-danger"></span>
<br/>
<input type="text" th:value="${user.lastName}" placeholder="Last Name" name="lastName" class="form-control" />
<span th:errors="${user.lastName}" class="text-danger"></span>
<br/>
<input type="text" th:value="${user.email}" placeholder="Email" name="email" class="form-control" />
<span th:errors="${user.email}" class="text-danger"></span>
<br/>
<input type="password" th:value="${user.password}" placeholder="Password" name="password" class="form-control" />
<span th:errors="${user.password}" class="text-danger"></span>
<br/>
<button type="submit" class="btn btn-lg btn-primary btn-block" th:text="Register"></button>
</form>
<div th:if="${exception}" style="width:30%;margin:auto;padding: 1% 0;">
<p th:text="${exception}" class="alert alert-danger" role="alert"></p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</body>
</html>
thanks for your help
Upvotes: 0
Views: 5193
Reputation: 6479
When a user registers, you are making a POST request to "/register".
However, "/register" requires a user to be authenticated.
You can add
.antMatchers("/register").permitAll()
to your security configuration in order to allow unauthenticated users to register.
Upvotes: 1