How to set up identity emails for SendGrid for ASP.NET 4.6.1 - sendgrid

SendGrid advises using its Version 6.3, but that only supports .NET 4.5 ; My app is 4.6.1 and is serving on an Azure app service.
I want to try to send smtp through SendGrid and see only this page for documentation. It does not show how to write the message in the IdentityConfig class and it does not say how/where to reference the SendGrid apikey via Azure's Environment Variable storage https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/csharp.html#-Using-NETs-Builtin-SMTP-Library.
I'd really appreciate some help on this.

I looked again at the SendGrid documentation and saw that the updates in late 2017 didn't say that the api only targeted 4.5.*, so decided to try the most recent version, 9.8 .
It worked with the Register Post method out of the box, simply adding a redirect to a "confirmationsent" view.
Here's the code that works for me:
public Task SendAsync(IdentityMessage message)
{
return configSendGridasync(message);
}
private async Task configSendGridasync(IdentityMessage message)
{
var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage();
msg.AddTo(message.Destination);
msg.From = new EmailAddress("info#XXX.org", "Website Name");
msg.Subject = message.Subject;
msg.PlainTextContent = message.Body;
msg.HtmlContent = message.Body;
var response = await client.SendEmailAsync(msg);
}
}

Related

ADFS single sign on for logged on user not working

I am trying to integrate our application a regular .net desktop service that runs in the user context with ADFS, and a Web API. The user is a domain user and this is a regular AD environment. The MVC aspect of the website are working well with the browser.
I am on ADAL3(VS2017), windows server 2016, I referred this link [ADFS SSO CloudIdentity] am able to use UserCredentialPassword to get a token successfully and call into my Web API, I just followed the steps and changed things to async.
However using the logged on credential bit where a new UserCredential() should indicate to call to get the token from current thread doesn't work at all for me, on ADAL 2, I am getting null pointer exception and on ADAL3 I get
MSIS7065: There are no registered protocol handlers on path /adfs/oauth2/token to process the incoming request.
I did see a similar query on SO but based on my understanding the OP there is falling back on browser based behaviour.
Falling back at browser based auth (with Promptbehaviour.never) based behaviour is undesired because I have seen a lot of config issues on customer site where even with the relevant settings enabled the browser was assuming it to be an internet site and logging in fails.
Code for reference
string authority = "https://adfs.domain.com/adfs";
string resourceURI = "https://local.ip:44325";
string clientID = "19cda707-b1bf-48a1-b4ac-a7df00e1a689";
AuthenticationContext ac = new AuthenticationContext(authority, false);
// I expect that the user's credential are picked up here.
AuthenticationResult authResult =
await ac.AcquireTokenAsync(resourceURI, clientID,
new UserCredential());
string authHeader = authResult.CreateAuthorizationHeader();
var client = new HttpClient();
var request = new HttpRequestMessage( HttpMethod.Get,
"https://local.ip:44325/api/values");
request.Headers.TryAddWithoutValidation( "Authorization", authHeader);
var response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
The call fails in acquiretokenasync.
Have you violated any of the constraints described here?
Also, similar question here around ADAL V3.0 and UserCredential support.
In the link above, the RP was created using PowerShell. Are you sure that you have properly configured an application in ADFS 4.0 - clientID etc.

Facebook OAuth stopped working suddenly

I noticed yesterday that my Facebook login for my website has stopped working.
This has been working great for the last 2 months, as far as I am aware I have not changed anything. I have tried everything I can on links such as: - as well as many more...
ASP.NET MVC5 OWIN Facebook authentication suddenly not working
I have noticed that the Stack Overflow Facebook auth has also stopped working.
Has anyone else noticed this and found any solution? It's worth noting I am using azure app services to host. But this issue is also found when I am using localhost.
My current setup looks like this...
in Startup.Auth.cs
var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
{
AppId = "xxxxxxxxxxxxx",
AppSecret = "xxxxxxxxxxxx"
};
facebookOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookOptions);
In the following method, loginInfo is null every time.
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
I also added a session "WAKEUP" from a different post suggestion, fb auth failed once before and this fixed the issue this time, but it has come back.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
Session["WAKEUP"] = "NOW!";
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
As RockSheep explained. Facebook dropped the support vor API v2.2. You need to update your OWIN nuget packages.
You can find the issue on github (from the Katanaproject).
Ensure to activate pre releases in your nuget manager, than you are able to update the nuget packages to version v3.1.0-rc1. But beware: After the update, you need to test your login carefully (maybe you also have other authentication providers like Microsoft or Google, you should test them as well).
Technical
The Api changed the version number to v2.8 and the return value from the API is now in JSON-Format and no longer escaped in the URI. The 'old' OWIN packages can not handle this changes.
[Oauth Access Token] Format - The response format of
https://www.facebook.com/v2.3/oauth/access_token returned when you
exchange a code for an access_token now return valid JSON instead of
being URL encoded. The new format of this response is {"access_token":
{TOKEN}, "token_type":{TYPE}, "expires_in":{TIME}}. We made this
update to be compliant with section 5.1 of RFC 6749.
Here you can find the code-changes on GitHub for further informations and better understanding.
A lot of people started having trouble after yesterday. This is due to Facebook dropping support for v2.2 of their API. For some reason their system still redirects auth calls that don't use a version number to the 2.2 API. A quickfix is to ensure that the API version gets sent with the API call.
Starting at v2.3 Facebook also started returning JSON objects. So make sure to change that in the code as well.
I had the same issue, found solution here Fix facebook oauth 2017
Basically, you need to extend HttpClientHandler and decode JSON response instead of body
Here is a solution for those who are using scribe java.
public Token extract(String response)
{
Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
JSONObject obj = new JSONObject(response);
return new Token(obj.get("access_token").toString(), EMPTY_SECRET, response);
}
Create a new class and set the extractor to JSON.
import org.scribe.builder.api.DefaultApi20;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.OAuthConfig;
public class FaceFmApi extends DefaultApi20 {
#Override
public String getAccessTokenEndpoint()
{
return "https://graph.facebook.com/oauth/access_token";
}
#Override
public AccessTokenExtractor getAccessTokenExtractor()
{
return new JsonTokenExtractor();
}
#Override
public String getAuthorizationUrl(OAuthConfig config) {
return null;
}
}
and inject your newly created class as below. Then getAccessToken() will work as expected.
public OAuthService getService() {
return new ServiceBuilder().provider(FaceFmApi.class)
.apiKey(config.getApiKey()).apiSecret(config.getApiSecret())
.callback(config.getCallback()).build();
}

