aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/service/security/BearerTokenAuthenticationFilter.java
blob: f4e73b12679ab7dbb056e5ab10314cd62fa45919 (plain) (blame)
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
/*
 * Copyright (C) 2008-2023, Juick
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.juick.service.security;

import com.juick.service.UserService;
import com.juick.service.security.entities.JuickUser;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.security.KeyPair;
import java.util.Collections;
import java.util.stream.Collectors;

public class BearerTokenAuthenticationFilter extends BaseAuthenticationFilter {
    private static final Logger logger = LoggerFactory.getLogger("Auth");
    private final JwtParser jwtParser;
    private final UserService userService;

    public BearerTokenAuthenticationFilter(UserService userService, KeyPair keys) {
        this.userService = userService;
        this.jwtParser = Jwts.parserBuilder()
                .setSigningKey(keys.getPrivate())
                .build();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        if (authenticationIsRequired()) {
            var headers = Collections.list(request.getHeaderNames())
                    .stream()
                    .collect(Collectors.toMap(String::toLowerCase, request::getHeader));
            var authorizationHeaderValue = headers.get("authorization");
            if (StringUtils.isNotEmpty(authorizationHeaderValue) && authorizationHeaderValue.startsWith("Bearer")) {
                String token = authorizationHeaderValue.substring(7);
                try {
                    var claims = jwtParser.parseClaimsJws(token).getBody();
                    var user = userService.getUserByName(claims.getSubject());
                    if (!user.isAnonymous()) {
                        Authentication authentication = new UsernamePasswordAuthenticationToken(
                                new JuickUser(user),
                                user.getCredentials(),
                                JuickUser.USER_AUTHORITY);
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                } catch (Exception e) {
                    logger.warn("Invalid Bearer token: {}", e.getMessage());
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}