管理员和用户的访问权限

时间:2019-06-13 03:50:38

标签: java spring spring-mvc spring-security

启动项目时,将出现“ 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();
    }
    }

1 个答案:

答案 0 :(得分:0)

Spring安全性在@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”)和一个提交按钮的表单

相关问题