GRPCCall+OAuth2.m 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #import <objc/runtime.h>
  19. #import "GRPCCall+OAuth2.h"
  20. static NSString *const kAuthorizationHeader = @"authorization";
  21. static NSString *const kBearerPrefix = @"Bearer ";
  22. static NSString *const kChallengeHeader = @"www-authenticate";
  23. @implementation GRPCCall (OAuth2)
  24. @dynamic tokenProvider;
  25. - (NSString *)oauth2AccessToken {
  26. NSString *headerValue = self.requestHeaders[kAuthorizationHeader];
  27. if ([headerValue hasPrefix:kBearerPrefix]) {
  28. return [headerValue substringFromIndex:kBearerPrefix.length];
  29. } else {
  30. return nil;
  31. }
  32. }
  33. - (void)setOauth2AccessToken:(NSString *)token {
  34. if (token) {
  35. self.requestHeaders[kAuthorizationHeader] = [kBearerPrefix stringByAppendingString:token];
  36. } else {
  37. [self.requestHeaders removeObjectForKey:kAuthorizationHeader];
  38. }
  39. }
  40. - (NSString *)oauth2ChallengeHeader {
  41. return self.responseHeaders[kChallengeHeader];
  42. }
  43. - (void)setTokenProvider:(id<GRPCAuthorizationProtocol>)tokenProvider {
  44. objc_setAssociatedObject(self, @selector(tokenProvider), tokenProvider, OBJC_ASSOCIATION_RETAIN);
  45. }
  46. - (id<GRPCAuthorizationProtocol>)tokenProvider {
  47. return objc_getAssociatedObject(self, @selector(tokenProvider));
  48. }
  49. @end