Swift:未设置请求授权标头
Posted
技术标签:
【中文标题】Swift:未设置请求授权标头【英文标题】:Swift: Request authorization header is not set 【发布时间】:2018-11-03 10:14:52 【问题描述】:我有一个 sylius API 的请求端点,当我通过邮递员设置带有 application/json
的内容类型标头和带有 精确值 Bearer SampleToken
的 Bearer SampleToken
标头时,它响应良好有预期的响应,但是当我尝试通过URLRequest
设置请求授权标头时,它给了我一个响应
error = "access_denied";
"error_description" = "OAuth2 authentication required";
当我通过 charles 监控请求时,我注意到 Authorization
标头已被剥离。我尝试了许多不同的方法来设置授权标头,但没有成功。
func getTotalProducts(page:String)
let urlPath="https://demo.sylius.com/api/v2/products"
var request = URLRequest(url: NSURL(string: urlPath)! as URL)
request.httpMethod = "GET"
request.setValue("Bearer SampleToken", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(request)
.responseJSON response in
switch(response.result)
case .success(let value):
print(value)
break
case .failure(let error):
print("something went wrong \(error.localizedDescription)")
.session.finishTasksAndInvalidate()
原始邮递员请求:
【问题讨论】:
你会展示邮递员的形象吗? @wings 确定我已经更新了帖子并附上了邮递员请求的屏幕截图 尝试单独传递标头,请参阅:grokswift.com/custom-headers-alamofire4-swift3 您会在您的应用中添加应用传输安全设置吗?<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <string>YES</string> <key>NSExceptionDomains</key> <dict> <key>demo.sylius.com</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <false/> <key>NSIncludesSubdomains</key> <true/> </dict> </dict> </dict>
@wings 他们已经存在于应用中
【参考方案1】:
尝试改变
request.setValue("Bearer SampleToken", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
到
request.allHTTPHeaderFields = [
"Authorization": "Bearer SampleToken",
"Content-Type": "application/json"
]
【讨论】:
【参考方案2】:您的授权令牌应该是 user:password
的 base64 编码字符串
request.setValue("Bearer base64EncodedString", forHTTPHeaderField: "Authorization")
【讨论】:
以上是关于Swift:未设置请求授权标头的主要内容,如果未能解决你的问题,请参考以下文章
simple-auth-token JWT 授权未设置授权标头