2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2021 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ============LICENSE_END=========================================================
20 package org.o.ran.oam.nf.oam.adopter.mock.app.config;
22 import java.io.IOException;
23 import javax.servlet.FilterChain;
24 import javax.servlet.ServletException;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27 import org.o.ran.oam.nf.oam.adopter.mock.app.properties.SecurityProperties;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
31 import org.springframework.security.core.context.SecurityContextHolder;
32 import org.springframework.util.StringUtils;
33 import org.springframework.web.filter.OncePerRequestFilter;
35 public class AuthTokenFilter extends OncePerRequestFilter {
36 private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
38 public static final String TOKEN = "someRandomToken";
39 private final UsernamePasswordAuthenticationToken authentication;
41 public AuthTokenFilter(final SecurityProperties security) {
42 this.authentication = new UsernamePasswordAuthenticationToken(security.getUsername(), security.getPassword());
46 protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
47 final FilterChain filterChain) throws ServletException, IOException {
49 final String token = extractToken(request);
50 if (token != null && token.equals(TOKEN)) {
52 SecurityContextHolder.getContext().setAuthentication(authentication);
54 } catch (final Exception e) {
55 logger.error("Cannot set user authentication", e);
58 filterChain.doFilter(request, response);
61 private static String extractToken(final HttpServletRequest request) {
62 final String headerAuth = request.getHeader("Authorization");
63 if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
64 return headerAuth.substring(7);