-
Notifications
You must be signed in to change notification settings - Fork 0
Security
Zhaoyuan YE edited this page Sep 2, 2023
·
2 revisions
Authentication & Authorization are provided by Spring Security framework + JWT Code reference
Currently, there are only two roles in this application (i.e., USER & ADMIN). To authorize user access, there are two changes that need to be made:
- add requestMatchers in WebSecurityConfig to match the URL path you want to secure
http.csrf(csrf -> csrf.disable())
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
// with no session, every requests from clients need to attach token to the header
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth ->
auth.requestMatchers("/api/books/secure/**").authenticated()
.requestMatchers("/api/reviews/secure/**").authenticated()
.anyRequest().permitAll());
- Limit access to specific roles on API in the controllers
@PutMapping("/secure/checkout")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<BookVO> checkoutBook(@RequestParam Long bookId) {
String username = jwtUtils.getUsernameFromJwtToken();
BookVO book = bookService.checkoutBook(username, bookId);
return ResponseEntity.ok(book);
}