I'm working on a blog application with Spring Boot Security.
My overridden configure method looks like:
@Override
protected void configure(HttpSecurity httpSec) throws Exception {
httpSec
.authorizeRequests()
.antMatchers("/users").authenticated()
.antMatchers("/admin", "/db").hasRole("ADMIN")
.antMatchers("/**").permitAll()
//.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/login?logout").permitAll();
httpSec.csrf().disable();
httpSec.headers().frameOptions().disable();
}
And my custom login form:
<form name="login" th:action="@{/login}" method="post" class="form-signin">
<h1>Please log in!</h1>
<div th:if="${param.error}" class="alert alert-danger">Wrong username and/or password.</div>
<div th:if="${param.logout}" class="alert alert-success">You logged out successfully.</div>
<label for="username">Username</label>
<input type="text" name="username" class="form-control" placeholder="username" required="true"/>
<label for="password">Password</label>
<input type="password" name="password" class="form-control" placeholder="password" required="true"/>
<br/>
<button type="submit" class="btn btn-lg btn-primary btn-block">Log in</button>
<br/>
<a href="/registration" style="color: blue !important">You can register here.</a>
<hr/>
</form>
The default behaviour of Spring Security is that when I send a request to an URL which needs to be authenticated (for example /users or /admin in my case) it automatically redirects to this custom login page.
I would like to disable this automatic redirection. When authentication is needed I would like to throw a custom exception (which I handle with a separate Class with @ControllerAdvice annotation) instead with message like "You have to log in to see this content". But I would like to reach my custom login page via navigation menu to authenticate "manually".
How could I reach this?
So far I have tried .formLogin().disabled(). In this way I can still reach my custom login page, but when I try to submit it gave an error "Method not allowed". But it is logical since th:action="@{/login}" can't send the username and password to /login.
AuthenticationEntryPoint.