Не получен желаемый ответ на http-запрос. Весенняя безопасностьJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Не получен желаемый ответ на http-запрос. Весенняя безопасность

Сообщение Anonymous »

Не возвращается список пользователей при запросе через Postman.
SecurityConfig:

Код: Выделить всё


package com.example.demo.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig {

@Bean
public UserDetailsManager userDetailsManager(DataSource dataSource) {
return new JdbcUserDetailsManager(dataSource);
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(configurer ->
configurer
.requestMatchers(HttpMethod.GET, "/users").hasRole("EMPLOYEE")
.requestMatchers(HttpMethod.GET, "/users/{id}").hasRole("EMPLOYEE")
.requestMatchers(HttpMethod.POST, "/users/create").hasRole("MANAGER")
.requestMatchers(HttpMethod.PUT, "/users/**").hasRole("MANAGER")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
.requestMatchers("/swagger-ui/**").permitAll()
.anyRequest().authenticated()
);

// use HTTP Basic authentication
http.httpBasic(Customizer.withDefaults());

// disable Cross Site Request Forgery (CSRF)
// in general, not required for stateless REST APIs that use POST, PUT, DELETE and/or PATCH
http.csrf(AbstractHttpConfigurer::disable);

return http.build();
}
}
UserRestController:

Код: Выделить всё

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.userservice.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Tag(name = "Users")
public class UserRestController {

private final UserService userService;

@Autowired
public UserRestController(UserService theUserService) {
userService = theUserService;
}

@Operation(
description = "Get an endpoint for all users",
summary = "Get all the users in JSON format"
)
@GetMapping("/users")
public List  getAllUsers() {
return userService.findAll();
}

@Operation(
description = "Get an endpoint for a user with a unique ID",
summary = "Get a specific user by providing a unique ID that exists in the database"
)
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
User user = userService.findById(id);
if (user == null) {
throw new RuntimeException("User not found");
}
return user;
}

@Operation(
description = "Get an endpoint for a user/all users with a specific name",
summary = "Get the JSON format for a user/all users with a specific name"
)
@GetMapping("/users/name/{username}")
public User getUserByFirstName(@PathVariable String username) {
User user = userService.findByUsername(username);
if (user == null) {
throw new RuntimeException("User not found");
}
return user;
}

@Operation(
description = "Delete the user with specific ID",
summary = "Delete the user from the database by providing a specific ID that exists in the database"
)
@DeleteMapping("/users/delete/{id}")
public String deleteUserById(@PathVariable Long id) {
User tempUser = userService.findById(id);

if (tempUser == null) {
throw new RuntimeException("User not found");
}

userService.delete(id);

return "User deleted - " + tempUser;
}

@Operation(
description = "Post a user by providing needed details",
summary="Post a user by providing the firstName, lastName, and userRole consecutively."
)
@PostMapping("/users/create")
public String createUser(@RequestBody User userRequest) {
User user = new User(userRequest.getUsername(), userRequest.getPassword());
//user.setId(12l);
userService.save(user);
return "User created - " + user;
}

}
Таблица пользователей из MySQL:
Изображение

Таблица полномочий (ролей) из MySQL:
Изображение

Я отправил запрос на http://localhost:8080/users и ожидал список всех пользователей. Операция успешна, когда Spring Security выключена, но когда она включена, она не работает

Подробнее здесь: https://stackoverflow.com/questions/788 ... g-security
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»