Is there any way to retrieve username from this
http://username#myapplication.com
type of address in ASP.NET MVC (optionally in ASP.NET) from current request?
You're looking for the Uri class:
var uri = new Uri(someString, UriKind.Absolute);
var user = uri.UserInfo;
If that's the guaranteed string you might try something like:
string myString = "http://username#myapplication.com";
if(myString.Contains("#"))
{
return myString.Split('#')[0].Replace("http://","");
}
Related
I am developing my Razor.Pages web application in .Net Core 3.1 and I configured the authentication using my company AD. I can use without any problem the User.Identity.Name to get the user#domain value but I need to get the full name of the person that is logged in so that I can filter some results of a query to an SQL DB based on the user's full name.
I tried googling around but didn't find anything a solution to my problem. Thanks!
After doing some digging around I finally managed to create a method that receives the User.Identity.Name of the logged in user and returns the full name.
Bellow is a snippet of the method!
public static string GetFullName(string domainName)
{
string fullName = "";
UserPrincipal principal;
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
principal = UserPrincipal.FindByIdentity(ctx, domainName);
}
if (principal != null)
fullName = $"{principal.GivenName} {principal.Surname}";
else
fullName = domainName;
return fullName;
}
I'm writing a mixed app using some MVC and some Webforms screens. I need to invoke a WebForms screen with a ReturnUrl in a hidden field. I'd like to validate the ReturnUrl before transferring back to it. MVC has an Url.IsLocalUrl function, but it doesn't seem to work on WebForm screens, so I use the UrlHelper class. But when I use it I get a NullReferenceException:
UrlHelper url = new UrlHelper();
if (url(validaddr)) <--- get NullReferenceException
{
}
Any ideas?
I use the below extension method to validate local url's in web forms. Hope this helps you too.
public static bool IsLocalURL(this string _url)
{
bool flag = false;
try
{
var url = new Uri(_url);
var ctx = HttpContext.Current;
if (url.Host.Equals(ctx.Request.Url.Host) && url.Port.Equals(ctx.Request.Url.Port))
flag = true;
}
catch { }
return flag;
}
This extension method is for string. You may create a similar for Uri class as well.
I came here trying to solve the same problem. I used RequestExtensions.IsUrlLocalToHost in System.Web.WebPages (available in nuget package Microsoft.AspNet.WebPages v3.2.6)
Doc here: https://learn.microsoft.com/en-us/dotnet/api/system.web.webpages.requestextensions.isurllocaltohost?view=aspnet-webpages-3.2
Assuming you have an HttpRequest to work with (you will probably need this anyway to compare the URL to the underlying host URL), you need to first convert your HttpRequest to HttpRequestBase:
var httpRequestBase = new HttpRequestWrapper(HttpContext.Current.Request) as HttpRequestBase;
Then you can perform:
httpRequestBase.IsUrlLocalToHost(myUrlString)
Code should be:
UrlHelper url = new UrlHelper();
if (url.IsLocalUrl(validaddr)) <--- get NullReferenceException
{
}
I am working on an authentication process for an ASP.NET web app. All my usernames follow the same template: login#domain.com. Domain is always the same.
My question is: Is there a way to add the part #domain.com automatically, so users could just type in their login in the username field?
Please, let me know if I need to provide some additional info to find the answer to this question.
Add domain name programmatically if it's not specified by users:
//var userNameWithDomain = "abc#domain.com" or "abc"; //get it from user's
//input
string[] arrUserName = userNameWithDomain.Split("#".ToCharArray());
string userName = null;
string domainName = null;
if (arrUserName.Length > 1)
{
userName = arrUserName[0];
domainName = arrUserName[1];
}
else
{
userName = userNameWithDomain;
domainName = "domain.com";
}
I am generating a URI as follows (this code is simplified and falsified):
Uri baseUri = "http://localhost/MyApp/Account/Login";
Uri fullUri = GetFullUri(baseUri, user);
GetFullUri looks like this (this is in a .NET 2 assembly):
public Uri GetFullUri(Uri baseUri, User user)
{
string token = GetTokenFromUser(user); //Implementation not important.
//Create a new URI based on the base URI, adding a query string.
return new Uri(baseUri, string.Format("?Token={0}", token));
}
Calling GetFullUri from a .NET 4 assembly, the result is correct, fullUri looks like:
http://localhost/MyApp/Account/Login?Token=ABC123
Then I called the same exact code from a .NET 2 assembly and the result is incorrect, fullUri looks like:
http://localhost/MyApp/Account/?Token=ABC123
Notice how the .NET 2 result is missing the 4th and final segment, "Login"? What's the deal with that?
Looks like a bug which was fixed in .NET 4.0. Try using the UriBuilder, which works in both:
public Uri GetFullUri(Uri baseUri, User user)
{
string token = GetTokenFromUser(user); //Implementation not important.
var builder = new UriBuilder(baseUri);
builder.Query = string.Format("Token={0}", token);
return builder.Uri;
}
Have a question I surpsisingly couldnt find an answer to when searching around.
If I request a users email from facebook like:
var scope = new List<string>();
scope.Add("email");
FbClient.RequestUserAuthorization(scope);
How do I retrieve it? I couldnt find a clear option for this in the FacebookGraph.
Near as I can tell, the FacebookGraph object that is in the examples from DotNetOpenAuth does not support changing the fields that you are receiving. However, since WebRequest that it is prompting is returning a JSON string, you can parse it yourself (or use another JSON parser). That's exactly what I did, using the NewtonSoft.Json.dll:
//as part of the uri for the webrequest, include all the fields you want to use
var request = WebRequest.Create("https://graph.facebook.com/me?fields=email,name&access_token=" + Uri.EscapeDataString(authorization.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream, true);
string MyStr = streamReader.ReadToEnd();
JObject userInfo = JObject.Parse(MyStr);
//now you can access elements via:
// (string)userInfo["name"], userInfo["email"], userInfo["id"], etc.
}
}
Note that you specify what fields you want sent back as part of the WebRequest URI. The fields that are available can be found at https://developers.facebook.com/docs/reference/api/user/
Using DNOA This answer did it for me.
Just added the following:
var scope = new List<string>();
scope.Add("email");
client.RequestUserAuthorization(scope);
and the following to the facebook graph.
[DataMember(Name = "email")]
public string EMail { get; set; }
What you wrote above appears to be requsting authorization from the user to allow your app to get email back when you query the user's object. To query the user's object you do an HTTP Get on https://graph.facebook.com/me. Try it out in the Graph API explorer tool at https://developers.facebook.com/tools/explorer