简体   繁体   中英

how to configure spring security for spring boot project

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

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.

You need to tell Spring security what URL are public with something like this -

@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {

private static final String[] PUBLIC_URLS = {"/public/*"};

@Override
protected void configure(final HttpSecurity http) throws Exception {
           http.authorizeRequests()
            .antMatchers("/userOnly/**").hasRole("USER")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/loginPage.html");
  }
  
  @Override
  public void configure(WebSecurity web) {
    List<RequestMatcher> matchers =
    Arrays.asList(urls).stream().map(url -> new 
    AntPathRequestMatcher(url)).collect(Collectors.toList());
    web.ignoring().requestMatchers(new OrRequestMatcher(matchers));
  }
}

With OrRequestMatcher , you can create list of all URLs which you need to be public. You can also use NegatedRequestMatcher to get all the private URL

   RequestMatcher privateUrlMatcher =  new 
   NegatedRequestMatcher(publicUrlMatcher);

I also suggest you to keep all public url under /src/main/resources/static/publicui and all private under /src/main/resources/static/privateui and have public permission for /publicui/*

try the following in your SecSecurityConfig class

@Configuration
@EnableAutoConfiguration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        
            .antMatchers("/users").authenticated()
            .anyRequest().permitAll()
            .and()
            .formLogin()
            
                .usernameParameter("email")
                .defaultSuccessUrl("/lib/allBooks")
                .permitAll()
            .and()
            .logout().logoutSuccessUrl("/lib").permitAll();
        
        http       
        .csrf().disable();
    }
}

Just modify the parameters set for your application. if you don't have login form yo can skip

                .usernameParameter("email")
                .defaultSuccessUrl("/lib/allBooks")
                .permitAll()

Can the public URL be a @RestController? I have two controllers one is @Controller for thymeleaf and the other just a @RestController. The @RestController endpoint have @Valid and @RequestBody (request/response - JSON). If it failed validation it gets route to the login page instead of JSON object.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM