Skip to content

Commit

Permalink
Feat : ajout controller vérification validité du token
Browse files Browse the repository at this point in the history
Fix sur signin : en cas de login / mdp incorrect envoie d'une erreur 401
  • Loading branch information
pierre-maraval committed Jun 19, 2024
1 parent 6037108 commit a504232
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
Expand All @@ -24,6 +25,9 @@ public ResponseEntity<?> handleForbiddenFailures(Throwable t) {
return errorResponse(t, HttpStatus.FORBIDDEN);
}

@ExceptionHandler(BadCredentialsException.class)
public ResponseEntity<?> handleBadCredentials(Throwable t) { return errorResponse(t, HttpStatus.UNAUTHORIZED); }

@ExceptionHandler({ IllegalArgumentException.class, FileCheckingException.class, FileTypeException.class})
public ResponseEntity<?> handleMiscFailures(Throwable t) {
return errorResponse(t, HttpStatus.BAD_REQUEST);
Expand Down
36 changes: 19 additions & 17 deletions web/src/main/java/fr/abes/item/security/SpringSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,33 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}

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

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/api/v1/signin").permitAll()
.requestMatchers("/api/v1/applicationDetails").permitAll()
.requestMatchers("/api/v1/applicationStatutServices").permitAll()
.requestMatchers("/api/v1/v2/api-docs", "/api/v1/configuration/ui", "/api/v1/swagger-resources/**", "/api/v1/configuration/**", "/api/v1/swagger-ui.html", "/api/v1/webjars/**").permitAll()
.anyRequest().authenticated())
.sessionManagement(manager -> manager.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/api/v1/signin").permitAll()
.requestMatchers("/api/v1/checkToken").permitAll()
.requestMatchers("/api/v1/applicationDetails").permitAll()
.requestMatchers("/api/v1/applicationStatutServices").permitAll()
.requestMatchers("/api/v1/v2/api-docs", "/api/v1/configuration/ui", "/api/v1/swagger-resources/**", "/api/v1/configuration/**", "/api/v1/swagger-ui.html", "/api/v1/webjars/**").permitAll()
.anyRequest().authenticated())
.sessionManagement(manager -> manager.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}

}
17 changes: 12 additions & 5 deletions web/src/main/java/fr/abes/item/web/AuthenticationController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@
import fr.abes.item.security.LoginRequest;
import fr.abes.item.security.User;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;


@RestController
Expand All @@ -33,7 +32,7 @@ public AuthenticationController(AuthenticationManager authenticationManager, Jwt
@Operation(summary = "permet de s'authentifier et de récupérer un token.",
description = "le token doit être utilisé pour accéder aux ressources protegées.")
@PostMapping("/signin")
public ResponseEntity<JwtAuthenticationResponse> authenticateUser(@RequestBody LoginRequest loginRequest) throws ForbiddenException {
public ResponseEntity<JwtAuthenticationResponse> authenticateUser(@RequestBody LoginRequest loginRequest) throws ForbiddenException, BadCredentialsException {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
User user = (User)authentication.getPrincipal();
Expand All @@ -44,4 +43,12 @@ public ResponseEntity<JwtAuthenticationResponse> authenticateUser(@RequestBody L

return ResponseEntity.ok(new JwtAuthenticationResponse(jwt, user.getUserNum(), user.getShortName(), user.getIln(), user.getRole(), user.getMail()));
}

@Operation(summary = "Permet de vérifier la validité d'un token")
@GetMapping("/checkToken")
public Boolean checkToken(HttpServletRequest request) {
String jwt = tokenProvider.getJwtFromRequest(request);
if (jwt == null) return false;
return tokenProvider.validateToken(jwt);
}
}

0 comments on commit a504232

Please sign in to comment.