001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.oauth; 003 004import jakarta.json.JsonObject; 005 006/** 007 * A generic OAuth 2.0 exception 008 * @since 18650 009 */ 010public final class OAuth20Exception extends OAuthException { 011 private static final long serialVersionUID = -203910656089454886L; 012 013 /** 014 * Invalid request types 015 */ 016 public enum Type { 017 invalid_request, 018 invalid_client, 019 invalid_grant, 020 unauthorized_client, 021 unsupported_grant_type, 022 invalid_scope, 023 unknown 024 } 025 026 private final Type type; 027 028 /** 029 * Create a new exception with a specified cause 030 * @param cause The cause leading to this exception 031 */ 032 public OAuth20Exception(Exception cause) { 033 super(cause); 034 this.type = Type.unknown; 035 } 036 037 /** 038 * Create a new exception with a given message 039 * @param message The message to use 040 */ 041 public OAuth20Exception(String message) { 042 super(message); 043 this.type = Type.unknown; 044 } 045 046 /** 047 * Create an exception from a server message 048 * @param serverMessage The server message. Should conform to 049 * <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.2.2">RFC 6747 Section 4.2.2</a>, but in JSON 050 * format. 051 */ 052 OAuth20Exception(JsonObject serverMessage) { 053 super(serverMessage != null 054 ? serverMessage.getString("error_description", serverMessage.getString("error", "Unknown error")) 055 : "Unknown error"); 056 if (serverMessage != null && serverMessage.containsKey("error")) { 057 switch (serverMessage.getString("error")) { 058 case "invalid_request": 059 case "invalid_client": 060 case "invalid_grant": 061 case "unauthorized_client": 062 case "unsupported_grant_type": 063 case "invalid_scope": 064 this.type = Type.valueOf(serverMessage.getString("error")); 065 break; 066 default: 067 this.type = Type.unknown; 068 } 069 } else { 070 this.type = Type.unknown; 071 } 072 } 073 074 @Override 075 OAuthVersion[] getOAuthVersions() { 076 return new OAuthVersion[] {OAuthVersion.OAuth20}; 077 } 078 079 @Override 080 public String getMessage() { 081 String message = super.getMessage(); 082 if (message == null) { 083 return "OAuth error " + this.type; 084 } 085 return "OAuth error " + this.type + ": " + message; 086 } 087}