Created
September 12, 2012 18:56
-
-
Save collinvandyck/3709088 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Path("authenticate") | |
| @Produces(MediaType.APPLICATION_JSON) | |
| public class AuthResource { | |
| private final UserDAO userDAO; | |
| public AuthResource(UserDAO userDAO) { | |
| this.userDAO = userDAO; | |
| } | |
| @GET | |
| public User authenticate(@Context HttpContext context) { | |
| final String apiKey = getApiKeyFromAuthorizationHeader(context); | |
| final User user = userDAO.getUserByApiKey(apiKey); | |
| return user; | |
| } | |
| private String getApiKeyFromAuthorizationHeader(HttpContext context) { | |
| final String authorization = context.getRequest().getHeaderValue("Authorization"); | |
| if (Strings.isNullOrEmpty(authorization)) { | |
| throw new WebApplicationException(Response.status(BAD_REQUEST).entity("Missing auth header").build()); | |
| } | |
| final String[] pieces = authorization.split(" "); | |
| if (pieces.length != 2) { | |
| throw new WebApplicationException(Response.status(BAD_REQUEST).entity("Bad auth header").build()); | |
| } | |
| if ("Basic".equals(pieces[0])) { | |
| return new String(Base64.decodeBase64(pieces[1]), Charsets.UTF_8); | |
| } | |
| return pieces[1]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment