每个角色都有其自己的可访问页面

时间:2019-06-26 03:29:11

标签: spring spring-mvc spring-security

我创建了一个项目,管理员和用户可以登录。我有JSP页面,只有管理员可以进入那里,因为访问仅限于用户。用户可以转到某些页面。 我有两个页面“ allStudents.jsp”-只有管理员可以去那里。 并且在此页面上的“ allStudentsUser.jsp”-只有用户可以输入。 因此,这就是在控制器中正确编写代码的方式,以便Tomkat可以读取我的“ allStudentsUser.jsp”页面。

学生控制器

C:\>myApp.exe
Traceback (most recent call last):
  File "site-packages\PyInstaller\loader\rthooks\pyi_rth_qt5plugins.py", line 47
, in <module>
ModuleNotFoundError: No module named 'PyQt5'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "site-packages\PyInstaller\loader\rthooks\pyi_rth_qt5plugins.py", line 49
, in <module>
  File "c:\users\me\appdata\local\programs\python\python37-32\lib\site-pack
ages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "site-packages\PySide2\__init__.py", line 49, in <module>
  File "site-packages\PySide2\__init__.py", line 21, in _setupQtDirectories
  File "c:\users\me\appdata\local\programs\python\python37-32\lib\site-pack
ages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "site-packages\shiboken2\__init__.py", line 4, in <module>
ImportError: DLL load failed: The specified module could not be found.
[8272] Failed to execute script pyi_rth_qt5plugins

安全配置

@Controller
public class StudentController {

    @Autowired
    private ServletContext servletContext;

    // Constructor based Dependency Injection
    private StudentService studentService;

    public StudentController() {

    }

    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @RequestMapping(value = "/allStudents",  method = {RequestMethod.GET, RequestMethod.POST})

    public ModelAndView displayAllUser() {
        System.out.println("User Page Requested : All Students");
        ModelAndView mv = new ModelAndView();
        List<Student> studentList = studentService.getAllStudents();
        mv.addObject("studentList", studentList);
        mv.setViewName("allStudents");
        return mv;
    }

    @RequestMapping(value = "/allStudentsUser",  method = {RequestMethod.GET, RequestMethod.POST})

    public ModelAndView displayAllUsers() {
        System.out.println("User Page Requested : All Students");
        ModelAndView mv = new ModelAndView();
        List<Student> studentList = studentService.getAllStudents();
        mv.addObject("studentList", studentList);
        mv.setViewName("allStudentsUser");
        return mv;
    }



    @RequestMapping(value = "/addStudent", method = RequestMethod.GET)
    public ModelAndView displayNewUserForm() {
        ModelAndView mv = new ModelAndView("addStudent");
        mv.addObject("headerMessage", "Add Student Details");
        mv.addObject("student", new Student());
        return mv;
    }

    @PostMapping(value = "/addStudent")
    public String saveNewStudent(@RequestParam("name") @NonNull String name,
            @RequestParam("surname") @NonNull String surname,
            @RequestParam("avatar") MultipartFile file)
            throws IOException {

        Student student = new Student();
        student.setSurname(surname);
        student.setName(name);

        if (file != null && !file.isEmpty()) {
            student.setAvatar(studentService.saveAvatarImage(file).getName());
        }

        studentService.saveStudent(student);
        return "redirect:/allStudents";
    }

    @GetMapping(value = "/editStudent/{id}")
    public ModelAndView displayEditUserForm(@PathVariable Long id) {
        ModelAndView mv = new ModelAndView("editStudent");
        Student student = studentService.getStudentById(id);
        mv.addObject("headerMessage", "Редактирование студента");
        mv.addObject("student", student);
        return mv;
    }

    @PostMapping(value = "/editStudent")
    public String saveEditedUser(
            @RequestParam("id") Long id,
            @RequestParam("name") String name,
            @RequestParam("surname") String surname,
            @RequestParam("avatar") MultipartFile file) {

        try {

            studentService.updateStudent(name, surname, file, studentService.getStudentById(id));

        } catch (FileSystemException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            return "redirect:/error";
        }

        return "redirect:/allStudents";
    }

