Open Kilda Java Documentation
NorthboundBasicAuthenticationEntryPoint.java
Go to the documentation of this file.
1 /* Copyright 2017 Telstra Open Source
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package org.openkilda.northbound.utils;
17 
20 import static org.openkilda.messaging.Utils.MAPPER;
21 
24 
25 import org.springframework.http.HttpHeaders;
26 import org.springframework.http.MediaType;
27 import org.springframework.security.core.AuthenticationException;
28 import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
29 import org.springframework.stereotype.Component;
30 
31 import java.io.IOException;
32 import java.util.Optional;
33 import javax.servlet.ServletException;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36 
40 @Component
41 public class NorthboundBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
45  private static final String DEFAULT_REALM = "Kilda";
46 
51  setRealmName(DEFAULT_REALM);
52  }
53 
57  @Override
58  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
59  throws IOException, ServletException {
60  String realm = String.format("Basic realm=%s", getRealmName());
61  response.addHeader(HttpHeaders.WWW_AUTHENTICATE, realm);
62  response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
63  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
64 
65  String correlationId = Optional.ofNullable(request.getHeader(CORRELATION_ID)).orElse(DEFAULT_CORRELATION_ID);
66  MessageError error = new MessageError(correlationId, System.currentTimeMillis(),
67  ErrorType.AUTH_FAILED.toString(), DEFAULT_REALM, exception.getClass().getSimpleName());
68  response.getWriter().print(MAPPER.writeValueAsString(error));
69  }
70 }
NorthboundBasicAuthenticationEntryPoint()
static final ObjectMapper MAPPER
Definition: Utils.java:31
void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
static final String DEFAULT_CORRELATION_ID
Definition: Utils.java:69
static final String CORRELATION_ID
Definition: Utils.java:43