SpringSecurity5-为具有不同用户角色的多个URL启用表单登录和基本身份验证

wnvonmuf  于 2021-09-30  发布在  Java
关注(0)|答案(0)|浏览(216)

我需要能够登录到我的应用程序,通过一个表单,并通过RESTAPI测试工具,如 Postman 使用基本身份验证。我找到了一个类似问题的答案,但是,我只能将其扩展到支持一个用户角色:

@Configuration
@Order(1)
public static class BasicAuthWebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .requestMatchers()
                .antMatchers("/course/addCourse", "/course/addTeacherToCourse", "/teacher/addTeacher", "/user/removeRole", "/user/addRole")
                .and()
            .authorizeRequests()
                .anyRequest().hasRole("ADMIN")
                .and()
            .httpBasic();
    }
}

@Configuration
@Order(2)
public static class FormLoginWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/register", "/css/**", "/js/**", "/img/**", "/login").permitAll()
                .and()
            .authorizeRequests()
                .antMatchers("/").hasRole("DEV")
                .and()
            .authorizeRequests()
                .antMatchers("/addAGradeForStudentInCourse", "/grade/addGradeForStudentInCourse" ,"/addAStudent","/student/addStudent","/addAStudentToCourse",  "/student/addStudentToCourse", "/teacher/allTeachers").hasRole("TEACHER")
                .and()
            .authorizeRequests()
                .antMatchers("/showAvgGradeInCourse", "/course/avgGradeInCourse", "/course/allCourseData", "/course/showByCourseNameAndThenAvgGrade", "/showTotalAvgGradeFromAllCoursesForAStudent", "/student/totalAvgGradeFromAllCourses", "/showAvgGradeForStudentInCourse", "/student/studAvgGradeInCourse", "/student/allStudents").hasRole("STUDENT")
                .and()
            .authorizeRequests()
                .antMatchers("/addACourse", "/course/addCourse", "/addATeacherToCourse", "/course/addTeacherToCourse", "/addATeacher", "/teacher/addTeacher", "/addUserRole", "/removeUserRole", "/user/removeRole", "/user/addRole").hasRole("ADMIN")
                .and()
            .formLogin()
                .permitAll()
                .loginPage("/login")
                .and()
            .logout()
                .logoutSuccessUrl("/login")
                .and()
            .authorizeRequests()
                .anyRequest().authenticated();
    }
}

我将如何着手延长该计划
BasicAuthWebSecurityConfig configure() 方法来支持多个用户角色,如
FormLoginWebSecurityConfig configure() 方法?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题