Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 59e25e67

Přidáno uživatelem Petr Urban před asi 2 roky(ů)

#10365 - vytváření endpointu pro refresh tokenu. Token se vytvoří nový s platností na 1 h a starý se znevaliduje.

Zobrazit rozdíly:

.idea/inspectionProfiles/Project_Default.xml
1
<component name="InspectionProjectProfileManager">
2
  <profile version="1.0">
3
    <option name="myName" value="Project Default" />
4
    <inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
5
  </profile>
6
</component>
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/config/WebConfig.java
13 13
        return new WebMvcConfigurer() {
14 14
            @Override
15 15
            public void addCorsMappings(CorsRegistry registry) {
16
                registry.addMapping("/**").allowedOrigins("*");
16
                registry.addMapping("/**")
17
                        .allowedOrigins("http://localhost:3000")
18
                        .allowCredentials(true);
17 19
            }
18 20
        };
19 21
    }
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/controller/UserController.java
88 88
        return aOuthService.logoutUser(user);
89 89
    }
90 90

  
91
    @GetMapping("/refresh")
92
    public ResponseEntity<String> refreshToken(@RequestHeader HttpHeaders headers) {
93
        final String authHeader = headers.getFirst(HttpHeaders.AUTHORIZATION);
94
        if (authHeader == null || !authHeader.startsWith("Bearer")) {
95
            // err
96
        }
97
        final String token = authHeader.substring(7);
98

  
99
        String jwtToken = null;
100
        ResponseEntity<String> response = aOuthService.refreshToken(token);
101

  
102
        if (response.getStatusCode().is2xxSuccessful()) {
103
            jwtToken = response.getBody();
104
            return getResponseEntity(UserModelStatusCodes.TOKEN_REFRESHED,jwtToken);
105
        }
106

  
107
        return getResponseEntity(UserModelStatusCodes.TOKEN_EXPIRED, UserModelStatusCodes.TOKEN_EXPIRED.getLabel());
108

  
109
    }
110

  
91 111
    /**
92 112
     * Method to create response
93 113
     *
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/httpExceptions/CustomExceptionHandler.java
1
package cz.zcu.fav.kiv.antipatterndetectionapp.v2.httpExceptions;
2

  
3
import org.springframework.http.HttpStatus;
4
import org.springframework.http.ResponseEntity;
5
import org.springframework.web.bind.annotation.ControllerAdvice;
6
import org.springframework.web.bind.annotation.ExceptionHandler;
7
import org.springframework.web.client.HttpClientErrorException;
8

  
9
@ControllerAdvice
10
public class CustomExceptionHandler {
11

  
12
    @ExceptionHandler(HttpClientErrorException.Unauthorized.class)
13
    public ResponseEntity<String> handleUnauthorizedException(HttpClientErrorException.Unauthorized ex) {
14
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ex.getResponseBodyAsString());
15
    }
16

  
17
}
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/JwtAuthenticationFilter.java
1 1
package cz.zcu.fav.kiv.antipatterndetectionapp.v2.security;
2 2

  
3
import cz.zcu.fav.kiv.antipatterndetectionapp.v2.httpExceptions.CustomExceptionHandler;
3 4
import cz.zcu.fav.kiv.antipatterndetectionapp.v2.service.OAuthService;
4 5
import org.springframework.http.*;
5 6
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
......
59 60
            }*/
60 61
        } catch (Exception e) {
61 62
            SecurityContextHolder.clearContext();
62
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
63
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
63 64
            response.getOutputStream().println("{\"error\" : \"Some other error related to jwt token!\"}");
64 65
            return;
65 66
        }
66 67

  
67 68
        chain.doFilter(request, response);
68 69
    }
70

  
71
    @Override
72
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
73
            String path = request.getRequestURI().substring(request.getContextPath().length());
74
        return path.startsWith("/v2/user/");
75
    }
69 76
}
70 77

  
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/WebSecurityConfig.java
64 64
        httpSecurity
65 65
                .csrf().disable()
66 66
                .authorizeRequests()
67
                .antMatchers("/v2/user/register", "/v2/user/login").permitAll()
67
                .mvcMatchers("/v2/user/register", "/v2/user/login", "/v2/user/refresh", "/v2/user/logout").permitAll()
68 68
                .anyRequest().authenticated()
69
//                .and()
70
//                .exceptionHandling()
71
//                .authenticationEntryPoint(new OAuthServiceImpl())
72 69
                .and()
73 70
                .sessionManagement()
74 71
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
75 72
                .and()
76 73
                .addFilterBefore(new JwtAuthenticationFilter(new OAuthServiceImpl()), UsernamePasswordAuthenticationFilter.class);
77
//        httpSecurity.addFilterAfter(new JwtAuthenticationFilter(new OAuthServiceImpl()), UsernamePasswordAuthenticationFilter.class);
78
//        httpSecurity.addFilter(new JwtAuthenticationFilter(new OAuthServiceImpl()));
79 74
    }
80 75

  
81 76
}
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/service/OAuthService.java
10 10
    public ResponseEntity<String> authenticate(String token);
11 11
    public ResponseEntity<String> loginUser(User user);
12 12
    public ResponseEntity<String> logoutUser(User user);
13

  
14
    ResponseEntity<String> refreshToken(String token);
15

  
13 16
}
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/service/OAuthServiceImpl.java
44 44
//    @Value("${auth.realm.logout}")
45 45
    private String AUTH_URL_LOGOUT = "http://localhost:8081/logout";
46 46

  
47
    private String AUTH_URL_REFRESH = "http://localhost:8081/refresh";
48

  
47 49
    /**
48 50
     *
49 51
     */
......
89 91
        return RequestBuilder.sendRequestResponse(AUTH_URL_LOGOUT, requestBody);
90 92
    }
91 93

  
94
    @Override
95
    public ResponseEntity<String> refreshToken(String token) {
96
        return RequestBuilder.sendRequestResponse(AUTH_URL_REFRESH, token, true);
97
    }
98

  
92 99
    @Override
93 100
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
94 101
        final User user = this.userService.getUserByName(s);
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/utils/RequestBuilder.java
44 44
        return response;
45 45
    }
46 46

  
47
    public static ResponseEntity<String> sendRequestResponse(String url, String token, boolean get) {
48
        RestTemplate restTemplate = new RestTemplate();
49

  
50
        HttpHeaders headers = new HttpHeaders();
51

  
52
        headers.setContentType(MediaType.APPLICATION_JSON);
53
        //headers.set("X-spade-request",spadeSignature);
54
        headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
55

  
56
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
57
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
58
        return response;
59
    }
60

  
47 61
}

Také k dispozici: Unified diff