Is there a nice and tested piece of code out there that I can use for this purpose:
get the user/pass and the address of a web service (asmx page) and check if the user/pass are valid or not.
I think I should use HTTPRequest,etc to do that but I do not have a good knowledge on that topic , causing my current method to not working properly.
If there is a good piece of code for this purpose I appreciate for pointing me to that.
Thanks
P.S: I am not using DefaultCredentials in my code. Since I want them to enter user/pass so now I need to be able to TEST their user/pass and show proper message to them if their credentials is not valid.
You can use the HttpWebRequest.Credentials Property (depends on the web service authentication) and the CredentialCache Class.
Also some code examples (from google):
Retrieving HTTP content in .NET
Combine Invoking Web Service dynamically using HttpWebRequest with .Credentials.
public bool TestCredentials(string url, string username, string password)
{
var web = new WebClient();
web.Credentials = new NetworkCredential(username,password);
try
{
web.DownloadData(url);
return true;
}
catch (WebException ex)
{
var response = (HttpWebResponse)ex.Response;
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
return false;
}
throw;
}
}
Related
Getting 401(authorised) while making web api controller call
public bool CheckCarrierSCAC(int carrierID)
{
bool carrierScacSatus = false;
carrierSCAC = new BackOfficeViewController().GetSCACCodeBYCarrierID(carrierID);
logger.LogMessage(message: string.Format("Credentials {0}{1}", ConfigurationManager.AppSettings["HermesUserName"], ConfigurationManager.AppSettings["HermesPassword"]), logDate: true);
Http.Preauthenticate = true;
string serviceUrl = string.Format("{0}/CarrierSCAC?carrier={1}", ConfigurationManager.AppSettings["GatewayInterface"], carrierSCAC);
logger.LogMessage(message: string.Format("Check Carrier SCAC Service URL {0} ", serviceUrl), logDate: true);
try
{
carrierScacSatus = Http.Get<bool>(uri: serviceUrl, cookieContainer: null, contentType: "application/json");
}
catch (Exception exception)
{
logger.LogException(exception, message: "error while check Carrier Scac =" + exception.Message);
}
return carrierScacSatus;
}
I have already used preauthentication still getting same error
Setting Http.Preauthenticate = true just tells the web request to send the Authorization header to that Uri going forward, assuming it's a pass-through to .NET's HttpWebRequest.Preauthenticate. In this case, you don't appear to actually be providing any credentials to the web request. The only case where you reference the credentials is in the logger message.
The Http.Get<T> method should allow you to provide either raw Header values (in which case you'll need to add your own Authorization header) or the credentials so that it creates the header for you. (This appears to be a library that wraps the C# WebRequest or some similar connection library, so you'll need to check it's documentation for specific details).
Every time I try to call the server, I get an error code : ErrorConnectionFailed with Connection failed. Try later. message.
I suspect that it comes from the fact that the credentials of service are empty. Although I have no idea why. If I create the credentials manually using my windows account login and password, it works fine : new WebCredentials(login, password, domain);
I have a console program that works fine (see below), but it does not on a web site.
static void Main(string[] args)
{
var service = GetContextualService(email);
EmailMessage email = EmailMessage.Bind(service, new ItemId(validEmailId));
Console.ReadKey();
}
private static ExchangeService GetContextualService(string email)
{
ExchangeService service = new ExchangeService();
// I don't even need credentials on a Console program to make it work
//service.Credentials = new WebCredentials(CredentialCache.DefaultCredentials);
//service.UseDefaultCredentials = true;
service.AutodiscoverUrl(email, RedirectionUrlValidationCallback);
return service;
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
While using on a website even with new WebCredentials(CredentialCache.DefaultCredentials);, it returns an exception. (see below)
private ExchangeService GetContextualService(string email)
{
ExchangeService service = new ExchangeService();
service.Credentials = new WebCredentials(CredentialCache.DefaultCredentials);
//service.UseDefaultCredentials = true;
service.AutodiscoverUrl(email, RedirectionUrlValidationCallback);
return service;
}
[HttpPost]
public List<InternetMessageHeader> GetMailHeader(JObject data)
{
ExchangeService service = GetContextualService(data.GetValue("email").Value<string>());
ItemId id = new ItemId(data.GetValue("mailId").Value<string>());
// EXCEPTION BELOW
EmailMessage email = EmailMessage.Bind(service, id);
return email.InternetMessageHeaders.ToList();
}
Why does any call to EWS returns me an exception ?
Why is it working fine on a console program and not on a web server ?
Any thought is welcome !
Strictly based on the code you posted, all I can say is that when you call AutoDiscoverUrl() it may not be talking to the same server that you need to talk to with EWS. Altho typically AD and EWS are on the CAS, it's possible (I think) to get an EWS URL that points to some other server. I've not been in the code in the EWS Editor in some time, but if it does not call the Managed API, it might do AD slightly differently. I'd suggest calling out the EWS URL before you try the Bind() and seeing if you can paste it into a browser. (It'll redirect you OWA, but the connection will be proven.) I'd also call out the AD URL in the redirection callback so you know who you're talking to. Sorry I can't be of more help.
I've been developing an internal ASP.NET web forms application for our business and one of the requirements is to display our Twitter feed on our portal home page to all users.
For this I've decided that it is best to use LinqToTwitter Single User Authorisation to get the statuses for everyone without them having to authenticate their own accounts.
My main problem at the minute is that when we use the auth object to get the TwitterContext, it returns with an error on the TwitterContext saying
Value cannot be null
on every internal context object.
I've gone through our twitter application settings at http://dev.twitter.com and I have our correct consumer key/token and access key/token. The permission for the application is set to Read-Only. There is no callback URL specified on the http://dev.twitter.com website as it is currently on our internal system (so it wouldn't be able to get back anyway). Is this where it is going wrong? Do I need to forward some ports and allow the callback to get through to our development machines?
Here's the code for prudence. As far as I can see, there is nothing wrong with it. I know that it is set to .FirstOrDefault, this was just for seeing whether it is actually getting anything (which it isn't).
Thanks for any help you can give! :)
private async Task GetTweets()
{
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
AccessToken = ConfigurationManager.AppSettings["accessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"],
}
};
try
{
using (TwitterContext twitterContext = new TwitterContext(auth))
{
var searchResponse = await (from c in twitterContext.Status
where c.Type == StatusType.User
&& c.ScreenName == "my_screenname"
select c).ToListAsync();
Tb_home_news.Text = searchResponse.FirstOrDefault().Text;
}
}
catch (Exception ex)
{
Tb_home_news.Text = ex.Message;
}
}
If you're creating a Web app, you do need to add a URL to your Twitter App page. It isn't used for the callback, but might help avoid 401's in the future if you're using AspNetAuthorizer.
It looks like you have a NullReferenceException somewhere. What does ex.ToString() say?
Double check CredentialStore after initialization to make sure that all 4 credentials are populated. AccessToken and AccessTokenSecret come from your Twitter app page.
Does searchResponse contain any values? Calling FirstOrDefault on an empty collection will return null.
I want to send some data to my mvc4 website from my wpf app and received data back from the website back to my wpf application. I tried to find a solution before coming here and people were saying something about a web service should be able to do that, but I dont know if i need to make a web service in my mvc4 website or if I need to make a wcf project in my wpf app.
Any guides or tutorials about this would be greatly appreciated.
EDIT:This is what I ended up with after seeing the first solution it does not work at the moment, I am not sure why im not getting a proper response back.
public bool GetData(LoginObj loginObj)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:12611/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("Home/VerifyLogin",loginObj).Result;
if (response.IsSuccessStatusCode)
{
var users = response.Content;
if (users.ToString() == "true")
return true;
else
return false;
}
return false;
}
this is in the home controller below
public class LoginObj
{
public string username { get; set; }
public string password { get; set; }
public LoginObj(string username, string password)
{
this.username = username;
this.password = password;
}
}
public JsonResult VerifyLogin(LoginObj loginObj)
{
bool isValid = true;
isValid = System.Web.Security.Membership.ValidateUser(loginObj.username, loginObj.password);
return Json(isValid,JsonRequestBehavior.AllowGet);
}
I'm not sure what you are trying to do, but normally a web application (mvc4) calls the service. Whatever to send, receive or both.
There you have your web app call the wcf requesting data and if it's changed elsewhere it will be returned from the wcf no matter what. When you need to save data you just send it to the wcf.
If you need some notification/chat-like app so a WCF can push data to your web app, seems like you are looking for SignalR.
If you can, please expand or explain better your question/need.
UPDATE:
You can create a 'web service' (wcf or webapi) or using the already mvc application and return a json response to act like a web service.
The simple you can get is something like :
A new action in your mvc app
public JsonResult CanLogin(string username, string password){
bool isValid = true; // check if username & password are ok and return True or False
return Json(isValid);
}
then on your wpf create an httpclient and call /application/CanLogin with user and password
you can allowGet on the json response for testing in your browser.
return Json(isValid, JsonRequestBehavior.AllowGet);
I'm building a simple app too that needs to access a calendar that's in my Google Apps account. But I'm having problems with authentication. I've tried the following code but it doesn't work:
Service service = new Service("<appname>");
service.setUserCredentials("<email>", "<password>");
CalendarEntry entry = (CalendarEntry)service.Get("<eventUrl>");
How do you get this to work with Google Apps? Is there any other type of authentication that I have to use for Google apps?
Update:
Unlocking the captcha solved my problem with getting the feed. Now I've hit the next wall: updating an event.
entry.Title.Text = "Foo";
entry.Update();
Gives me the GDataRequestException exception: "Can not update a read-only entry".
Im using the private calendar xml address that I got under kalendarsettings:
https://www.google.com/calendar/feeds/_%40group.calendar.google.com/private-/basic
I would recommend using Fiddler to see what http response you are getting back from Google. When I ran your code against my google apps account, I was getting back an "Error=CaptchaRequired" response. This required that I go to https://www.google.com/a/yourgoogleappdomain.com/UnlockCaptcha (replacing with your domain obviously). After I did that I was able to properly connect. You may be getting a different error code too so check for that and post it here. You could have an invalid password or invalid url or this functionality is disabled by your google apps administrator. Here is my sample code:
var calendarService = new CalendarService("company-app-version");
calendarService.setUserCredentials("<email>", "<password>");
var eventQuery = new EventQuery("http://www.google.com/calendar/feeds/user%40domain.com/private/full");
var eventFeed = calendarService.Query(eventQuery);
foreach (var atomEntry in eventFeed.Entries)
{
Console.WriteLine(atomEntry.Title.Text);
}
Make sure to replace the email, password, and email inside of the URL (url encode the # sign too).
using Google.GData.Client;
public bool ValidateGoogleAccount(string login, string password)
{
try
{
Service bloggerService = new Service("blogger", "App-Name");
bloggerService.Credentials = new GDataCredentials(login, password);
string token = bloggerService.QueryAuthenticationToken();
if (token != null)
return true;
else
return false;
}
catch (Google.GData.Client.InvalidCredentialsException)
{
return false;
}
}
Yet another solution Austin from google provides (it worked for me):
http://groups.google.com/group/google-calendar-help-dataapi/browse_thread/thread/400104713435a4b4?pli=1