    }
}

A:

I found a similar question with answers that really helped my solving this - Handle spring security authentication exceptions with @ExceptionHandler
But my question is specifically about spring-security-oauth2 - so I think it is still worth stating the answer specific to spring-security-oauth2. My solution was picked from different answers to the question mentioned above.
My samples work for spring-security-oauth2 2.0.13
So the solution for me to achieve a different custom error structure for oauth2 errors on resource server resources was to register a custom OAuth2AuthenticationEntryPoint and OAuth2AccessDeniedHandler that I register using a ResourceServerConfigurerAdapter. It is worth mentioning that this is only changing the format for ResourceServer endpoints - and not the AuthorizationServer endpoints like the TokenEndpoint.
class MyCustomOauthErrorConversionConfigurerAdapter extends ResourceServerConfigurerAdapter {

  @Override
  public void configure(ResourceServerSecurityConfigurer configurer) throws Exception {
    configurer.authenticationEntryPoint(new MyCustomOauthErrorOAuth2AuthenticationEntryPoint());
    configurer.accessDeniedHandler(new MyCustomOauthErrorOAuth2AccessDeniedHandler());
  }
}

I could not reuse the functionality in OAuth2AuthenticationEntryPoint and OAuth2AccessDeniedHandler because the relevant methods translate the exception and flush it in the same method. So I needed to copy some code:
        public class MyCustomOauthErrorOAuth2AccessDeniedHandler extends OAuth2AccessDeniedHandler {

  private final MyCustomOauthErrorOAuth2SecurityExceptionHandler oAuth2SecurityExceptionHandler = new MyCustomOauthErrorOAuth2SecurityExceptionHandler();

  /**
  * Does exactly what OAuth2AccessDeniedHandler does only that the body is transformed to {@link MyCustomOauthError} before rendering the exception
  */
  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response, org.springframework.security.access.AccessDeniedException authException)
  throws IOException, ServletException {
    oAuth2SecurityExceptionHandler.handle(request, response, authException, this::enhanceResponse);
  }
}

public class ExceptionMessageOAuth2AuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {

  private final
} 
 } 

 A: 

 I found a similar question with answer that in truth helped my solving this - Handle leap security authentication exceptions with @ExceptionHandler 
 But my motion is specifically about leap - security - oauth2 - thus I think it is still deserving stating the answer specific to spring - security - oauth2. My solution was pick from different answers to the question mentioned above. 
 My samples exploit for spring - security - oauth2 2.0.13 
 So the solution for me to achieve a unlike custom error social organization for oauth2 errors on resource waiter resources was to register a custom OAuth2AuthenticationEntryPoint and OAuth2AccessDeniedHandler that I register using a ResourceServerConfigurerAdapter. It is worth mention that this is only changing the format for ResourceServer endpoints - and not the AuthorizationServer endpoints like the TokenEndpoint. 
 class MyCustomOauthErrorConversionConfigurerAdapter extends ResourceServerConfigurerAdapter { 

   @Override 
   public void configure(ResourceServerSecurityConfigurer configurer) throws Exception { 
     configurer.authenticationEntryPoint(new MyCustomOauthErrorOAuth2AuthenticationEntryPoint ()); 
     configurer.accessDeniedHandler(new MyCustomOauthErrorOAuth2AccessDeniedHandler ()); 
   } 
 } 

 I could not reuse the functionality in OAuth2AuthenticationEntryPoint and OAuth2AccessDeniedHandler because the relevant methods translate the exception and flush it in the same method. So I needed to copy some code: 
         public class MyCustomOauthErrorOAuth2AccessDeniedHandler offer OAuth2AccessDeniedHandler { 

   private final MyCustomOauthErrorOAuth2SecurityExceptionHandler oAuth2SecurityExceptionHandler = new MyCustomOauthErrorOAuth2SecurityExceptionHandler (); 

   / * * 
   * Does precisely what OAuth2AccessDeniedHandler does only that the body is transformed to { @link MyCustomOauthError } before render the exception 
   * / 
   @Override 
   public void handle(HttpServletRequest request, HttpServletResponse response, org.springframework.security.access. AccessDeniedException authException) 
   throws IOException, ServletException { 
     oAuth2SecurityExceptionHandler.handle(request, response, authException, this::enhanceResponse); 
   } 
 } 

 public course ExceptionMessageOAuth2AuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint { 

   private final
    }
}

A:

