Bonjour � tous !
Je rencontre deux probl�mes...
J'ai une application qui fonctionne avec Spring + JWT.
D�sormais je souhaite int�grer Redis pour le stockage des tokens, suite � beaucoup de modification, le probl�me est que j'ai une erreur de base, mais je n'arrive pas du tout � trouver sa source..
J'ai tout tent�, @Autowired ou non... toujours pareil..
Code java : S�lectionner tout - Visualiser dans une fen�tre � part
1
2
3
4
5 .common.security.specific.jwt.JwtUtil.extractToken(javax.servlet.http.HttpServletRequest)" because "this.jwtUtil" is null Le problème est identique avec "because "this.tokenService" is null".. Bon en fait c'est à se demander si le autowired fonctionne.. aucune instanciation ne fonctionne..
Et mon deuxi�me probl�me, mais peut �tre li� au premier est qu'une fois que mon application m'a donn� le token, elle ne l'a pas ins�r� dans Redis ( alors que la connection est OK ).
Voila tout ce que j'ai c�t� code :
Merci pour l'aide !
JwtUtil.java
Code java : S�lectionner tout - Visualiser dans une fen�tre � part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 @Service public class JwtUtil { /** * Get the token from authorization header. * * @param request * @return token */ public String extractToken(HttpServletRequest request) { String authHeader = request.getHeader(JwtConstant.AUTHORIZATION_HEADER_STRING); if (authHeader.startsWith(JwtConstant.TOKEN_BEARER_PREFIX)) { return authHeader.replace(JwtConstant.TOKEN_BEARER_PREFIX, ""); } return null; } }
JwtAuthentificationFilter.java
Code java : S�lectionner tout - Visualiser dans une fen�tre � part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private AuthenticationManager authManager; private TokenService tokenService; private JwtHelper jwtHelper; public JwtAuthenticationFilter(AuthenticationManager authManager, TokenService tokenService, JwtHelper jwtHelper) { this.authManager = authManager; this.tokenService = tokenService; this.jwtHelper = jwtHelper; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { // Map dto value. UserDataDTO req = this.getCredentials(request); // Authenticate user. return this.authManager.authenticate(new UsernamePasswordAuthenticationToken( req.getEmail(), req.getPassword())); } catch (Exception e) { throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication auth) { try { SecurityContextHolder.getContext().setAuthentication(auth); // Create token. System.out.println("Je passe"); JwtModel model = this.jwtHelper.createToken(((User) auth.getPrincipal()).getUsername()); // Set token. this.tokenService.setSecretKey(model.getToken(), model); // Set key expiration on redis. this.tokenService.setKeyExpiration(model.getToken(), model.getExpDate()); // Add token to authorization header. response.addHeader(JwtConstant.AUTHORIZATION_HEADER_STRING, JwtConstant.TOKEN_BEARER_PREFIX + model.getToken()); } catch (Exception e) { throw new RuntimeException(e); } } private UserDataDTO getCredentials(HttpServletRequest request) { // Map dto value. UserDataDTO auth = null; try { auth = new ObjectMapper().readValue(request.getInputStream(), UserDataDTO.class); } catch (IOException e) { e.printStackTrace(); } return auth; } }
JwtAuthorizationFilter.java
Code java : S�lectionner tout - Visualiser dans une fen�tre � part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65 @Service public class JwtAuthorizationFilter extends BasicAuthenticationFilter { private UserDetailsService userDetailsService; private TokenService tokenService; private JwtHelper jwtHelper; @Autowired private JwtUtil jwtUtil; public JwtAuthorizationFilter(AuthenticationManager authenticationManager, UserDetailsService userDetailsService, TokenService tokenService, JwtHelper jwtHelper, JwtUtil jwtUtil) { super(authenticationManager); this.userDetailsService = userDetailsService; this.tokenService = tokenService; this.jwtHelper = jwtHelper; this.jwtUtil = jwtUtil; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) { try { // Check for authorization header existence. String header = request.getHeader(JwtConstant.AUTHORIZATION_HEADER_STRING); if (header == null || !header.startsWith(JwtConstant.TOKEN_BEARER_PREFIX)) { chain.doFilter(request, response); return; } // Validate request.. UsernamePasswordAuthenticationToken authorization = authorizeRequest(request); SecurityContextHolder.getContext().setAuthentication(authorization); chain.doFilter(request, response); } catch (Exception e) { SecurityContextHolder.clearContext(); throw new InternalServerErrorException(e.toString()); } } private UsernamePasswordAuthenticationToken authorizeRequest(HttpServletRequest request) { try { // Get token. String token = this.jwtUtil.extractToken(request); // PROBLEME ICI if (token != null) { // Get token key. JwtModel model = (JwtModel) this.tokenService.getSecretKey(token); // Validate token. Claims claims = this.jwtHelper.validateToken(model); // Validate user authority/role if allowed to do the api dto. String user = claims.getSubject(); System.out.println("user" + user); UserDetails userDetails = this.userDetailsService.loadUserByUsername(user); if (userDetails != null) { return new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); } } } catch (Exception e) { throw new RuntimeException(e); } return null; } }
JwtHelper.java
Code java : S�lectionner tout - Visualiser dans une fen�tre � part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90 @Service public class JwtHelper { @Value("${security.jwt.token.secret-key") private String secretKey; @Value("${security.jwt.token.expire-length}") private long validityInMilliseconds; // 1h @Value("${security.jwt.token.issuer}") private String issuer; // 1h @Autowired private MyUserDetails myUserDetails; @Autowired private UserJpaRepository userJpaRepository; @PostConstruct protected void init() { secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); } public JwtModel createToken(String email) { AppUser user = userJpaRepository.findByEmail(email); Claims claims = Jwts.claims().setSubject(email); claims.put("auth", user.getAppUserRoles().stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())) .filter(Objects::nonNull).collect(Collectors.toList())); Date current = new Date(); Date expiration = generateTokenExp(JwtConstant.ACCESS_TOKEN_EXPIRATION); String token = Jwts.builder() .setIssuer(issuer) .setClaims(claims) .setIssuedAt(current) .setExpiration(expiration) .signWith(SignatureAlgorithm.HS512, secretKey) .compact(); return new JwtModel(token, issuer, email, current, expiration); } public Authentication getAuthentication(String token) { UserDetails userDetails = myUserDetails.loadUserByUsername(getEmail(token)); return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); } public String getEmail(String token) { return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); } public String resolveToken(HttpServletRequest req) { String bearerToken = req.getHeader("Authorization"); if (bearerToken != null && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } public Claims validateToken(JwtModel model) { try { Claims claims = Jwts.parser() .requireIssuer(model.getIssuer()) .requireSubject(model.getSubject()) .requireIssuedAt(model.getIssueDate()) .requireExpiration(model.getExpDate()) .setSigningKey( secretKey) .parseClaimsJws(model.getToken()) .getBody(); return claims; } catch (JwtException | IllegalArgumentException e) { throw new InternalServerErrorException("Expired or invalid JWT token"); } } private Date generateTokenExp(Integer timeExpired) { Date current = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(current); calendar.add(Calendar.MINUTE, timeExpired); return calendar.getTime(); } }
WebSecurityConfig.java
Code java : S�lectionner tout - Visualiser dans une fen�tre � part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private UserDetailsService userDetailsService; private JwtHelper jwtHelper; private JwtUtil jwtUtil; private TokenService tokenService; @Override protected void configure(HttpSecurity http) throws Exception { // Disable CSRF (cross site request forgery) http.csrf().disable(); // No session will be created or used by spring security http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Entry points http.authorizeRequests()// .antMatchers("/users/signin").permitAll()// .antMatchers("/users/signup").permitAll()// .antMatchers("/h2-console/**/**").permitAll() // Disallow everything else.. .anyRequest().authenticated(); // If a user try to access a resource without having enough permissions http.exceptionHandling().accessDeniedPage("/login"); // Apply JWT http.addFilter(new JwtAuthenticationFilter(authenticationManager(), tokenService, jwtHelper)); http.addFilterBefore(new JwtAuthorizationFilter( authenticationManager(), userDetailsService, tokenService, jwtHelper, jwtUtil), UsernamePasswordAuthenticationFilter.class); } @Override public void configure(WebSecurity web) throws Exception { // Allow swagger to be accessed without authentication web.ignoring().antMatchers("/v2/api-docs")// .antMatchers("/swagger-resources/**")// .antMatchers("/swagger-ui.html")// .antMatchers("/configuration/**")// .antMatchers("/webjars/**")// .antMatchers("/public") // Un-secure H2 Database (for testing purposes, H2 console shouldn't be // unprotected in production) .and() .ignoring() .antMatchers("/h2-console/**/**") ; ; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(12); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
Partager