| 56 | |
| 57 | |
| 58 | Future<AuthenticationResult> JWTAuthenticatorProcess::authenticate( |
| 59 | const Request &request) |
| 60 | { |
| 61 | AuthenticationResult result; |
| 62 | |
| 63 | Option<string> header = request.headers.get("Authorization"); |
| 64 | |
| 65 | if (header.isNone()) { |
| 66 | // Requests without any authentication information shouldn't include |
| 67 | // error information (see RFC 6750, Section 3.1). |
| 68 | result.unauthorized = Unauthorized({"Bearer realm=\"" + realm_ + "\""}); |
| 69 | return result; |
| 70 | } |
| 71 | |
| 72 | const vector<string> token = strings::split(header.get(), " "); |
| 73 | |
| 74 | if (token.size() != 2) { |
| 75 | result.unauthorized = Unauthorized({ |
| 76 | "Bearer realm=\"" + realm_ + "\", " |
| 77 | "error=\"invalid_token\", " |
| 78 | "error_description=\"Malformed 'Authorization' header\""}); |
| 79 | return result; |
| 80 | } |
| 81 | |
| 82 | if (token[0] != "Bearer") { |
| 83 | result.unauthorized = Unauthorized({ |
| 84 | "Bearer realm=\"" + realm_ + "\", " |
| 85 | "error=\"invalid_token\", " |
| 86 | "error_description=\"Scheme '" + token[0] + "' unsupported\""}); |
| 87 | return result; |
| 88 | } |
| 89 | |
| 90 | const Try<JWT, JWTError> jwt = JWT::parse(token[1], secret_); |
| 91 | |
| 92 | if (jwt.isError()) { |
| 93 | switch (jwt.error().type) { |
| 94 | case JWTError::Type::INVALID_TOKEN: |
| 95 | result.unauthorized = Unauthorized({ |
| 96 | "Bearer realm=\"" + realm_ + "\", " |
| 97 | "error=\"invalid_token\", " |
| 98 | "error_description=\"Invalid JWT: " + jwt.error().message + "\""}); |
| 99 | return result; |
| 100 | |
| 101 | case JWTError::Type::UNKNOWN: |
| 102 | return Failure(jwt.error()); |
| 103 | |
| 104 | UNREACHABLE(); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | Principal principal(Option<string>::none()); |
| 109 | |
| 110 | if (jwt->payload.values.empty()) { |
| 111 | result.unauthorized = Unauthorized({ |
| 112 | "Bearer realm=\"" + realm_ + "\", " |
| 113 | "error=\"invalid_token\", " |
| 114 | "error_description=\"JWT claims missing\""}); |
| 115 | return result; |