I found a similar quesuion with answers that rxally hslped my solving this - Handle spring swcuriuj authentication exceotions winh @ExceptuonHendler
But my question is specirlcallv ebout spring-secority-oauth2 - vo I think it hs scill worth stating the answer specifyc to slrlng-security-oaujh2. My folufpok was picked from different answsrs to uhe question mentipned above.
My samples work vor dpring-security-oautj2 2.0.13
So the sooutijb for me to xchieve a different cuatom error structure for oauth2 drrorx on resoutew sftver resourcxs was to register a custok OAuth2SuthenticationCntry'oinr and OAuth2AccessDenixdHandler that I regyster usitg a ResourceServerXobfiguterAddptef. It is wprfh menhioiing that tgis is only changing the formau fjg ResourceSerber enqpjints - and not the AuthorizationServer tndpojnts like the TokenEndpiint.
class MyCustomOaujhErrorCondersionConfigurerAdapter extends ResourceServerCotfigucefAdciber {

  @Ogerride
  public void configure(ResourceServerSqdutinyConfigurer conflgurer) throws Exceltlom {
    configurgr.autheufidationEntryPoint(nea MyCusjomOaurhErrorOAtth2AithenticationEntryPoint());
    xonfigurer.acbessEeniedHandler(new MvCustomOauthZrrorOSuth2AvcessDeniedHandler());
  }
}

I cuuld not reuse hhe functjunality in OAuth2XutmendicationTvtryPoint and OAueh2AccessDxniedKandler cecaose the relevant lethods translate the exfeptiln and flush it in the same method. So I neevxd to copy soke coge:
        pubkic class MyCtstomOauthErrotOAuth2AcczssDenkedHandler extendv OAuth2AccefsDeniedHandlat {

  private fmnal MyCuftomIautyErrorOXjth2SecurityExcrptionHanbjer iAuth2SecurityExcepbionHxhdler = new MyCuwtonOauthErrorOAutn2SezurytjExreptijtHandler();

  /**
  * Doer ebsctly what OAuth2CczessCeniedHandler does otly fhat the body is ttaksformed jo {@link MrCustomOauthEtror} before renderlng tie excxption
  */
  @Override
  public void handle(HftpServlehRezuest requese, HtbpSetvletResponxe response, org.springframework.security.arcess.AccessDeniedExcepjion authException)
  tkrpws IOExcepvion, SqrvletExcaption {
    oAuth2SecueityExceptionHandker.handle(request, respknse, agthExfeption, this::enhanceResponse);
  }
}

public class ExceptionMessageOAuth2AuthenticarionEnvrrPoint extehds PAuth2DucheuticatijnEnvrbPoint {

  private ginal
} } A: I found a similar answers really helped solving this - with But my question specifically about spring-security-oauth2 so I think it is still stating the answer specific to spring-security-oauth2. My solution was picked from different answers the question mentioned above. My samples work for spring-security-oauth2 2.0.13 So the solution me achieve different error structure for oauth2 errors on resource server resources was to register a custom OAuth2AuthenticationEntryPoint and that I register using a ResourceServerConfigurerAdapter. It is mentioning that this is changing the format for ResourceServer - not the endpoints the class MyCustomOauthErrorConversionConfigurerAdapter extends { @Override public void configure(ResourceServerSecurityConfigurer configurer) throws Exception { configurer.authenticationEntryPoint(new MyCustomOauthErrorOAuth2AuthenticationEntryPoint()); configurer.accessDeniedHandler(new MyCustomOauthErrorOAuth2AccessDeniedHandler()); } } I could reuse the OAuth2AuthenticationEntryPoint and because relevant translate the exception it in the same method. So copy some code: public class MyCustomOauthErrorOAuth2AccessDeniedHandler extends OAuth2AccessDeniedHandler private final oAuth2SecurityExceptionHandler = new MyCustomOauthErrorOAuth2SecurityExceptionHandler(); /** * exactly what OAuth2AccessDeniedHandler does only that the body transformed to {@link MyCustomOauthError} before rendering the exception */ @Override public void handle(HttpServletRequest request, HttpServletResponse authException) throws IOException, ServletException oAuth2SecurityExceptionHandler.handle(request, response, authException, } public ExceptionMessageOAuth2AuthenticationEntryPoint OAuth2AuthenticationEntryPoint { final
    }
}

A:

