I'm trying to use Spring Security in my application, But after hitting the login processing url defined in configure method of WebSecurityConfig Class
, from login page, its always redirecting to the failurUrl
even if the correct username and password is provided. I have seen a lot of similar problem like this but all of the solutions that were given did not work for me. There's the code with the security config:
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests().
antMatchers(PUBLIC_MATCHERS).
permitAll().anyRequest().authenticated();
http
.formLogin().loginPage("/index").defaultSuccessUrl("/userFront",true).failureUrl("/index?error").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/index?logout").deleteCookies("remember-me").permitAll()
.and()
.csrf().disable().cors().disable()
.rememberMe();
}
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
}
And the service responsible for signing in ( UserSecurityService.java
)
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if (user==null) {
LOG.warn("Username {} not found",username);
throw new UsernameNotFoundException("Username "+username+"not found");
}
return user;
}
finally the login form ( index.html
)
<form class="form-signin" th:action="@{/index}" method="post">
<h2 class="text-center">Sign In</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username"
required="required" roleId="username" name="username"
id="username " autofocus="autofocus">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password"
id="password" name="password" required="required"
roleId="inputPassword">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign
In</button>
</div>
<div class="clearfix">
<label class="float-left form-check-label"><input
type="checkbox" name="remember-me" id="remember-me">
Remember me</label>
</div>
</form>
What i am missing here please im tired of searching everywhere ?
Do you have a method in your controller to handle POST to /login? If not, I suggest you change your GET controller method from /index to /login, change the form to POST to /login, and update the configure()
method accordingly (change "/index" to "/login").
[Update]
Make sure your login method is only serving GET and let the Spring default handle the POST:
@RequestMapping(method = { RequestMethod.GET }, value = { "/login" })
public String index() {
return "login";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.