【发布时间】:2023-03-10 06:39:01
【问题描述】:
我正在使用 Spring Boot 编写 Web 应用程序。它是基于 jwt 身份验证的 我有模型用户、教师、学生、课程。教师和学生扩展用户
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
// Other fields and getters setters
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "teacher_id", nullable = false)
private Teacher teacher;
@ManyToMany(mappedBy = "enrolledCourses")
private Set<Student> students;
// Other fields and getters setters
}
@Entity
public class Teacher extends User{
@OneToMany(mappedBy = "teacher")
private Set<Course> courses;
// Other fields and getters setters
}
@Entity
public class Student extends User{
@ManyToMany
@JoinTable(
name = "course_student",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> enrolledCourses;
// Other fields and getters setters
}
我还有课程 Api,我在其中实现了发布、放置、删除、更新和 这些方法必须仅供教师用户使用。 我的课程 Api 是这样的
@RestController
@RequestMapping("/teachers")
@PreAuthorize("hasRole('TEACHER')")
public class TeacherCourseController {
@GetMapping("/{teacherId}/courses")
public Set<Course> getCourse(@PathVariable("teacherId") Teacher teacher){
// code
}
@PostMapping("/{teacherId}/courses")
public Course createCourse(
@PathVariable("teacherId") Long teacherId,
@ModelAttribute CourseDto courseDto){
// code
}
@PutMapping("/{teacherId}/courses/{courseId}")
@JsonView(Views.IdName.class)
public Course updateCourse(
@ModelAttribute CourseDto courseDto,
@PathVariable("courseId") Course courseFromDb){
// code
}
@DeleteMapping("/{teacherId}/courses/{courseId}")
public void getCourse(@PathVariable("courseId") Course course) throws IOException {
// code
}
}
我的 api 网址变得更糟,看起来像这样 http://localhost:8080/teachers/{teacherId}/courses/{courseId} 我如何检查老师是否要求他的课程而不是其他老师。谢谢
【问题讨论】:
标签: spring-boot http security authentication jwt