Merge "Move web security configuration to application module"
[cps.git] / cps-application / src / test / groovy / org / onap / cps / rest / controller / ControllerSecuritySpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Pantheon.tech
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        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.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.onap.cps.rest.controller
21
22 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
23
24 import org.springframework.beans.factory.annotation.Autowired
25 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
26 import org.springframework.http.HttpStatus
27 import org.springframework.test.web.servlet.MockMvc
28 import spock.lang.Specification
29
30 @WebMvcTest(controllers = TestController.class)
31 class ControllerSecuritySpec extends Specification {
32
33     @Autowired
34     MockMvc mvc
35
36     def testEndpoint = '/test'
37
38     def 'Get request with authentication'() {
39         when: 'request is sent with authentication'
40             def response = mvc.perform(
41                     get(testEndpoint).header("Authorization", 'Basic Y3BzdXNlcjpjcHNyMGNrcyE=')
42             ).andReturn().response
43         then: 'HTTP OK status code is returned'
44             assert response.status == HttpStatus.OK.value()
45     }
46
47     def 'Get request without authentication is not authorized'() {
48         when: 'request is sent without authentication'
49             def response = mvc.perform(get(testEndpoint)).andReturn().response
50         then: 'HTTP Unauthorized status code is returned'
51             assert response.status == HttpStatus.UNAUTHORIZED.value()
52     }
53
54     def 'Get request with invalid authentication is not authorized'() {
55         when: 'request is sent with invalid authentication'
56             def response = mvc.perform(
57                     get(testEndpoint).header("Authorization", 'Basic invalid auth')
58             ).andReturn().response
59         then: 'HTTP Unauthorized status code is returned'
60             assert response.status == HttpStatus.UNAUTHORIZED.value()
61     }
62 }