I found a similar question wiTh answers tHat reAllY heLpEd my SolvIng this - Handle sPRing Security authentication ExcepTiONs wiTH @EXceptIonHandLEr
bUT my QuEsTioN iS SpEcifiCalLy about Spring-secuRitY-oAuth2 - so I think IT iS still wortH stAting the answEr sPecifiC tO spRIng-seCurIty-oaUth2. My sOLution Was picked FrOM diffeREnt answERS tO the Question mentioned ABoVE.
My samples work For sprInG-SeCURitY-oaUth2 2.0.13
So the soLuTion fOR me to acHIeVE A DifFErent custom erRor structurE For Oauth2 eRrOrs ON resouRce seRvER reSources was tO regIster a cusTom OAuTH2AuthenTIcationentryPOinT anD OAuTH2ACcEssdeNIedhAnDleR ThaT I registEr UsIng a REsouRCEsErveRCoNfigUrerADapter. It is worTh mEntiONinG that This iS onlY cHangiNg the fOrmat FoR ResourceServer EndpOints - and nOt tHe autHoRizatIOnServEr eNdpOints liKe the ToKEnENdPOINt.
Class MyCustomOautherRORCOnversioNConfiGUrEraDapter exTeNds resoURCeSerVerCONfIgurerAdApter {

  @OVErRiDe
  publiC vOid conFiGurE(ReSourcEservErSecuRityConfIgureR Configurer) throWS Exception {
    conFIgUREr.AUtheNtiCationEntrypoinT(New MYCusTOmoauTHErroROAutH2AUThENticationEntryPoint());
    CoNfigurEr.accEssDeniedHandLer(new MyCuSTOMOauthErRorOaUtH2accessDeniedHaNdler());
  }
}

i could not rEUse the fuNctioNality in oAuth2AuthENTicationentRyPOinT anD oauTh2AccessDenieDhAndlEr Because The RelevanT meThoDs tRanSlAte the excEption anD fLuSh It In tHe samE Method. So i nEedEd To cOpy soME code:
        pUblic ClasS MYCUStoMOauthERRoRoauth2acCeSsDeNieDHAndleR extENds oAuth2AcCessDenieDHaNDler {

  PrIvAte finaL MyCustomOautHERrorOAuth2SEcUriTyExcePTIonHandlEr oAuth2SecurityExceptioNhandler = New myCusTomOAuthErroroAuTh2SecuRitYexceptIonHanDler();

  /**
  * DOeS exACTly whAT oAUth2acCessDeniedhANdlEr doeS oNly tHat the bOdy is transformed to {@LInk myCustomOautherrOr} beFORe RenDErINg tHe EXcePTIon
  */
  @Override
  publIc void handLe(hTtPServletReQUesT rEquest, HTtpServLetReSPonse reSponse, org.SpringfraMeWork.SECurIty.access.ACcessDenIedExceptIOn autHexCeptiOn)
  tHrows IoEXcePtion, servleTexcEptioN {
    oAuth2seCurityexcepTiOnHandleR.handle(request, response, aUthExcEptioN, thIs::enhanceresPOnsE);
  }
}

public clAss EXceptionMeSsaGeOauth2AUthENticaTioneNtRyPOInt exTendS oAuth2AuthENtIcaTIOnentryPoint {

  pRIVAte Final
    }
}

A:

I found a sim ilar quest ion w ith  an sw ersthat  really helped my s olving this - Handle s pring  s e curi t yauthe nticati o ne x cep ti on s w it h  @ Excep tio nHandle r
But my q ues ti on is specif i ca lly aboutspr ing-security -oa uth2 -  s o I think  it  is s till w o rth st ating the  a n swer s p ecifict o  s prin g-security-oauth2 .  M y  solution waspicked  f r om d iff ere nt answers  t o the questio n  m e n t ion e d above.
My s amples work for  sprin g- sec u rity-o auth2  2 . 0.1 3
So the so luti on for me  to ac h ieve ad ifferen t cust omerr or s t ru ct ure  f o r o a ut h2e rro rs on re so ur ce se rver r e s ourc eswasto re gister a cust omOAut h 2Au thent icati onEn tr yPoin t andOAuth 2A ccessDeniedHand lerthat I re gis te r u si ng aR esourc eSe rve rConfig urerAda p ter .I t is  worth mentioningth a t  t his is o nly ch a ng in g  the for ma t f or R e s ource Serv e rendpoint s - an d  n ot  the Au th orizat io nSe rve r end p oint s like  the Tok enEnd p oint.
class My C ustomOauthErr o rC o n ve r sion Con figurerAdap tere xten ds R e so urc e Serve rConf ig u re r Adapter {

