Merge pull request #52 from HideyoshiSolutions/devel

Fixes unhandled authentication error (#51)
This commit is contained in:
2024-05-26 02:02:05 -03:00
committed by GitHub
4 changed files with 45 additions and 41 deletions

View File

@@ -94,35 +94,48 @@ public class UserController {
@PostMapping("/profile-picture") @PostMapping("/profile-picture")
@UserResourceGuard(accessType = UserResourceGuardEnum.USER) @UserResourceGuard(accessType = UserResourceGuardEnum.USER)
public StorageServiceUploadResponse addProfilePicture( public ResponseEntity<StorageServiceUploadResponse> addProfilePicture(
@RequestParam FileTypeEnum fileType @RequestParam FileTypeEnum fileType
) { ) {
UserDTO user = this.authService.getLoggedUser(); UserDTO user = this.authService.getLoggedUser();
return this.storageService.getNewFileUrl(
var newFileOption = this.storageService.getNewFileUrl(
user.getUsername(), user.getUsername(),
"profile", "profile",
fileType fileType
).orElseThrow(() -> new BadRequestException("File not found")); );
if (newFileOption.isEmpty()) {
throw new BadRequestException("Invalid File Type");
}
return ResponseEntity.ok(newFileOption.get());
} }
@DeleteMapping("/profile-picture") @DeleteMapping("/profile-picture")
@UserResourceGuard(accessType = UserResourceGuardEnum.USER) @UserResourceGuard(accessType = UserResourceGuardEnum.USER)
public void deleteProfilePicture() { public ResponseEntity<Void> deleteProfilePicture() {
UserDTO user = this.authService.getLoggedUser(); UserDTO user = this.authService.getLoggedUser();
this.storageService.deleteFile( this.storageService.deleteFile(
user.getUsername(), user.getUsername(),
"profile" "profile"
); );
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }
@PostMapping("/profile-picture/proccess") @PostMapping("/profile-picture/proccess")
@UserResourceGuard(accessType = UserResourceGuardEnum.USER) @UserResourceGuard(accessType = UserResourceGuardEnum.USER)
public void processProfilePicture() { public ResponseEntity<Void> processProfilePicture() {
UserDTO user = this.authService.getLoggedUser(); UserDTO user = this.authService.getLoggedUser();
this.storageService.processFile( this.storageService.processFile(
user.getUsername(), user.getUsername(),
"profile" "profile"
); );
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }
} }

View File

@@ -61,15 +61,31 @@ public class SecurityConfig {
http.httpBasic().disable() http.httpBasic().disable()
.cors().and().csrf().disable(); .cors().and().csrf().disable();
this.addEndpointSecurityToHttp(http); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
this.addOAuthSecurityToHttp(http);
this.configureEndpoints(http); http.exceptionHandling()
.authenticationEntryPoint(this::failureHandler);
return http.build(); http.formLogin(form -> form
} .loginProcessingUrl("/user/login")
.successHandler(this::successFormHandler)
.failureHandler(this::failureHandler)
);
http.oauth2Login(
oauth -> oauth
.authorizationEndpoint()
.authorizationRequestRepository(this.oAuthRequestRepository)
.and().successHandler(this::successOAuth2Handler)
.failureHandler(this::failureHandler)
);
http.addFilterBefore(
new JWTAuthenticationFilter(this.authService),
UsernamePasswordAuthenticationFilter.class
);
private void configureEndpoints(HttpSecurity http) throws Exception {
for (String endpoint : this.userResourceHandler.getOpenPaths()) { for (String endpoint : this.userResourceHandler.getOpenPaths()) {
http.authorizeRequests().antMatchers(endpoint).permitAll(); http.authorizeRequests().antMatchers(endpoint).permitAll();
} }
@@ -78,30 +94,7 @@ public class SecurityConfig {
http.authorizeRequests().antMatchers(endpoint).hasAnyAuthority("ROLE_USER", "ROLE_ADMIN"); http.authorizeRequests().antMatchers(endpoint).hasAnyAuthority("ROLE_USER", "ROLE_ADMIN");
} }
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED); return http.build();
http.addFilterBefore(
new JWTAuthenticationFilter(this.authService),
UsernamePasswordAuthenticationFilter.class
);
}
private void addEndpointSecurityToHttp(HttpSecurity http) throws Exception {
http.formLogin(form -> form
.loginProcessingUrl("/user/login")
.successHandler(this::successFormHandler)
.failureHandler(this::failureHandler)
);
http.authorizeRequests().antMatchers("/login").denyAll();
}
private void addOAuthSecurityToHttp(HttpSecurity http) throws Exception {
http.oauth2Login()
.authorizationEndpoint()
.authorizationRequestRepository(this.oAuthRequestRepository)
.and().successHandler(this::successOAuth2Handler)
.failureHandler(this::failureHandler);
} }
private void successFormHandler(HttpServletRequest request, private void successFormHandler(HttpServletRequest request,

View File

@@ -1,7 +1,7 @@
package br.com.hideyoshi.auth.security.filter; package br.com.hideyoshi.auth.security.filter;
import br.com.hideyoshi.auth.security.service.AuthService; import br.com.hideyoshi.auth.security.service.AuthService;
import br.com.hideyoshi.auth.util.exception.AuthenticationInvalidException; import br.com.hideyoshi.auth.util.exception.BadRequestException;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
@@ -52,7 +52,7 @@ public class JWTAuthenticationFilter extends OncePerRequestFilter {
String accessToken = authorizationHeader.substring(AUTHORIZATION_TYPE_STRING.length()); String accessToken = authorizationHeader.substring(AUTHORIZATION_TYPE_STRING.length());
return this.authService.extractAccessTokenInfo(accessToken); return this.authService.extractAccessTokenInfo(accessToken);
} else { } else {
throw new AuthenticationInvalidException("Access denied"); throw new BadRequestException("No authorization header found");
} }
} }
} }

View File

@@ -27,7 +27,6 @@ import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import javax.validation.Valid; import javax.validation.Valid;
import java.io.IOException; import java.io.IOException;
@@ -130,11 +129,10 @@ public class AuthService {
JWTVerifier verifier = JWT.require(algorithm).build(); JWTVerifier verifier = JWT.require(algorithm).build();
try { try {
return Optional.of(verifier.verify(token)); return Optional.of(verifier.verify(token));
} catch (Exception e) { } catch (Exception ignored) {
log.warn("Token verification failed: {}", e.getMessage());
}
return Optional.empty(); return Optional.empty();
} }
}
private UserDTO getUserFromOAuth2User(OAuthDTO oAuth2User) { private UserDTO getUserFromOAuth2User(OAuthDTO oAuth2User) {
UserDTO user; UserDTO user;