oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java
@Override
	public void handle(
			HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException)
			throws IOException, ServletException {

		Map<String, String> parameters = new LinkedHashMap<>();

		if (this.realmName != null) {
			parameters.put("realm", this.realmName);
		}

		if (request.getUserPrincipal() instanceof AbstractOAuth2TokenAuthenticationToken) {
			AbstractOAuth2TokenAuthenticationToken token =
					(AbstractOAuth2TokenAuthenticationToken) request.getUserPrincipal();

			String scope = getScope(token);

			parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE);
			parameters.put("error_description",
					String.format("The token provided has insufficient scope [%s] for this request", scope));
			parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1");

			if (StringUtils.hasText(scope)) {
				parameters.put("scope", scope);
			}
		}

		String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters);

		response.addHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate);
		response.setStatus(HttpStatus.FORBIDDEN.value());
	}
@Override
	public void handle(
			HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException)
			throws IOException, ServletException {

		Map<String, String> parameters = new LinkedHashMap<>();

		if (this.realmName != null) {
			parameters.put("realm", this.realmName);
		}

		if (request.getUserPrincipal() instanceof AbstractOAuth2TokenAuthenticationToken) {
			AbstractOAuth2TokenAuthenticationToken token =
					(AbstractOAuth2TokenAuthenticationToken) request.getUserPrincipal();

			String scope = getScope(token);

			parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE);
			parameters.put("error_description",
					String.format("The token provided has insufficient scope [%s] for this request", scope));
			parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1");

			if (StringUtils.hasText(scope)) {
				parameters.put("scope", scope);
			}
		}

		String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters);

		response.addHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate);
		response.setStatus(HttpStatus.FORBIDDEN.value());
	}
Collect error details from the provided parameters and format according to
RFC 6750, specifically {@code error}, {@code error_description}, {@code error_uri}, and {@scope scope}.

@param request that resulted in an <code>AccessDeniedException</code>
@param response so that the user agent can be advised of the failure
@param accessDeniedException that caused the invocation