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();
}
}
Код: Выделить всё
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:

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