http - UIWebView 和 HTTP Basic Auth 的问题

标签 http uiwebview authorization

我在网上搜索了如何在 uiwebview 中进行基本的 http 身份验证。我已经尝试了所有方法,但无论我做什么,结果都不一致。有时 auth 有效,有时无效。这让我难以自拔,我希望得到一些帮助!

这是相关代码。我总是遇到身份验证挑战,但 webview 并不总是加载(我基本上超时等待 webViewDidFinishLoad - 没有错误)。有什么想法吗?

/*
 Load a webview
*/
- (void)loadWebView
{
    NSLog(@"loading webview");
    if( _webView == NULL ){
        // UIWebView initialization
        _webView = [[UIWebView alloc] init];
        _webView.hidden = TRUE;
    }

    // set up webview request
    NSURL *url = [NSURL URLWithString:BASE_URL];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:30];

    // load the request
    [_webView setDelegate:self];
    [_webView loadRequest:request];

    // add ourselves as delegate to connection events so we can authenticate
    (void)[NSURLConnection connectionWithRequest:request delegate:self];
}


/**
 authenticates against HTTP basic authorization
 */
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    //receive a authenticate and challenge with the user credential
    NSLog(@"got auth challenge.  Authenticating...");
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic] &&
        [challenge previousFailureCount] == 0)
    {
        NSURLCredential *credentail = [NSURLCredential
                                       credentialWithUser:AUTH_USERNAME
                                       password:AUTH_PASS
                                       persistence:NSURLCredentialPersistenceForSession];


        [[challenge sender] useCredential:credentail forAuthenticationChallenge:challenge];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error Message" message:@"Invalid credentails" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

/**
 store auth credentials
 */
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
{
    NSLog(@"using credential storage");
    return YES;
}

最佳答案

你可以在url而不是请求头中传递认证 请尝试代替 BASE_URL:

NSString* urlString = [NSString stringWithFormat:@"%@//%@:%@@%@",@"http:",userName,password,myUrl]

关于http - UIWebView 和 HTTP Basic Auth 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017321/

相关文章:

django - 如何向所有 Django 响应添加 HTTP header

java - 400 - 错误的请求 - 请求在语法上不正确

javascript - 如何伪造 UIWebViewNavigationTypeLinkClicked 为 UIWebVIew

JSF:认证和授权,最好的前进方式

java - 为什么这个线程池不同时执行HTTP请求?

objective-c - UIWebView 功能

iphone - 以编程方式在 contenteditable UIWebView 中显示键盘

c# - 从 ASP.NET Core 1.1 MVC 迁移到 2.0 后自定义 cookie 身份验证不起作用

javascript - 在 OpenAPI (Swagger) 中使用 HMAC-SHA256 身份验证测试 API 路由

http - yum 安装遇到 HTTP 403 错误?