Here is my WebAppInitializer:
@Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { AppConfig.class, WebSecurityConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Here is my Security Config:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.authorizeRequests()
.antMatchers("/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").defaultSuccessUrl("/home").failureUrl("/error").permitAll()
.and().httpBasic();
// @formatter:on
}
}
And this is my login.html (example html from thymeleaf):
<form th:action="@{/j_spring_security_check}" method="post">
<label for="j_username">Username</label>:
<input type="text" id="j_username" name="j_username" /> <br />
<label for="j_password">Password</label>:
<input type="password" id="j_password" name="j_password" /> <br />
<input type="submit" value="Log in" />
</form>
When i click on login, this error appears:
HTTP ERROR 404
Problem accessing /j_spring_security_check. Reason:
Not Found
How can i get rid of this error? I googled a lot, but no success yet. (Yes I do not use any xml.)
I have created this, and it works now:
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
This activates the SpringSecurityFilterChain apperently.
I also had to switch from @EnableWebSecurity to @EnableWebMvcSecurity because of an CSRF error. As in the spring doc is written:
...The reason is that Spring Security is protecting against CSRF attakcks and there is no CSRF token include in our request. Update our configuration to use the @EnableWebMvcSecurity annotation which will do the same as @EnableWebMvcSecurity and provide integration with Spring MVC. Among other things, it will ensure our CSRF Token is included in our forms automatically when using Thymleaf 2.1+ or Spring MVC taglibs...
Also Thanks M. Deinum for his comment. Spring has recently switched the /j_spring_security_check /j_password /j_username to /login /password /username apparently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With