Issue
I'm trying to make a web application that uses: SpringBoot, Mysql, JDBC , MVC, DAO Thymeleaf, IntelliJ
And I'm trying to figure out how Spring security works (which I'm having a lot of difficulty with). My views are organized as follows:
resources(folder): - ________static(folder)
|____templates(folder):__________images(folder)
|___userOnly(folder):_____header.html
| |__help.html
| |__menu.html
| |__newDocForm.html
| |__profil.html
|
|__firstPage.html
|__header.html
|__home.html
|__index.html
|__inscriptionForm.html
|__loginPage.html
I would like to do that unidentified users can access all views except those contained in "userOnly" and that my "loginPage" page is used as the login page.
If I understood correctly, I must create a class that inherits from "WebSecurityConfigurerAdapter". What I have done. And then configure "configure", which I can't do correctly :(
@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/userOnly/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/loginPage.html");
}
}
Sorry if my questions seems strange but english is not my first language
Solution
As of Spring-Boot 2.7 the use of WebSecurityConfigurerAdapter
is deprecated. If you're using Spring-Boot 2.6 or older the other answers might suit you better.
To my best knowledge the recommended way for defining security config in Spring-Boot 2.7 is as follows:
@Configuration
public class WebSecurityConfig
{
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
{
// @formatter:off
http.authorizeRequests()
.mvcMatchers("/userOnly/**").permitAll()
.anyRequest().permitAll();
http.formLogin()
.permitAll()
.loginPage("/loginPage.html");
http.logout()
.permitAll();
// @formatter:on
return http.build();
}
}
The use of web.ignoring() in the answer from voucher_wolves
is, I believe, not recommended, instead one should add those cases to http.mvcMatcher().permitAll()
.
On a side note, I would personally recommend whitelisting the public pages and adding authentication to everything else, (for example a public folder). This way if you forget to add security to a link it's not public by default.
Answered By - Ralan
Answer Checked By - Marie Seifert (JavaFixing Admin)