Property based GRPC server service.
[ccsdk/cds.git] / ms / blueprintsprocessor / application / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / security / BasicAuthServerInterceptor.kt
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 io.grpc.*
19 import org.onap.ccsdk.cds.controllerblueprints.core.logger
20 import org.springframework.security.authentication.BadCredentialsException
21 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
22 import org.springframework.security.core.AuthenticationException
23 import org.springframework.security.core.context.SecurityContextHolder
24 import org.springframework.stereotype.Component
25 import java.nio.charset.StandardCharsets
26 import java.util.*
27
28 @Component
29 class BasicAuthServerInterceptor(private val authenticationManager: AuthenticationManager)
30     : ServerInterceptor {
31
32     private val log = logger(BasicAuthServerInterceptor::class)
33
34     override fun <ReqT, RespT> interceptCall(
35             call: ServerCall<ReqT, RespT>,
36             headers: Metadata,
37             next: ServerCallHandler<ReqT, RespT>): ServerCall.Listener<ReqT> {
38         val authHeader = headers.get(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER))
39
40         if (authHeader.isNullOrEmpty()) {
41             throw Status.UNAUTHENTICATED.withDescription("Missing required authentication")
42                     .asRuntimeException()
43         }
44
45         try {
46             val tokens = decodeBasicAuth(authHeader)
47             val username = tokens[0]
48
49             log.info("Basic Authentication Authorization header found for user: {}", username)
50
51             val authRequest = UsernamePasswordAuthenticationToken(username, tokens[1])
52             val authResult = authenticationManager.authenticate(authRequest).block()
53
54             log.info("Authentication success: {}", authResult)
55
56             SecurityContextHolder.getContext().authentication = authResult
57
58         } catch (e: AuthenticationException) {
59             SecurityContextHolder.clearContext()
60
61             log.info("Authentication request failed: {}", e.message)
62
63             throw Status.UNAUTHENTICATED.withDescription(e.message).withCause(e).asRuntimeException()
64         }
65
66         return next.startCall(call, headers)
67     }
68
69     private fun decodeBasicAuth(authHeader: String): Array<String> {
70         val basicAuth: String
71         try {
72             basicAuth = String(Base64.getDecoder().decode(authHeader.substring(6).toByteArray(StandardCharsets.UTF_8)),
73                     StandardCharsets.UTF_8)
74         } catch (e: IllegalArgumentException) {
75             throw BadCredentialsException("Failed to decode basic authentication token")
76         } catch (e: IndexOutOfBoundsException) {
77             throw BadCredentialsException("Failed to decode basic authentication token")
78         }
79
80         val delim = basicAuth.indexOf(':')
81         if (delim == -1) {
82             throw BadCredentialsException("Failed to decode basic authentication token")
83         }
84
85         return arrayOf(basicAuth.substring(0, delim), basicAuth.substring(delim + 1))
86     }
87 }