Migrate ccsdk/apps to ccsdk/cds
[ccsdk/cds.git] / ms / blueprintsprocessor / application / src / main / java / org / onap / ccsdk / cds / blueprintsprocessor / security / BasicAuthServerInterceptor.java
1 /*
2  * Copyright (C) 2019 Bell Canada.
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package org.onap.ccsdk.cds.blueprintsprocessor.security;
17
18 import com.google.common.base.Strings;
19 import io.grpc.Metadata;
20 import io.grpc.ServerCall;
21 import io.grpc.ServerCallHandler;
22 import io.grpc.ServerInterceptor;
23 import io.grpc.Status;
24 import java.nio.charset.StandardCharsets;
25 import java.util.Base64;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import org.springframework.beans.factory.annotation.Autowired;
29 import org.springframework.security.authentication.BadCredentialsException;
30 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
31 import org.springframework.security.core.Authentication;
32 import org.springframework.security.core.AuthenticationException;
33 import org.springframework.security.core.context.SecurityContextHolder;
34 import org.springframework.stereotype.Component;
35
36 @Component
37 public class BasicAuthServerInterceptor implements ServerInterceptor {
38
39     private static Logger log = LoggerFactory.getLogger(BasicAuthServerInterceptor.class);
40
41     @Autowired
42     private AuthenticationManager authenticationManager;
43
44
45     @Override
46     public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
47         ServerCall<ReqT, RespT> call,
48         Metadata headers,
49         ServerCallHandler<ReqT, RespT> next) {
50         String authHeader = headers.get(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER));
51
52         if (Strings.isNullOrEmpty(authHeader)) {
53             throw Status.UNAUTHENTICATED.withDescription("Missing required authentication").asRuntimeException();
54
55         }
56
57         try {
58             String[] tokens = decodeBasicAuth(authHeader);
59             String username = tokens[0];
60
61             log.info("Basic Authentication Authorization header found for user: {}", username);
62
63             Authentication authRequest = new UsernamePasswordAuthenticationToken(username, tokens[1]);
64             Authentication authResult = authenticationManager.authenticate(authRequest).block();
65
66             log.info("Authentication success: {}", authResult);
67
68             SecurityContextHolder.getContext().setAuthentication(authResult);
69
70         } catch (AuthenticationException e) {
71             SecurityContextHolder.clearContext();
72
73             log.info("Authentication request failed: {}", e.getMessage());
74
75             throw Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e).asRuntimeException();
76         }
77
78         return next.startCall(call, headers);
79     }
80
81     private String[] decodeBasicAuth(String authHeader) {
82         String basicAuth;
83         try {
84             basicAuth = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes(StandardCharsets.UTF_8)),
85                 StandardCharsets.UTF_8);
86         } catch (IllegalArgumentException | IndexOutOfBoundsException e) {
87             throw new BadCredentialsException("Failed to decode basic authentication token");
88         }
89
90         int delim = basicAuth.indexOf(':');
91         if (delim == -1) {
92             throw new BadCredentialsException("Failed to decode basic authentication token");
93         }
94
95         return new String[]{basicAuth.substring(0, delim), basicAuth.substring(delim + 1)};
96     }
97 }