Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SMA-80: allow logging in and signing up with expired jwt token #71

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand Down Expand Up @@ -38,8 +39,16 @@ protected void doFilterInternal(
return;
}

final String jwt = authHeader.substring(7);
final String userEmail = jwtService.extractUserName(jwt);
final String jwt;
final String userEmail;

try {
jwt = authHeader.substring(7);
userEmail = jwtService.extractUserName(jwt);
} catch (Exception e) {
filterChain.doFilter(request, response);
return;
}

if (isUserAuthenticated(userEmail)) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.web.cors.CorsConfiguration;
Expand Down Expand Up @@ -44,7 +46,9 @@ public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
http
.exceptionHandling((exception) -> exception.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.csrf(AbstractHttpConfigurer::disable)
.headers(h -> h.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.authorizeHttpRequests(
r -> r.requestMatchers(WHITE_LIST_URL).permitAll().anyRequest().authenticated())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public ResponseEntity<?> getUserMainPage() {
try {
return ResponseEntity.ok().body(userService.getMyRank());
} catch (ResponseStatusException e) {
return ResponseEntity.badRequest().body(e.getStatusCode());
return new ResponseEntity<>(e.getMessage(), e.getStatusCode());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ void addNewPlaceShouldReturn403NotAuthenticatedUser() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/places/add")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(placeDTO)))
// Verify that the response status is 403 Forbidden
.andExpect(MockMvcResultMatchers.status().isForbidden());
// Verify that the response status is 401 Forbidden
.andExpect(MockMvcResultMatchers.status().isUnauthorized());
}

@Test
Expand Down
2 changes: 1 addition & 1 deletion frontend/sportsmatch-app/src/components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function Navbar() {
setLoggedIn(true)
} catch (error) {
const code = (error as ApiError).status
if (code == 401) {
if (code === 401) {
localStorage.removeItem('token')
setLoggedIn(false)
}
Expand Down
29 changes: 28 additions & 1 deletion frontend/sportsmatch-app/src/components/PrivateRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import { useState, useEffect } from 'react'
import { Navigate, Outlet } from 'react-router-dom'
import { OpenAPI, ExSecuredEndpointService, ApiError } from '../generated/api'

const PrivateRoute = () => {
const requestedUrl = window.location.pathname
const [isAuthorized, setAuthorized] = useState<boolean>(true)

if (localStorage.getItem('token')) {
useEffect(() => {
if (!localStorage.getItem('token')) {
setAuthorized(false)
}
}, [])

useEffect(() => {
const init = async () => {
if (localStorage.getItem('token')) {
OpenAPI.TOKEN = localStorage.getItem('token')!
try {
await ExSecuredEndpointService.getUserMainPage()
} catch (error) {
const code = (error as ApiError).status
if (code === 401) {
localStorage.removeItem('token')
setAuthorized(false)
}
}
}
}
init()
}, [])

if (isAuthorized) {
return <Outlet />
} else {
return <Navigate to={'/login'} state={requestedUrl} />
Expand Down
Loading