powered by simpleCommunicator - 2.0.49     © 2025 Programmizd 02
Форумы / Java [игнор отключен] [закрыт для гостей] / Сервер получил запрос, но отказался его авторизовать
6 сообщений из 6, страница 1 из 1
Сервер получил запрос, но отказался его авторизовать
    #39829132
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
В моем проекте есть список студентов и туда может добавлять, удалять, редактировать студентов только админ. Когда я захожу в роли Админа на сайт, он спокойно удаляет их, но когда хочу добавить или отредактировать он выдает ошибку "сервер получил запрос, но отказался его авторизовать"

Security Config
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /*@Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withDefaultPasswordEncoder()
                .username("admin").password("1234").roles("ADMIN").build());
        return manager;
    }*/
    @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");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/allStudents**").permitAll()
                .antMatchers("/addStudent**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/editStudent/**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/deleteStudent/**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/index", "/user", "/").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/allStudents")
                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
    }

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

}


Authorization Controller
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
package adil.java.schoolmaven.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class AuthorizationController {


@RequestMapping(value="/", method=RequestMethod.GET)    
    public String index() {    

        return "allStudents";    
    }    

    @RequestMapping(value="/login", method=RequestMethod.GET)    
    public String login() {  
        return "login";    
    }    

}


Student Controller

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
@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 = "/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;

    }

}
...
Рейтинг: 0 / 0
Сервер получил запрос, но отказался его авторизовать
    #39829167
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019 он выдает ошибку "сервер получил запрос, но отказался его авторизовать"

Прям так и написал? Из какого класса ошибка выпала?
...
Рейтинг: 0 / 0
Сервер получил запрос, но отказался его авторизовать
    #39829168
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Да вот такая ошибка
...
Рейтинг: 0 / 0
Сервер получил запрос, но отказался его авторизовать
    #39829173
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Вот студента он удаляет когда захожу через админа, а когда пытаюсь добавить или редактировать он выдает вот такую ошибку
...
Рейтинг: 0 / 0
Сервер получил запрос, но отказался его авторизовать
    #39829204
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
fallen2019,

У меня получилось надо было добавить-
Код: java
1.
 http.csrf().disable().authorizeRequests()
...
Рейтинг: 0 / 0
Сервер получил запрос, но отказался его авторизовать
    #39829267
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019fallen2019,

У меня получилось надо было добавить-
Код: java
1.
 http.csrf().disable().authorizeRequests()


Вам неплохо было бы разобраться что это все значит, а не методом тыка тупо заставить работать.
То, что вы задизаблили CSRF (кстати знаете что это значит?) не есть хорошо.
...
Рейтинг: 0 / 0
6 сообщений из 6, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Сервер получил запрос, но отказался его авторизовать
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]