    @GetMapping(value = "/deleteStudent/{id}")
    public ModelAndView deleteUserById(@PathVariable Long id) {
        studentService.deleteStudentById(id);
        ModelAndView mv = new ModelAndView("redirect:/allStudents");

        return mv;

    }

}

AllStudents.jsp(对于管理员)

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password(passwordEncoder().encode("1234")).roles("ADMIN")
                .and()
                .withUser("user").password(passwordEncoder().encode("user1234")).roles("USER")
                .and();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/allStudentsUser**").permitAll()
                .antMatchers("/allStudents**").hasRole("ADMIN")
                .antMatchers("/addStudent/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/editStudent/**").hasRole("ADMIN")
                .antMatchers("/deleteStudent/**").hasRole("ADMIN")
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/allStudents")
                .failureUrl("/login?error=true")
                .and()
                .logout()
                .logoutSuccessUrl("/login?logout=true")
                .and()
                .csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

AllStudentsUser.jsp(对于用户)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        <link href="../css/style.css" rel="stylesheet" type="text/css">
        <style><%@include file="/css/style.css"%></style>
        <title>Все студенты</title>
    </head>
    <body>
            <br>
            <br>
            <br>
            <br>
            <div class="it">
                <h3>Список всех студентов</h3>
                ${message}

                <br>
                <br>
                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Name</th>

                            <th scope="col">Surname</th>
                            <th scope="col">Avatar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach var="student" items="${studentList}">
                            <tr>
                                <th scope="row">1</th>
                                <td>${student.name}</td>
                                <td>${student.surname}</td>

                                <td><img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" style="max-height: 200px; max-width: 200px;" /></td>

                                <td>
                                    <sec:authorize access="hasRole('ADMIN')">
                                        <a href="${pageContext.request.contextPath}/editStudent/${student.id}">
                                            <button type="button" class="btn btn-primary">Edit</button>
                                        </a>
                                    </sec:authorize>
                                </td>
                                <td>
                                    <sec:authorize access="hasRole('ADMIN')">
                                        <a href="${pageContext.request.contextPath}/deleteStudent/${student.id}">
                                            <button type="button" class="btn btn-primary">Delete</button>
                                        </a>
                                    </sec:authorize>
                                </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>

            </div>

    </body>
</html>

学生控制器(添加安全保护)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        <link href="../css/style.css" rel="stylesheet" type="text/css">
        <style><%@include file="/css/style.css"%></style>
        <title>Все студенты</title>
    </head>
    <body>
            <br>
            <br>
            <br>
            <br>
            <div class="it">
                <h3>Список всех студентов</h3>
                ${message}

                <br>
                <br>
                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Name</th>

                            <th scope="col">Surname</th>
                            <th scope="col">Avatar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach var="student" items="${studentList}">
                            <tr>
                                <th scope="row">1</th>
                                <td>${student.name}</td>
                                <td>${student.surname}</td>

                                <td><img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" style="max-height: 200px; max-width: 200px;" /></td>


                            </tr>
                        </c:forEach>
                    </tbody>
                </table>

            </div>

    </body>
</html>

1 个答案:

答案 0 :(得分:0)

我建议使用@Secured("ADMIN")@Secured("USER")

如果要使用它,请添加到SecurityConfig.java上的@EnableGlobalMethodSecurity(securedEnabled = true)

您的代码示例:

    @Secured("ROLE_ADMIN")
    @RequestMapping(value = "/allStudents",  method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView displayAllUser() {
        // ...
    }
    @Secured("ROLE_USER")
    @RequestMapping(value = "/allStudentsUser",  method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView displayAllUsers() {
        // ...
    }

指南链接:https://docs.spring.io/spring-security/site/docs/5.2.0.M3/reference/htmlsingle/#jc-method