2 * Copyright (C) 2019 Bell Canada.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.onap.ccsdk.cds.blueprintsprocessor.security;
18 import java.nio.charset.StandardCharsets;
19 import java.util.Base64;
20 import org.springframework.beans.factory.annotation.Autowired;
21 import org.springframework.http.HttpHeaders;
22 import org.springframework.http.server.reactive.ServerHttpRequest;
23 import org.springframework.security.authentication.BadCredentialsException;
24 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
25 import org.springframework.security.core.Authentication;
26 import org.springframework.security.core.context.SecurityContext;
27 import org.springframework.security.core.context.SecurityContextImpl;
28 import org.springframework.security.web.server.context.ServerSecurityContextRepository;
29 import org.springframework.stereotype.Component;
30 import org.springframework.web.server.ServerWebExchange;
31 import reactor.core.publisher.Mono;
34 public class SecurityContextRepository implements ServerSecurityContextRepository {
37 private AuthenticationManager authenticationManager;
40 public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) {
41 throw new UnsupportedOperationException("Not supported.");
45 public Mono<SecurityContext> load(ServerWebExchange swe) {
46 ServerHttpRequest request = swe.getRequest();
47 String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
48 if (authHeader != null && authHeader.startsWith("Basic")) {
49 String[] tokens = decodeBasicAuth(authHeader);
50 String username = tokens[0];
51 String password = tokens[1];
52 Authentication auth = new UsernamePasswordAuthenticationToken(username, password);
53 return this.authenticationManager.authenticate(auth).map(SecurityContextImpl::new);
59 private String[] decodeBasicAuth(String authHeader) {
62 basicAuth = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes(StandardCharsets.UTF_8)),
63 StandardCharsets.UTF_8);
64 } catch (IllegalArgumentException | IndexOutOfBoundsException e) {
65 throw new BadCredentialsException("Failed to decode basic authentication token");
68 int delim = basicAuth.indexOf(':');
70 throw new BadCredentialsException("Failed to decode basic authentication token");
73 return new String[]{basicAuth.substring(0, delim), basicAuth.substring(delim + 1)};