gpt4 book ai didi

ios - 在 Web 请求中附加附加信息以进行身份​​验证

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:01 24 4
gpt4 key购买 nike

我正在为 OAuth 2.0 实现我自己的身份验证框架。据我了解,如果 token 已过期,服务器将发送 401。

我实现了 NSURLConnection 的委托(delegate)

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

捕获这些错误并刷新 token 。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
// refresh token and send it to server

if ([challenge previousFailureCount] > 0) {
// do something may be alert message
}
else
{
//refreshToken
}
}

但似乎我无法将 token 附加到 url。

最佳答案

你不能 - 更改 url 意味着新请求。当前请求正在进行中,并且是针对此 URL。

一种直接的方法是在 url 连接本身周围有一个“包装对象”,如果第一次失败,它可以透明地执行第二次请求

例如伪代码

@interface MyConnection
- loadRequest:(NSURLRequest*)r completionHandler:handler //not fully felshed out for this example
@end

@implementation MyConnection

- loadRequest:(NSURLRequest*)r completionHandler:handler //not fully felshed out for this example
{
[NSURLConnection sendRequest:r completion:{
if(response.status == 401)
{
NSMutableURLRequest *r2 = [NSMutableURLRequest requestWithURL:r.URL + token];
//refresh by sending a new request r2
[NSURLConnection sendRequest:r2 completion:{
handler(response);
}];
}
else {
handler(response);
}
}];
}
@end

关于ios - 在 Web 请求中附加附加信息以进行身份​​验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24018283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com