Projekt

Obecné

Profil

Stáhnout (4.2 KB) Statistiky
| Větev: | Tag: | Revize:
1
package cz.zcu.kiv.backendapi.security.jwt;
2

    
3
import com.auth0.jwt.JWT;
4
import com.auth0.jwt.algorithms.Algorithm;
5
import com.fasterxml.jackson.databind.ObjectMapper;
6
import cz.zcu.kiv.backendapi.user.UserEntity;
7
import lombok.RequiredArgsConstructor;
8
import lombok.extern.slf4j.Slf4j;
9
import org.springframework.security.authentication.AuthenticationManager;
10
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
11
import org.springframework.security.core.Authentication;
12
import org.springframework.security.core.AuthenticationException;
13
import org.springframework.security.core.GrantedAuthority;
14
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
15

    
16
import javax.servlet.FilterChain;
17
import javax.servlet.http.HttpServletRequest;
18
import javax.servlet.http.HttpServletResponse;
19
import java.io.IOException;
20
import java.time.LocalDate;
21
import java.time.LocalDateTime;
22
import java.time.ZoneId;
23
import java.util.Date;
24
import java.util.stream.Collectors;
25

    
26
/**
27
 * Class that checks login and provides user with tokens after successful login
28
 */
29
@Slf4j
30
@RequiredArgsConstructor
31
public class JwtUsernameAndPasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
32
    /**
33
     * Authentication manager
34
     */
35
    private final AuthenticationManager authenticationManager;
36

    
37
    /**
38
     * JWT utils
39
     */
40
    private final JwtUtils jwtUtils;
41

    
42
    /**
43
     * Attempts authentication - checks username and password
44
     *
45
     * @param request  request (contains username and password)
46
     * @param response response
47
     * @return authentication manager
48
     * @throws AuthenticationException authentication exception
49
     */
50
    @Override
51
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
52
        try {
53
            UsernameAndPasswordAuthenticationRequest authenticationRequest = new ObjectMapper()
54
                    .readValue(request.getInputStream(), UsernameAndPasswordAuthenticationRequest.class);
55
            log.info("Username is: " + authenticationRequest.getUsername());
56
            log.info("Password is: " + authenticationRequest.getPassword());
57
            Authentication authentication = new UsernamePasswordAuthenticationToken(
58
                    authenticationRequest.getUsername(),
59
                    authenticationRequest.getPassword()
60
            );
61
            return authenticationManager.authenticate(authentication);
62
        } catch (IOException e) {
63
            log.error("Error getting authentication request from request: " + e.getMessage());
64
            throw new RuntimeException(e);
65
        }
66
    }
67

    
68
    /**
69
     * Handles successful authentication - sends tokens to client
70
     *
71
     * @param request        request
72
     * @param response       response
73
     * @param chain          filter chain
74
     * @param authentication authentication
75
     * @throws IOException I/O exception
76
     */
77
    @Override
78
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException {
79
        UserEntity user = (UserEntity) authentication.getPrincipal();
80

    
81
        Algorithm algorithm = jwtUtils.getAlgorithm(); //TODO secure
82

    
83
        String access_token = JWT.create()
84
                .withSubject(user.getUsername())
85
                .withExpiresAt(Date.from((LocalDateTime.now().plusMinutes(jwtUtils.getTokenExpirationAfterMinutes())).atZone(ZoneId.systemDefault()).toInstant()))
86
                .withIssuer(request.getRequestURL().toString())
87
                .withClaim(jwtUtils.getClaimAuthoritiesName(), user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
88
                .sign(algorithm);
89

    
90
        String refresh_token = JWT.create()
91
                .withSubject(user.getUsername())
92
                .withExpiresAt(Date.from((LocalDate.now().plusMonths(jwtUtils.getRefreshTokenExpirationAfterMonths())).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()))
93
                .withIssuer(request.getRequestURL().toString())
94
                .sign(algorithm);
95

    
96
        jwtUtils.writeTokensToResponse(response, access_token, refresh_token);
97
    }
98
}
(2-2/4)