当我启动项目时,页面“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 安全性以 @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 个输入的表单(即“用户名”和“密码”)和一个提交按钮
关于java - 管理员和用户的访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56573137/