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 org.springframework.http.HttpHeaders
19 import org.springframework.security.authentication.BadCredentialsException
20 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
21 import org.springframework.security.core.context.SecurityContext
22 import org.springframework.security.core.context.SecurityContextImpl
23 import org.springframework.security.web.server.context.ServerSecurityContextRepository
24 import org.springframework.stereotype.Component
25 import org.springframework.web.server.ServerWebExchange
26 import reactor.core.publisher.Mono
27 import java.nio.charset.StandardCharsets
31 class SecurityContextRepository(private val authenticationManager: AuthenticationManager)
32 : ServerSecurityContextRepository {
34 override fun save(swe: ServerWebExchange, sc: SecurityContext): Mono<Void> {
35 throw UnsupportedOperationException("Not supported.")
38 override fun load(swe: ServerWebExchange): Mono<SecurityContext> {
39 val request = swe.request
40 val authHeader = request.headers.getFirst(HttpHeaders.AUTHORIZATION)
41 if (authHeader != null && authHeader.startsWith("Basic")) {
42 val tokens = decodeBasicAuth(authHeader)
43 val username = tokens[0]
44 val password = tokens[1]
45 val auth = UsernamePasswordAuthenticationToken(username, password)
46 return this.authenticationManager!!.authenticate(auth)
47 .map { SecurityContextImpl(it) }
53 private fun decodeBasicAuth(authHeader: String): Array<String> {
56 basicAuth = String(Base64.getDecoder().decode(authHeader.substring(6).toByteArray(StandardCharsets.UTF_8)),
57 StandardCharsets.UTF_8)
58 } catch (e: IllegalArgumentException) {
59 throw BadCredentialsException("Failed to decode basic authentication token")
60 } catch (e: IndexOutOfBoundsException) {
61 throw BadCredentialsException("Failed to decode basic authentication token")
64 val delim = basicAuth.indexOf(':')
66 throw BadCredentialsException("Failed to decode basic authentication token")
69 return arrayOf(basicAuth.substring(0, delim), basicAuth.substring(delim + 1))