EWS from WebSite using user credentials and windows authentication for intranet

I am trying to understand how I should configure a web site (ASP.Net) that need to pass the user credential and get some mail things
I get different kind of errors depending on the app pool configure,
What is the complete way to do it? I mean code + Configuration ;o)
I don't want to write the user and password but get them through the windows authentication
Thanks
code:
Service = new ExchangeService(ExchangeVersion.Exchange2010_SP2)
{
Url =
new Uri(
"https://xxx/yyy.asmx"),
//UseDefaultCredentials = true doesnt help
};
var view = new ItemView(1820);
// Find the first email message in the Inbox that has attachments. This results
FindItemsResults<Item> results = Service.FindItems(folderName, view);
//Here I get the error 401
Take a look at Get started with EWS Managed API client applications, it covers the basics to get you up and rolling. Note that when you use UseDefaultCredentials, you have to be on a domain joined machine, with the user logged in, and you must be targeting an on-prem server. We tested that scenario out and the following code works in that scenario.
using System;
using Microsoft.Exchange.WebServices.Data;
namespace HelloWorld
{
class Program
{
static void Main()
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.UseDefaultCredentials = true;
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
//Replace the URL below with your own, but using AutoDiscover is recommended instead
service.Url = new Uri("https://computer.domain.contoso.com/EWS/Exchange.asmx");
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox,
new ItemView(1));
}
}
}
If that doesn't work for you, then you might want to try using impersonation. See this thread, where I think they've got a similar situation . More information about impersonation is on MSDN: Impersonation and EWS in Exchange.

Using GoogleAnalytics with a Service Account

I'm trying to use the Google.Apis.Analytics.v3 client Library to retrieve metrics and I would like to work with a Service Account.
According to the documentation and several questions here on StackOverflow, I assume this should work. I have already used Service Accounts in the past against the Google BigQuery and Google Cloud Storage APIs, so I thought I could make it to work quite easily.
Unfortunately, each time I perform an operation against Google Analytics, I receive the following error:
TokenResponseException:
Additional information: Error:"invalid_grant", Description:"", Uri:""
For the record, here what I have done:
Created a brand new project in Google Developer Console.
Enabled Google Analytics API.
Create a "Service Account" Client ID.
Take note the "Client ID" the certificate and its password.
Add the Service Account "Email address" as a user with full permission on Google Analytics Account.
Here is the code I'm using to connect to Google Analytics:
private static AnalyticsService ConnectServiceAccount()
{
const string serviceAccountId = "xxxxxxxxxx-xxxxxxxxxxxx.apps.googleusercontent.com";
const string serviceAccountCertificate = "xxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12";
const string applicationName = "";
var certificate = GetServiceAccountCertificate(serviceAccountCertificate);
var credentials = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountId)
{
Scopes = new[] {
AnalyticsService.Scope.Analytics,
AnalyticsService.Scope.AnalyticsEdit,
AnalyticsService.Scope.AnalyticsManageUsers,
AnalyticsService.Scope.AnalyticsProvision,
AnalyticsService.Scope.AnalyticsReadonly
},
}.FromCertificate(certificate)
);
var service =
new AnalyticsService(
new BaseClientService.Initializer
{
GZipEnabled = true,
HttpClientInitializer = credentials,
});
return service;
}
Can someone help me troubleshoot this issue?
You can find the solution here
The service account is an email address which is like #developer.gserviceaccount.com
Looks like you are using the wrong serviceAccountID. It should be the one ending in #developer.gserviceaccount.com
And, you only need to give that email Read and Analyze rights not full control in your analytics account.
I also thought it needed an applicationName. This is the app name in your GA console.

Unable to send push notification from server

I am working on an iPhone app which is using push notifications from a asp.net backend. I have used moon apns to send notifications. I was able to send the notifications when I executed the code on localhost but when I try to run the same code on server it doesn't send notifications.
I am using following code to send the notifications:
string message = string.Format("{0} has sent you a text chirp", username);
var payload1 = new NotificationPayload(token, message, int.Parse(badgeNumber), "default");
payload1.AddCustom("MessageType", "MessageTypeText");
payload1.AddCustom("Sender", toFbID);
payload1.AddCustom("AlertMessage", message);
payload1.AddCustom("MessageID", msgid);
var p = new List<NotificationPayload> { payload1 };
var push = new PushNotification(true, "aps_development.p12", "chrip");
var rejected = push.SendToApple(p);
foreach (var item in rejected)
{
contxt.Response.Write(item);
}
Edit
Just updated path of .p12 key, also the key is within the folder where the .net files are.
Try checking out PushSharp. https://github.com/Redth/PushSharp
There's a wiki article on how to properly setup for sending push notifications, and of course the library itself makes it all easier too :)