1 | package com.example.rezevirajmasa.demo.config;
|
---|
2 |
|
---|
3 | import com.auth0.jwt.JWT;
|
---|
4 | import com.auth0.jwt.JWTVerifier;
|
---|
5 | import com.auth0.jwt.algorithms.Algorithm;
|
---|
6 | import com.auth0.jwt.interfaces.DecodedJWT;
|
---|
7 | import com.example.rezevirajmasa.demo.dto.UserDto;
|
---|
8 | import com.example.rezevirajmasa.demo.service.UserService;
|
---|
9 | import jakarta.annotation.PostConstruct;
|
---|
10 | import lombok.RequiredArgsConstructor;
|
---|
11 | import org.springframework.beans.factory.annotation.Value;
|
---|
12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
---|
13 | import org.springframework.security.core.Authentication;
|
---|
14 | import org.springframework.stereotype.Component;
|
---|
15 |
|
---|
16 | import java.util.Base64;
|
---|
17 | import java.util.Collections;
|
---|
18 | import java.util.Date;
|
---|
19 |
|
---|
20 | @RequiredArgsConstructor
|
---|
21 | @Component
|
---|
22 | public class UserAuthProvider {
|
---|
23 | @Value("${security.jwt.token.secret-key:secret:value}")
|
---|
24 | private String secretKey;
|
---|
25 |
|
---|
26 | private final UserService userService;
|
---|
27 |
|
---|
28 | @PostConstruct
|
---|
29 | protected void init() {
|
---|
30 | secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
|
---|
31 | }
|
---|
32 |
|
---|
33 | public String createToken(String login) {
|
---|
34 | Date now = new Date();
|
---|
35 | Date validity = new Date(now.getTime() + 3_600_000);
|
---|
36 | return JWT.create()
|
---|
37 | .withIssuer(login)
|
---|
38 | .withIssuedAt(now)
|
---|
39 | .withExpiresAt(validity)
|
---|
40 | .sign(Algorithm.HMAC256(secretKey));
|
---|
41 | }
|
---|
42 |
|
---|
43 | public Authentication validateToken(String token) {
|
---|
44 | JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
|
---|
45 |
|
---|
46 | DecodedJWT decoded = verifier.verify(token);
|
---|
47 |
|
---|
48 | UserDto user = userService.findByEmail(decoded.getIssuer());
|
---|
49 |
|
---|
50 | return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
|
---|
51 | }
|
---|
52 | }
|
---|