I am getting bad access error when doing this. The third line throws the error. Why?
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Signup" bundle:nil];
AddFriendsTableViewController * svc =[sb instantiateViewControllerWithIdentifier:#"addFriendsController"];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self];
Related
I just want to get Error Message.
But application show It needs basic login.
How can I pass it?
AccountServiceController
[Authorize]
[Route("UserRoles")]
public async Task<IHttpActionResult> GetUserRoles(string userName){
//my code
}
Strat.Auth
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
ExpireTimeSpan = System.TimeSpan.FromDays(1)
});
var OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
Provider = new DrDB.Identity.Infrastructure.SimpleAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
You're going about this the wrong way.
The WebAPI shouldn't be displaying the logon prompt - the calling application should.
If you check the response that the WebAPI is returning, it's likely a 401 (unauthorized).
The caller can check for a 401 response, and display whatever login page it needs to.
I've scoured the web on how to do basic http auth in a uiwebview. I've tried it all and am getting inconsistent results no matter what I do. Sometimes auth works, sometimes it doesn't. It's driving me up the wall and I'd love some help!
Here's the relevant code. I always get an auth challenge, but the webview doesn't always load (I basically time out waiting for webViewDidFinishLoad - no errors). Any ideas?
/*
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;
}
You can pass authentication in url instead of request header
please try instead of BASE_URL:
NSString* urlString = [NSString stringWithFormat:#"%#//%#:%##%#",#"http:",userName,password,myUrl]
I call a web service with the HTTPS scheme. To access to web service I need a username and password. I implemented the http basic authentication.
I always get the 401 error and I am sure that username and password are correct. Here is the code I used (I saw this code here: How can I pass credentials while using NSURLSession). Suggestions? Thank you!
NSURL *url = [NSURL URLWithString:#"http://myurl...."];
NSString *user = #"userna,e";
NSString *password = #"password";
NSURLCredential *defaultCredential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistencePermanent];
NSString *host = [url host];
NSInteger port = [[url port] integerValue];
NSString *protocol = [url scheme];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
NSURLCredentialStorage *credentials = [NSURLCredentialStorage sharedCredentialStorage];
[credentials setDefaultCredential:defaultCredential forProtectionSpace:protectionSpace];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setURLCredentialStorage:credentials];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
NSLog(#"%d", httpResp.statusCode);
}
}] resume];
...
// ONLY FOR SELF-SIGNED CERTIFICATE!!! DANGEROUS!!
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
For basic auth I didn't manage to getting working with the way the docs described but I could just do exactly what the docs say not to do and set the header directly on the session.
This is the Swift version.
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfig.HTTPAdditionalHeaders = ["Authorization":"Basic fjdslkfsdfk="]
I think you can also set them directly on the request. Obj-C equivalent is left as an exercise for the reader.
There is a good blog post here that explains how the credential delegate should be used.
I am working on an app that needs to share data with a windows server. I have looked at a number of examples on the web and come up with the implementation listed below. While the iOS code and the web-service work fine independently, I don't know how to connect them together. All the examples I have seen don't show the URL of the web-service (or at least not in a manner that allows me to figure out what is going on). Please look at the value I have for ServerURL and suggest what it should be. I believe it should have the name of the entry point "doSomething" included somewhere, but I don't know what the syntax should look like. I have tried http://texas/WebSite3/Service.asmx/doSomething and http://texas/WebSite3/Service.asmx?op=doSomething but neither seems to work. Please let me know if there is any other issue present.
I assume that once I get it to work on my local system I can replace Texas with a full domain name.
Here is the iOS code:
-(void)checkWithServer {
// Create the POST request payload.
NSDictionary *tmp = [[NSDictionary alloc]initWithObjectsAndKeys:
#"test#gmail.com", #"email",
#"John Doe", #"name",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
NSString *serverURL = #"http://texas/WebSite3/Service.asmx";
// Create the POST request to the server.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverURL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [postdata length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postdata];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
}
Here is the webservice that it talks to:
[WebService(Namespace = "http://texas/WebSite3")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string doSomething(string msg)
{
byte[] buffer = GetBytes(msg);
XmlReader reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(buffer, System.Xml.XmlDictionaryReaderQuotas.Max);
XElement root = XElement.Load(reader);
string result = "{\"result\":\"none\"}";
return result;
}
With Axeva's help this is what I came up with.
iOS code:
-(void)checkWithServer {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURL *postURL = [NSURL URLWithString: #"http://texas/WebSite3/Service.asmx/doSomething"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"test#gmail.com", #"email",
#"John Doe", #"name",
nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/json" forHTTPHeaderField: #"Accept"];
[request setValue: #"application/json; charset=utf-8" forHTTPHeaderField: #"content-type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
} else {
// Handle the success
}
}
];
}
Web-server code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;
[WebService(Namespace = "http://texas/WebSite3")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string doSomething(string email, string name)
{
return "{\"name\": \"" + name + "\", \"email\": \"" + email + "\"}";
}
}
Apparently the web-server is smart enough to pull the JSON apart and assign the variables name and email.
I don't believe there's any magic with the .NET causing the issues. Just try something like this:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURL *postURL = [NSURL URLWithString: #"http://texas/WebSite3/Service.asmx/doSomething"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"test#gmail.com", #"email",
#"John Doe", #"name",
nil];
NSString *postValues = [jsonDict urlEncodedString];
NSData *jsonData = [postValues dataUsingEncoding: NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/json" forHTTPHeaderField: #"Accept"];
// [request setValue: #"application/json" forHTTPHeaderField: #"content-type"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField: #"content-type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
} else {
// Handle the success
}
}
];
I have a web application that is protected using ADFS, this was previously NTLM. We used to be able to retrieve data using the ASIHTTPRequest classes, but it does not appear to work with ADFS. The response is a redirect to the login url.
Is this the correct method of connecting from iOS to a ADFS protected URL?
NSURL *url = [NSURL URLWithString:#"https://URL_TO_WCF_SERVICE"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addRequestHeader:#"Authorization" value:[NSString stringWithFormat:#"Basic %#",[ASIHTTPRequest base64forData:[[NSString stringWithFormat:#"%#:%#",userName, password] dataUsingEncoding:NSUTF8StringEncoding]]]];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"%#", response);
}
It might be related to Extended Protection. See NTLM authentication to AD FS for non-IE browser without 'Extended Protection' switched off? for more info.
HTH!