|
| 1 | +/** |
| 2 | + * Copyright 2015 Google Inc. All Rights Reserved. |
| 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 | + |
| 17 | +package com.example.managedvms.endpoints; |
| 18 | + |
| 19 | +import java.io.IOException; |
| 20 | +import java.io.PrintWriter; |
| 21 | +import java.util.Base64; |
| 22 | + |
| 23 | +import javax.servlet.annotation.WebServlet; |
| 24 | +import javax.servlet.http.HttpServlet; |
| 25 | +import javax.servlet.http.HttpServletRequest; |
| 26 | +import javax.servlet.http.HttpServletResponse; |
| 27 | + |
| 28 | +import com.google.gson.Gson; |
| 29 | +import com.google.gson.JsonObject; |
| 30 | + |
| 31 | +/** |
| 32 | + * A servlet that returns authentication information. |
| 33 | + * See swagger.yaml for authentication mechanisms (e.g. JWT tokens, Google ID token). |
| 34 | + */ |
| 35 | +@WebServlet("/auth/info/*") |
| 36 | +public class AuthInfoServlet extends HttpServlet { |
| 37 | + |
| 38 | + @Override |
| 39 | + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { |
| 40 | + String encodedInfo = req.getHeader("X-Endpoint-API-UserInfo"); |
| 41 | + if (encodedInfo == null || encodedInfo == "") { |
| 42 | + JsonObject anon = new JsonObject(); |
| 43 | + anon.addProperty("id", "anonymous"); |
| 44 | + new Gson().toJson(anon, resp.getWriter()); |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + try { |
| 49 | + byte[] authInfo = Base64.getDecoder().decode(encodedInfo); |
| 50 | + resp.getOutputStream().write(authInfo); |
| 51 | + } catch (IllegalArgumentException iae) { |
| 52 | + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); |
| 53 | + JsonObject error = new JsonObject(); |
| 54 | + error.addProperty("code", HttpServletResponse.SC_BAD_REQUEST); |
| 55 | + error.addProperty("message", "Could not decode auth info."); |
| 56 | + new Gson().toJson(error, resp.getWriter()); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments