How do I convert an NSHttpCookie to a System.Net.Cookie in MonoTouch? - iphone

I have a MonoTouch iPhone app that does federated sign in via the Azure Access Control Service. The login is done via an embedded UIWebView browser. When the login is done, I want to transfer the cookie into my app. I have access to the
NSHttpCookieStorage.SharedStorage.Cookies
collection, so I can find the cookie. But in order to call the back end services, I need to have a
System.Net.Cookie
that I can put into a CookieContainer to send to the service.
How do I convert between the two... is this the only way?
NSHttpCookie cookie = NSHttpCookieStorage.SharedStorage.Cookies[0];
System.Net.Cookie newCookie = new System.Net.Cookie()
{
Name = cookie.Name,
Value = cookie.Value,
Version = (int) cookie.Version,
Expires = cookie.ExpiresDate,
Domain = cookie.Domain,
Path = cookie.Path,
Port = cookie.PortList[0].ToString(), // is this correct??
Secure = cookie.IsSecure,
HttpOnly = cookie.IsHttpOnly
};

Yes, that is how you could convert. Perhaps you should just make an extension method on NSHttpCookie? Then you could call something like:
var c = cookie.ToCLRCookie ();

Related

Identity Server Not returning the Correct Access Token

I am makeing a call to identity server from angular2(java script client app), but its not returning the correct access_token, instead its returning something like
b8fee3ff98859c83e69b68376b413a542217cb9f054fc9638e885fe18650f880
Like the comments suggest, your client is returning reference tokens. If you want your client to get self contained access tokens make sure your client is of the form:
var angular_client = new Client
{
ClientId = "angular_client",
AccessTokenType = AccessTokenType.Jwt, //You probably have this set to .Reference
AccessTokenLifeTime = 3600,
AllowAccessTokensViaBrowser = true,
...
}

Fetch user email with C# Facebook SDK

I would like to fetch a user's email using the C# Facebook SDK. How can I do so? I've tried the code below, but I just get an empty email. Is it because I somehow need to ask for more rights? If so, how do I do that?
Facebook.FacebookClient fbc = new Facebook.FacebookClient(user.MobileServiceAuthenticationToken);
dynamic clientCredentials = await fbc.GetTaskAsync("oauth/access_token",
new{client_id = facebookClientId,client_secret = facebookClientSecret,
grant_type = "client_credentials",redirect_uri = "https://xxx.azure-mobile.net/signin-facebook"});
fbc.AccessToken = clientCredentials.access_token;
fbc.AppId = facebookClientId;
fbc.AppSecret = facebookClientSecret;
string id = user.UserId.Replace("Facebook:", string.Empty);
dynamic result = await fbc.GetTaskAsync(id + "?fields=id,name,picture,last_name,first_name,gender");
Best regards
TJ78
You need to gather the email permission in the login Url's scope parameter, otherwise you will not be able to receive the email field.

How to get Facebook Friend List in ASP.NET?

I'm building an App with ASP.NET MVC 5 and Identity.
So far the login is working correctly.
Here the auth:
var fb = new FacebookAuthenticationOptions();
fb.Scope.Add("email");
fb.Scope.Add("friends_about_me");
fb.Scope.Add("friends_photos");
fb.AppId = "";
fb.AppSecret = "";
fb.Provider = new FacebookAuthenticationProvider() {
OnAuthenticated = async FbContext => {
FbContext.Identity.AddClaim(
new System.Security.Claims.Claim("FacebookAccessToken", FbContext.AccessToken));
}
};
fb.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
app.UseFacebookAuthentication(fb);
I'm trying to get the friends list. I've been looking for a few examples but none is working with this version of MVC 5.
My question is. How can I fetch all the friends with this version?
I don't want to use Javascript API, I want all the code in c# and then send to the view.
I think I just need to rewrite the login and store the access token in the session, and then simply call var client = new FacebookClient(TOKEN);
So how can I rewrite the login?
You've already got everything you need. The OnAuthenticated callback you've set adds a claim containing the access token for Facebook. You just need to pull the claim for the user:
var identity = (ClaimsIdentity)User.Identity;
var facebookClaim = identity.Claims.FirstOrDefault(c => c.Type == "FacebookAccessToken");
if (facebookClaim != null)
{
// access facebook API with `facebookClaim.Value`
}
And if it exists, then you can use the Facebook API to pull in their friends by making standard HTTP calls via something like HttpClient.

Pass a ADFS token to a custom STS service

I am testing a product that authenticates uses using a custom STS service. The way it used to work is, when a user hits the website using the browser, we issue a redirect to hit the STS service. the STS service authenticates the user by hitting AD and then issues a SAML token with some custom claims for the user. The website then hits the STS once again to get a ActAs token so we can communicate with the data service.
And I had a automation that would mimic this behavior and its working fine in production.
We are not modifying the STS to use ADFS to authenticate instead of hitting the AD directly. So now when I hit the website, the request gets redirected to a ADFS endpoint which authenticates the user and issues a token. Then we hit the custom STS service that would use the token to authenticate the user (instead of hitting AD), add custom claims and issue a SAML token for the user. We then generate a ActAs token using this to finally hit the data service.
I am trying to update my automation for this changed behavior. So what I am doing now is hit the ADFS service, obtain a token and pass the token to the STS service so it can issue me a SAML token.
I am quite an amateur when it comes to windows identity service so i am having hard time trying to get this work. I have successfully obtained the token (Bearer Token) from the ADFS but i cant figureout how to pass this token to my custom STS so it can issue me a SAML token.
Any help would be highly appreciated. Thanks!
here is the code i am using
public static SecurityToken GetSecurityToken()
{
var endPoint = new EndpointAddress(new Uri(#"ADFS endpoint"));
var msgBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential, false);
msgBinding.Security.Message.EstablishSecurityContext = false;
msgBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
var factory = new WSTrustChannelFactory(msgBinding, endPoint);
factory.TrustVersion = TrustVersion.WSTrust13;
factory.Credentials.SupportInteractive = true;
factory.Credentials.UserName.UserName = "user";
factory.Credentials.UserName.Password = "pwd";
var rst = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
KeyType = KeyTypes.Bearer,
AppliesTo = new EndpointReference(#"custom STS endpoint")
};
return factory.CreateChannel().Issue(rst);
}
public static void GetUserClaimsFromSecurityTokenService(SecurityToken secToken)
{
var securityTokenManager = new SecurityTokenHandlerCollectionManager(string.Empty);
securityTokenManager[string.Empty] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
var trustChannelFactory = new WSTrustChannelFactory(Binding, new EndpointAddress("custom STS endpoint"))
{
TrustVersion = TrustVersion.WSTrust13,
SecurityTokenHandlerCollectionManager = securityTokenManager,
};
var rst = new RequestSecurityToken(RequestTypes.Issue)
{
AppliesTo = new EndpointReference("website url"),
TokenType = SamlSecurityTokenHandler.Assertion
};
var channel = (WSTrustChannel)trustChannelFactory.CreateChannel();
channel.Open(TimeSpan.FromMinutes(15));
try
{
RequestSecurityTokenResponse rstr;
SecurityToken token = channel.Issue(rst, out rstr);
var genericToken = (GenericXmlSecurityToken)token;
var req = new SamlSecurityTokenRequirement();
var handler = new SamlSecurityTokenHandler(req)
{
Configuration = new SecurityTokenHandlerConfiguration()
};
var newToken = handler.ReadToken(new XmlNodeReader(genericToken.TokenXml));
}
finally
{
channel.Close();
}
}

Reusing ClaimsPrincipal to authenticate against sharepoint online

I have an Office 365 account (using the latest SharePoint 2013 instance)
I also have a simple .net web app that is authenticating against Office 365, I created an AppPrincipalId and added it using New-MsolServicePrincipal powershell commmand.
This works correctly. I launch the app (in debug), it redirects to 365 login, I login, it comes back to the app, and I have derived a class from ClaimsAuthenticationManager and overriden the Authenticate method.
I can now see the ClaimsPrincipal, with the relevant claims and identity etc.
Now I would like to re-use this identity to programmatically access SharePoint.
My questions:
a) Will SharePoint permit this Identity (seeing that it was issued by sts.windows.net)
b) How can I reconstruct a valid JWT (or use the existing one), and encapsulate this in a HttpRequest using authentication bearer.
The code I am using is below - this is coming back 401 not authorized.
Any help would be highly appreciated.
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true)
{
List<Claim> claims = null;
claims = (from item in incomingPrincipal.Claims
where item.Type.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)
select item).ToList();
RNGCryptoServiceProvider cryptoProvider = new RNGCryptoServiceProvider();
byte[] keyForHmacSha256 = Convert.FromBase64String("Gs8Qc/mAF5seXcGHCUY/kUNELTE=");
// Create our JWT from the session security token
JWTSecurityToken jwt = new JWTSecurityToken
(
"https://sts.windows.net/myAppIdGuid/",
"00000003-0000-0ff1-ce00-000000000000", // sharepoint id
claims,
new SigningCredentials(
new InMemorySymmetricSecurityKey(keyForHmacSha256),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256"),
DateTime.UtcNow,
DateTime.UtcNow.AddHours(1)
);
var validationParameters = new TokenValidationParameters()
{
AllowedAudience = "00000003-0000-0ff1-ce00-000000000000", // sharepoint id
ValidIssuer = "https://sts.windows.net/myAppIdGuid/", // d3cbe is my app
ValidateExpiration = true,
ValidateNotBefore = true,
ValidateIssuer = true,
ValidateSignature = true,
SigningToken = new BinarySecretSecurityToken(Convert.FromBase64String("mySecretKeyFromPowerShellCommand")),
};
JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler();
var jwtOnWire = jwtHandler.WriteToken(jwt);
var claimPrincipal = jwtHandler.ValidateToken(jwtOnWire, validationParameters);
JWTSecurityToken parsedJwt = jwtHandler.ReadToken(jwtOnWire) as JWTSecurityToken;
HttpWebRequest endpointRequest =
(HttpWebRequest)HttpWebRequest.Create(
"https://MySharepointOnlineUrl/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization",
"Bearer " + parsedJwt.RawData);
HttpWebResponse endpointResponse =
(HttpWebResponse)endpointRequest.GetResponse();
}
}
If your scenario is about consuming SharePoint Online data from a remote web app, you probably want to use the OAuth flow. You can't generate the token yourself. Instead you ask for consent to the user to access certain scopes (resource + permission). These two links should help
http://msdn.microsoft.com/en-us/library/office/apps/jj687470(v=office.15).aspx
http://jomit.blogspot.com.ar/2013/03/authentication-and-authorization-with.html