This question already has an answer here:
Spring Security, secured and none secured access

(1个答案)


去年关闭。





当我启动该项目时,将出现“ allStudents.jsp”页面,管理员必须首先在其登录名和密码的帮助下进入该页面。只有管​​理员可以编辑,添加,删除学生。但是为什么我的学生在没有管理员输入的情况下被编辑和删除。毕竟,我设置了只有管理员才能删除和编辑学生的访问权限。

package adil.java.schoolmaven.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/allStudents**").permitAll()
                .antMatchers("/addStudent**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/editStudent/**").access("hasRole('ROLE_ADMIN')")



                .and()
                .authorizeRequests().antMatchers("/**").permitAll()
                .and()

                .formLogin().loginPage("/login").failureUrl("/login?error")
            .usernameParameter("username").passwordParameter("password")
                .successForwardUrl("/allStudents")
                .loginPage("/allStudents")

                .loginProcessingUrl("/loginAction")
                .and()
                .logout().logoutSuccessUrl("/login?logout")
                .and()
                .csrf().disable();
    }
    }

最佳答案

Spring Security在@Order中工作,即具有最高的安全点,其次是较小的安全点。如果只有管理员可以访问添加/编辑/删除学生,则应将这些端点修改为/ adminAddStudent或类似名称。接下来修改您的安全配置,如下所示

  @Override
    protected void configure(HttpSecurity http) throws Exception
    {

        http
        .authorizeRequests()
        .antMatchers("/admin**").access("hasRole('ROLE_ADMIN')")
        .and()
        .formLogin()
        .loginPage("/login")
        .usernameParameter("username")
        .passwordParameter("password")
        .and()
        .logout().logoutSuccessUrl("/").permitAll()
        .and()
        .csrf().disable();

    }


/allStudent绝对不是登录页面,因为登录页面包含具有2个输入(即“ username”和“ password”)和一个提交按钮的表单

10-04 12:15