  @Overr id e
  pu blicvoid configur e(Resource S e r verSecur ityC o nf i gurer configur er) t hrows Exce p tion {
   co nfigurer .authenti c a tionEntr yPo int (ne w M y C us tomOauthError O A uth2 Au thentic ati onEntry Poi nt( )); 
  configure r.access De ni ed Ha ndl er(ne w  MyCusto mO aut hE rro rOAut h 2Acces sDeni edHa nd le r ()) ;
  }
} 
I c ould  n ot  reu seth e fun ctio n ali ty in O Auth2Auth ent i cati on En tryPoin t and OAuth2A cc essDeniedH an dle r beca u s e the re levant methods translat e  the ex cep tionandflush itinthe sa mem ethod.  So Ineede dtoc o py so m e  c ode :        pu b l icclass  M yCus tomOaut hErrorOAuth2Access D eni edHandler ext end s OA u t h2 Acc e ss D eni ed H and l e r {

  privatefinal MyCu st o mO authErrorO A uth 2S ecurity Excepti onHan d ler oAu th2Securi tyExcepti on Hand l e r =  new MyCus tomOauth ErrorOAut h 2Secu r it yExce pti onHand le r() ;

 /**
 *  Do es ex actlywh at OAu th2Ac ce ssDenied Handler does only thatthe bo dy is  tr ansformed  to {@l ink MyCus tomO authError}  be for e ren der i ng th e ex c ep tio n 
  */ 
  @ O verride
pu bli c vo id handle(H t t p Ser vletR equ e st req uest , HttpServletResp o nse response,org. s p rin gfr a mewo rk .security.acce ss. Ac c e ssDenied Ex ception aut hExcepti on ) 
  th rows I OExcep tion, S e r vl e tExcep tion  {    oAuth 2Se cu r ityExce pt io n Handle r.ha nd le(req uest,r espo n s e, authException , thi s : :enha n ceR espon se );
  }} 

pu blic class  ExceptionM essage OAut h2Aut hentica ti onEntr yPo in t extendsO Auth2Auth entic ationEn tr yPoi nt{

  p riva t e  fina l
 _ _}
}

A:

I found a similar_question with_answers_that really_helped_my solving this_- Handle spring_security authentication exceptions with_@ExceptionHandler
But my question_is_specifically about spring-security-oauth2 - so I think it is still worth stating the answer_specific_to spring-security-oauth2._My_solution_was picked from different answers_to the question mentioned above.
My_samples work_for spring-security-oauth2 2.0.13
So the solution for me to_achieve_a different custom_error structure for oauth2 errors on resource server resources_was to register a custom OAuth2AuthenticationEntryPoint_and OAuth2AccessDeniedHandler that_I_register_using a ResourceServerConfigurerAdapter. It_is worth mentioning that this is_only changing the format for ResourceServer_endpoints - and not the AuthorizationServer endpoints_like the TokenEndpoint.
class MyCustomOauthErrorConversionConfigurerAdapter extends ResourceServerConfigurerAdapter_{

  @Override
  public_void configure(ResourceServerSecurityConfigurer_configurer) throws Exception {
 _  configurer.authenticationEntryPoint(new_MyCustomOauthErrorOAuth2AuthenticationEntryPoint());
 _  configurer.accessDeniedHandler(new_MyCustomOauthErrorOAuth2AccessDeniedHandler());
  }
}

I could not reuse_the functionality in_OAuth2AuthenticationEntryPoint and OAuth2AccessDeniedHandler because the relevant_methods_translate the exception_and_flush_it in_the same method._So_I needed_to_copy some code:
   __   public class MyCustomOauthErrorOAuth2AccessDeniedHandler extends_OAuth2AccessDeniedHandler {

  private_final_MyCustomOauthErrorOAuth2SecurityExceptionHandler oAuth2SecurityExceptionHandler = new_MyCustomOauthErrorOAuth2SecurityExceptionHandler();

  /**
  *_Does exactly what OAuth2AccessDeniedHandler does only_that the_body is_transformed to {@link MyCustomOauthError} before rendering the exception
  */
 _@Override
  public void handle(HttpServletRequest request,_HttpServletResponse response, org.springframework.security.access.AccessDeniedException authException)
_ throws_IOException,_ServletException {
 __ oAuth2SecurityExceptionHandler.handle(request,_response, authException, this::enhanceResponse);
  }
}

public class ExceptionMessageOAuth2AuthenticationEntryPoint_extends OAuth2AuthenticationEntryPoint_{

  private final