-
Notifications
You must be signed in to change notification settings - Fork 0
/
TokenAuthenticationFilterService.java
76 lines (63 loc) · 2.39 KB
/
TokenAuthenticationFilterService.java
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
package com.github.yangricardo.api_spring_boot.modules.auth.services;
import com.github.yangricardo.api_spring_boot.modules.users.model.User;
import com.github.yangricardo.api_spring_boot.modules.users.services.IUserService;
import java.io.IOException;
import java.util.Optional;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;
@Service
public class TokenAuthenticationFilterService extends OncePerRequestFilter {
@Autowired
TokenIssuerService tokenIssuerService;
@Autowired
IUserService userService;
public TokenAuthenticationFilterService(
TokenIssuerService tokenIssuerService,
IUserService userService
) {
this.tokenIssuerService = tokenIssuerService;
this.userService = userService;
}
protected String getTokenFromHeader(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
return null;
}
return token.substring(7, token.length());
}
private void authenticate(String tokenFromHeader) {
Long id = tokenIssuerService.getTokenId(tokenFromHeader);
Optional<User> optionalUser = userService.findById(id);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
user,
null,
user.getRoles()
);
SecurityContextHolder
.getContext()
.setAuthentication(usernamePasswordAuthenticationToken);
}
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
String tokenFromHeader = getTokenFromHeader(request);
boolean tokenValid = tokenIssuerService.isTokenValid(tokenFromHeader);
if (tokenValid) {
this.authenticate(tokenFromHeader);
}
filterChain.doFilter(request, response);
}
}