Braintree: Generate Client Token in ASP.NET MVC 4.5 - c#

I'm having some issues integrating Braintree, as well as understanding the concept of how the transaction takes place.
Here's how i currently understand Braintree:
Server Generates ClientToken -> Integrates into html/js -> User receives payment form and sends data to Braintree -> Nonce is sent to Server -> Server sends Transaction to Braintree
Is this correct?
I'm currently on step 1, trying to generate a client token, and i'm getting a NullReferenceException:
public ActionResult Payment(EditContainerViewModel newEdit)
{
//generate client token
newEdit.PaymentInfo.ClientToken = PaymentConstants.Gateway.ClientToken.generate();
return View(newEdit);
}
And heres the Gateway declaration:
public static class PaymentConstants
{
public static BraintreeGateway Gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "id",
PublicKey = "publickey",
PrivateKey = "privatekey"
};
}
Heres my view:
#model Sandbox.Models.EditContainerViewModel
<h2>Payment</h2>
<form id="checkout" method="post" action="/checkout">
<div id="payment-form"></div>
<input type="submit" value="Pay $10">
</form>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
// We generated a client token for you so you can test out this code
// immediately. In a production-ready integration, you will need to
// generate a client token on your server (see section below).
var clientToken = "#Html.Raw(Model.PaymentInfo.ClientToken)";
braintree.setup(clientToken, "dropin", {
container: "payment-form"
});
</script>
I'd really appreciate any insight on this topic, especially as i found that the provided ASP.NET examples didn't show the token generation stage.
Thank you!

As said in the comment, i was far too focused on Braintree that i made an extremely beginner error. This serves as a great reminder that you can find the answer by just taking a step back and looking at the error from a new perspective. :)

Related

Braintree - Retrieve Payment Method Nonce in Xamarin Forms C#

I'm writing an app written in C# - Xamarin Forms.
I'm simply trying to get a response from Braintree's server so I can process payment.
This response is the payment_method_nonce which is required to process payment.
Here's the client side code provided by Braintree.
<script src="https://js.braintreegateway.com/web/dropin/1.24.0/js/dropin.js"></script>
<div id="dropin-container"></div>
<button id="submit-button" class="button button--small button--green">Purchase</button>
var button = document.querySelector('#submit-button');
braintree.dropin.create({
authorization: 'xxxxx',
selector: '#dropin-container'
}, function (err, instance) {
button.addEventListener('click', function () {
instance.requestPaymentMethod(function (err, payload) {
// Submit payload.nonce to your server
});
})
});
It generates the credit card form nicely however if you click on the Purchase button, a payment_method_nonce is expected to return from the Braintree server.
My question is, how do I capture this payment_method_nonce variable in C# when the client form is rendered in Javascript, inside a webview?
Got it working.
You have to get the payment method token first after you've processed the credit card details.
Then pass this method payment token to get the payment method nonce then you proceed with the transaction.
Here's the code:
// Get the payment method token
var paymentmethod_token = creditCard.Token.ToString();
// Generate a payment method nonce
Result<PaymentMethodNonce> paymentmethodnonce_result = gateway.PaymentMethodNonce.Create(paymentmethod_token);
var nonce = paymentmethodnonce_result.Target.Nonce;

Google Data API Authorization Redirect URI Mismatch

Background
I am wanting to write a small, personal web app in .NET Core 1.1 to interact with YouTube and make some things easier for me to do and I am following the tutorials/samples in Google's YouTube documentation. Sounds simple enough, right? ;)
Authenticating with Google's APIs seems impossible! I have done the following:
Created an account in the Google Developer Console
Created a new project in the Google Developer Console
Created a Web Application OAuth Client ID and added my Web App debug URI to the list of approved redirect URIs
Saved the json file provided after generating the OAuth Client ID to my system
In my application, my debug server url is set (and when my application launches in debug, it's using the url I set which is http://127.0.0.1:60077).
However, when I attempt to authenticate with Google's APIs, I recieve the following error:
That’s an error.
Error: redirect_uri_mismatch
The redirect URI in the request, http://127.0.0.1:63354/authorize/,
does not match the ones authorized for the OAuth client.
Problem
So now, for the problem. The only thing I can find when searching for a solution for this is people that say
just put the redirect URI in your approved redirect URIs
Unfortunately, the issue is that every single time my code attempts to authenticate with Google's APIs, the redirect URI it is using changes (the port changes even though I set a static port in the project's properties). I cannot seem to find a way to get it to use a static port. Any help or information would be awesome!
NOTE: Please don't say things like "why don't you just do it this other way that doesn't answer your question at all".
The code
client_id.json
{
"web": {
"client_id": "[MY_CLIENT_ID]",
"project_id": "[MY_PROJECT_ID]",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "[MY_CLIENT_SECRET]",
"redirect_uris": [
"http://127.0.0.1:60077/authorize/"
]
}
}
Method That Is Attempting to Use API
public async Task<IActionResult> Test()
{
string ClientIdPath = #"C:\Path\To\My\client_id.json";
UserCredential credential;
using (var stream = new FileStream(ClientIdPath, FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeReadonly },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelsListRequest = youtubeService.Channels.List("contentDetails");
channelsListRequest.Mine = true;
// Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
var channelsListResponse = await channelsListRequest.ExecuteAsync();
return Ok(channelsListResponse);
}
Project Properties
The Original Answer works, but it is NOT the best way to do this for an ASP.NET Web Application. See the update below for a better way to handle the flow for an ASP.NET Web Application.
Original Answer
So, I figured this out. The issue is that Google thinks of a web app as a JavaScript based web application and NOT a web app with server side processing. Thus, you CANNOT create a Web Application OAuth Client ID in the Google Developer Console for a server based web application.
The solution is to select the type Other when creating an OAuth Client ID in the Google Developer Console. This will have Google treat it as an installed application and NOT a JavaScript application, thus not requiring a redirect URI to handle the callback.
It's somewhat confusing as Google's documentation for .NET tells you to create a Web App OAuth Client ID.
Feb 16, 2018 Updated Better Answer:
I wanted to provide an update to this answer. Though, what I said above works, this is NOT the best way to implement the OAuth workflow for a ASP.NET solution. There is a better way which actually uses a proper OAuth 2.0 flow. Google's documentation is terrible in regards to this (especially for .NET), so I'll provide a simple implementation example here. The sample is using ASP.NET core, but it's easily adapted to the full .NET framework :)
Note: Google does have a Google.Apis.Auth.MVC package to help simplifiy this OAuth 2.0 flow, but unfortunately it's coupled to a specific MVC implementation and does not work for ASP.NET Core or Web API. So, I wouldn't use it. The example I'll be giving will work for ALL ASP.NET applications. This same code flow can be used for any of the Google APIs you've enabled as it's dependent on the scopes you are requesting.
Also, I am assuming you have your application set up in your Google Developer dashboard. That is to say that you have created an application, enabled the necessary YouTube APIs, created a Web Application Client, and set your allowed redirect urls properly.
The flow will work like this:
The user clicks a button (e.g. Add YouTube)
The View calls a method on the Controller to obtain an Authorization URL
On the controller method, we ask Google to give us an Authorization URL based on our client credentials (the ones created in the Google Developer Dashboard) and provide Google with a Redirect URL for our application (this Redirect URL must be in your list of accepted Redirect URLs for your Google Application)
Google gives us back an Authorization URL
We redirect the user to that Authorization URL
User grants our application access
Google gives our application back a special access code using the Redirect URL we provided Google on the request
We use that access code to get the Oauth tokens for the user
We save the Oauth tokens for the user
You need the following NuGet Packages
Google.Apis
Google.Apis.Auth
Google.Apis.Core
Google.apis.YouTube.v3
The Model
public class ExampleModel
{
public bool UserHasYoutubeToken { get; set; }
}
The Controller
public class ExampleController : Controller
{
// I'm assuming you have some sort of service that can read users from and update users to your database
private IUserService userService;
public ExampleController(IUserService userService)
{
this.userService = userService;
}
public async Task<IActionResult> Index()
{
var userId = // Get your user's ID however you get it
// I'm assuming you have some way of knowing if a user has an access token for YouTube or not
var userHasToken = this.userService.UserHasYoutubeToken(userId);
var model = new ExampleModel { UserHasYoutubeToken = userHasToken }
return View(model);
}
// This is a method we'll use to obtain the authorization code flow
private AuthorizationCodeFlow GetGoogleAuthorizationCodeFlow(params string[] scopes)
{
var clientIdPath = #"C:\Path\To\My\client_id.json";
using (var fileStream = new FileStream(clientIdPath, FileMode.Open, FileAccess.Read))
{
var clientSecrets = GoogleClientSecrets.Load(stream).Secrets;
var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = clientSecrets, Scopes = scopes };
var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
return googleAuthorizationCodeFlow;
}
}
// This is a route that your View will call (we'll call it using JQuery)
[HttpPost]
public async Task<string> GetAuthorizationUrl()
{
// First, we need to build a redirect url that Google will use to redirect back to the application after the user grants access
var protocol = Request.IsHttps ? "https" : "http";
var redirectUrl = $"{protocol}://{Request.Host}/{Url.Action(nameof(this.GetYoutubeAuthenticationToken)).TrimStart('/')}";
// Next, let's define the scopes we'll be accessing. We are requesting YouTubeForceSsl so we can manage a user's YouTube account.
var scopes = new[] { YouTubeService.Scope.YoutubeForceSsl };
// Now, let's grab the AuthorizationCodeFlow that will generate a unique authorization URL to redirect our user to
var googleAuthorizationCodeFlow = this.GetGoogleAuthorizationCodeFlow(scopes);
var codeRequestUrl = googleAuthorizationCodeFlow.CreateAuthorizationCodeRequest(redirectUrl);
codeRequestUrl.ResponseType = "code";
// Build the url
var authorizationUrl = codeRequestUrl.Build();
// Give it back to our caller for the redirect
return authorizationUrl;
}
public async Task<IActionResult> GetYoutubeAuthenticationToken([FromQuery] string code)
{
if(string.IsNullOrEmpty(code))
{
/*
This means the user canceled and did not grant us access. In this case, there will be a query parameter
on the request URL called 'error' that will have the error message. You can handle this case however.
Here, we'll just not do anything, but you should write code to handle this case however your application
needs to.
*/
}
// The userId is the ID of the user as it relates to YOUR application (NOT their Youtube Id).
// This is the User ID that you assigned them whenever they signed up or however you uniquely identify people using your application
var userId = // Get your user's ID however you do (whether it's on a claim or you have it stored in session or somewhere else)
// We need to build the same redirect url again. Google uses this for validaiton I think...? Not sure what it's used for
// at this stage, I just know we need it :)
var protocol = Request.IsHttps ? "https" : "http";
var redirectUrl = $"{protocol}://{Request.Host}/{Url.Action(nameof(this.GetYoutubeAuthenticationToken)).TrimStart('/')}";
// Now, let's ask Youtube for our OAuth token that will let us do awesome things for the user
var scopes = new[] { YouTubeService.Scope.YoutubeForceSsl };
var googleAuthorizationCodeFlow = this.GetYoutubeAuthorizationCodeFlow(scopes);
var token = await googleAuthorizationCodeFlow.ExchangeCodeForTokenAsync(userId, code, redirectUrl, CancellationToken.None);
// Now, you need to store this token in rlation to your user. So, however you save your user data, just make sure you
// save the token for your user. This is the token you'll use to build up the UserCredentials needed to act on behalf
// of the user.
var tokenJson = JsonConvert.SerializeObject(token);
await this.userService.SaveUserToken(userId, tokenJson);
// Now that we've got access to the user's YouTube account, let's get back
// to our application :)
return RedirectToAction(nameof(this.Index));
}
}
The View
#using YourApplication.Controllers
#model YourApplication.Models.ExampleModel
<div>
#if(Model.UserHasYoutubeToken)
{
<p>YAY! We have access to your YouTube account!</p>
}
else
{
<button id="addYoutube">Add YouTube</button>
}
</div>
<script>
$(document).ready(function () {
var addYoutubeUrl = '#Url.Action(nameof(ExampleController.GetAuthorizationUrl))';
// When the user clicks the 'Add YouTube' button, we'll call the server
// to get the Authorization URL Google built for us, then redirect the
// user to it.
$('#addYoutube').click(function () {
$.post(addYoutubeUrl, function (result) {
if (result) {
window.location.href = result;
}
});
});
});
</script>
As referred here, you need to specify a fix port for the ASP.NET development server like How to fix a port number in asp.NET development server and add this url with the fix port to the allowed urls. Also as stated in this thread, when your browser redirects the user to Google's oAuth page, you should be passing as a parameter the redirect URI you want Google's server to return to with the token response.
I noticed that there is easy non-programmatic way around.
If you have typical monotlith application built in typical MS convention(so not compatible with 12factor and typical DDD) there is an option to tell your Proxy WWW server to rewrite all requests from HTTP to HTTPS so even if you have set up Web App on http://localhost:5000 and then added in Google API url like: http://your.domain.net/sigin-google, it will work perfectly and it is not that bas because it is much safer to set up main WWW to rewrite all to HTTPS.
It is not very good practice I guess however it makes sense and does the job.
I've struggled with this issue for hours in a .net Core application. What finally fixed it for me was, in the Google developers console, to create and use a credential for "Desktop app" instead of a "Web application".
Yeah!! Using credentials of desktop app instead of web app worked for me fine. It took me more than 2 days to figure out this problem. The main problem is that google auth library dose not adding or supporting http://localhost:8000 as redirect uri for web app creds but credentials of desktop app fixed that issue. Cause its supporting http://___ connection instead of https: connection for redirect uri

Is sending Session from javascript safe?

Well, this is a bit weird i think to ask this question, because i am not sure if that's the place to ask that.
OK, into the question..
I have this code
<script>
var session = "<%= Session["User"]%>";
</script>
So, i was thinking, is that safe? let me tell you what i mean..
I have a web api which you can get the name, last name, age and everything about the user with his Session, can i send this web api this session and use it?
Is that a safe thing to do ? in matter of securiy? if not, is there any better way?
EDIT 1:
What am i trying to aaccomplish? simple, i will store the UserId in the session, the UserId will Guid, when the user is loogin in the javascript can send post to an API server to get info, the API will send the UserId from the session.
Is That ok?
Workflow that you describe looks fine. For me it seems safe to use some ID to get more information about some user, especially if this is supposed to be an API, at least, Facebook API uses such principle not being afraid of some hackers :)
My main concern here is the coding style when you try to mix code and view which is not good. If you really need to share some information between client and server sides then I would go with one of these options.
Option # 1 - Cookies
What is the difference between a Session and a Cookie?
You can keep some simple information in a cookie and get it this way :
Client : $.cookie('ID')
Server : Response.Cookies["ID"]
In this case there is no need to put in a mess your client side JS with C# code and cookies will be saved on users PC which means that nobody will see them except him.
Option # 2 - Templates
Server : put all needed information into hidden form or ViewState
Client : take information from hidden form using HTML selectors
Straight answer :
In general, if you worry only about safety then it is fine to use this code, it should not break security of your site.
Although, personally I do not like this approach because :
you will mix code and view, MVC was created to split them
it is not clear where exactly in your view you will put this code and thus it is not clear how you are going to check that this variable was initialized
it may happen that you will put there some value that will break JS syntax and will cause JS error
In my personal opinion, I would replace it with one of the mentioned options.
Option 1 - MVC + JQuery + Cookie Example
public ActionResult Index()
{
string demo = Request.QueryString["MyNameSpace.ID"]; // get value from client
Response.Cookies["MyNameSpace.ID"].Value = "server"; // change value in response
return View();
}
Then in your JS file :
$(document).ready(function() { // make sure server rendered page
var ID = $.cookie('MyNameSpace.ID'); // get cookie value from server
$.cookie('MyNameSpace.ID', 'client'); // update, on the next request server will get it
});
Option 2 - MVC + JQuery + Templates Example
public class OptionsModel // View Model
{
public string ID { get; set; }
public string User { get; set; }
}
public ActionResult Index() // Controller
{
OptionsModel options = new OptionsModel();
options.ID = "server";
return View(options);
}
Your view :
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<OptionsModel>" %>
<%=Html.HiddenFor(m => Model.ID, new { #class = "MyNameSpace:ID" })%>
<%=Html.HiddenFor(m => Model.User, new { #class = "MyNameSpace:User" })%>
Then in your JS file :
$(document).ready(function() { // make sure server rendered page
var options = $('[class^=MyNameSpace]') // get values from hidden fields
options[0] = 'client'; // update data
$.ajax({ data : options }); // create handler to send data back to server
});
Examples for Web Forms do not differ significantly.
The code you have posted will be rendered on the page as so when it hits the client (assuming you are using ASP.NET
<script>
var session = "John Smith";
</script>
This is due to the use of the server side scripting tags <%= %> (https://technet.microsoft.com/en-us/library/cc961121.aspx)
As a note its probably not the best thing in the world to fully expose the session to javascript if that is your intention. At the end of the day it depends what you are storing in there and using it for (but ASP.NET will also use it for certain things) but exposing it just opens another area for someone to attack.
http://www.owasp.org is a great place to learn more about securing your website.

PUSH on event "DB Data Changes" using SignalR

All right I followed the chat application demo just fine, a couple of other tuts as well, but all of them combined doesn't answer or due to my lack of intelligence to derive the answer I want. The scenario is as follows
I am building a website with
MVC 4
.NET Framework 4.0
IIS 7.5
ASP.NET 4
SQL Server 2008 R2
that is to accompany a desktop app, i.e. my web application and the desktop app will be interacting with the same DB. I want to add an AMS (Acess Management System) to the website and the desktop application, so that Users access rights to any function inside the apps can be managed finely grained. I want the changes to be PUSHED to the wesite in realtime.
For Example: A manager from the desktop app revokes the rights of the clerks to view sales reports, and a couple of clerks were online on the website, so I want those changes to be PUSHED to the website as they are made.
Now currently I am storing the rights of the users at login, so that with the increasing number of users wont cause the performance of the website to degrade quickly, now I know that when checking for every action either allowed or not, I can make a round trip to the DB and check for the condition, but as I said earlier, that would degrade the performance.
Now I want to PUSH the rights of the users to the website if there are some changes, either from the website itself or the desktop app, I looked into SignalR, and I found a solution here on SO (This and This), but I don't want a clock ticker running continuously and then broadcasting the changes to all connected clients. And the user that is being changed, maybe connected to the website or maybe not. Please can someone point me in the right direction
I have spent much time on trying to find a solution for this, and the simplest I've found, using SignalR, is to use Hubs as a gateway to your Repository/API:
So, here's how the project would be set up:
ASP.NET MVC Controllers' Actions dish out entire pages.
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
The View should be wrapped in a Layout that loads a Knockout MVVM. The View then initializes the part of the MVVMs that need to be used (as in, lump all your MVVM script in one file, and the View initializes the SignalR connections, to avoid needless connections (the code below has the Script initializing itself)). The View also has KnockOut bindings attached to it.
MVVM:
function AddressViewModel(rid, nick, line1, line2, city, state, zip)
{
<!-- Modifiable Properties should be observable. This will allow Hub updates to flow to the View -->
var self = this;
self.rid = rid;
self.nick = ko.observable(nick);
self.line1 = ko.observable(line1);
self.line2 = ko.observable(line2);
self.city = ko.observable(city);
self.state = ko.observable(new StateViewModel(state.RID, state.Title, state.Abbreviation));
self.zip = ko.observable(zip);
}
function StateViewModel(rid, title, abbreviation)
{
<!-- States are a stagnant list. These will not be updated -->
var self = this;
self.rid = rid;
self.title = title;
self.abbreviation = abbreviation;
}
var Page = new function()
{
//Page holds all Page's View Models. The init function can be modified to start only certain hubs.
var page = this;
page.init = function()
{
page.Account.init();
}
page.Account = new function ()
{
//Account holds account-specific information. Should only be retrieved on an encrypted, secure, and authorized connection.
account.init = function()
{
account.Addresses.init();
}
//Addresses manages the calls to Hubs and their callbacks to modify local content.
account.Addresses = new function ()
{
//Connect to the hub, and create an observable list.
var addresses = this;
addresses.hub = $.connection.accountAddressHub;
addresses.list = ko.observableArray([]);
//Called on initial load. This calls the Index() function on the Hub.
addresses.init = function ()
{
addresses.hub.server.index();
}
//displayMode allows for dynamic changing of the template.
addresses.displayMode = ko.computed(function ()
{
return 'Address';
});
//Empty allows to prompt user instead of just showing a blank screen.
addresses.empty = ko.computed(function ()
{
if (addresses.list().length == 0)
{
return true;
}
else
{
return false;
}
});
//During initial load, unless if MVC provides the information with the View, the list will be empty until the first SignalR callback. This allows us to prompt the user we're still loading.
addresses.loading = ko.observable(true);
//The Hub's Index function ought to reach indexBack with a list of addresses. The addresses are then mapped to the list, using the local AddressViewModel. Sets initial load to false, as we now have addresses.
addresses.hub.client.indexBack = function (addressList)
{
$.map(addressList, function (address)
{
addresses.list.push(new AddressViewModel(address.RID, address.Nick, address.Line1, address.Line2, address.City, address.State, address.ZIP));
});
addresses.loading(false);
}
}
}
}
On Run Script (Place in Layout, Script File, or View, depending on needs or confirgurations per page)
$(function ()
{
//Configures what SignalR will do when starting, on receive, reconnected, reconnected, or disconnected.
$.connection.hub.starting(function ()
{
$('.updated').hide();
$('.updating').show();
});
$.connection.hub.received(function ()
{
$('.updating').hide();
$('.updated').show();
});
$.connection.hub.reconnecting(function ()
{
$('.updated').hide();
$('.updating').show();
});
$.connection.hub.reconnected(function ()
{
$('.updating').hide();
$('.updated').show();
});
//This will keep attempt to reconnect - the beauty of this, if the user unplugs the internet with page loaded, and then plugs in, the client reconnects automatically. However, the client would probably not receive any backlog - I haven't test that.
$.connection.hub.disconnected(function ()
{
setTimeout(function ()
{
$.connection.hub.start();
}, 5000); // Restart connection after 5 seconds.
});
//Apply knockout bindings, using the Page function from above.
ko.applyBindings(Page);
//Start the connection.
$.connection.hub.start(function ()
{
}).done(function ()
{
//If successfully connected, call the init functions, which propagate through the script to connect to all the necessary hubs.
console.log('Connected to Server!');
Page.init();
})
.fail(function ()
{
console.log('Could not Connect!');
});;
});
LayOut:
<!DOCTYPE html>
<html>
<head>
. . .
#Styles.Render( "~/Content/css" )
<!-- Load jQuery, KnockOut, and your MVVM scripts. -->
#Scripts.Render( "~/bundles/jquery" )
<script src="~/signalr/hubs"></script>
. . .
</head>
<body id="body" data-spy="scroll" data-target="#sidenav">
. . .
<div id="wrap">
<div class="container">
#RenderBody()
</div>
</div>
#{ Html.RenderPartial( "_Foot" ); }
</body>
</html>
View (Index):
#{
ViewBag.Title = "My Account";
}
<div>
#{
Html.RenderPartial( "_AddressesWrapper" );
}
</div>
_AddressesWrapper:
<div data-bind="with: Page.Account.Addresses">
#{
Html.RenderPartial( "_Address" );
}
<div id="Addresses" class="subcontainer">
<div class="subheader">
<div class="subtitle">
<h2>
<span class="glyphicon glyphicon-home">
</span>
Addresses
</h2>
</div>
</div>
<div id="AddressesContent" class="subcontent">
<div class="row panel panel-primary">
<!-- Check to see if content is empty. If empty, content may still be loading.-->
<div data-bind="if: Page.Account.Addresses.empty">
<!-- Content is empty. Check if content is still initially loading -->
<div data-bind="if:Page.Account.Addresses.loading">
<!-- Content is still in the initial load. Tell Client. -->
<div class="well well-lg">
<p class="text-center">
<img src="#Url.Content("~/Content/Images/ajax-loader.gif")" width="50px" height="50px" />
<strong>We are updating your Addresses.</strong> This should only take a moment.
</p>
</div>
</div>
<div data-bind="ifnot:Page.Account.Addresses.loading">
<!-- Else, if not loading, the Client has no addresses. Tell Client. -->
<div class="well well-lg">
<p class="text-center">
<strong>You have no Addresses.</strong> If you add an Addresses, you can view, edit, and delete it here.
</p>
</div>
</div>
</div>
<!-- Addresses is not empty -->
<div data-bind="ifnot: Page.Account.Addresses.empty">
<!-- We have content to display. Bind the list with a template in the Partial View we loaded earlier -->
<div data-bind="template: { name: Page.Account.Addresses.displayMode, foreach: Page.Account.Addresses.list }">
</div>
</div>
</div>
</div>
</div>
</div>
_Address:
<script type="text/html" id="Address">
<div class="col-lg-3 col-xs-6 col-sm-4 well well-sm">
<address>
<strong data-bind="text: nick"></strong><br>
<span data-bind="text: line1"></span><br>
<span data-bind="if: line2 == null">
<span data-bind="text: line2"></span><br>
</span>
<span data-bind="text: city"></span>, <span data-bind=" text: state().abbreviation"></span> <span data-bind="text: zip"></span>
</address>
</div>
</script>
The KnockOut script interchanges with a SignalR Hub. The Hub receives the call, checks the authorization, if necessary, and passes the call to the proper repository or straight to WebAPI 2 (this example). The SignalR Hub action then takes the results of the API exchange and determines which function to call, and what data to pass.
public class AccountAddressHub : AccountObjectHub
{
public override async Task Index()
{
//Connect to Internal API - Must be done within action.
using( AddressController api = new AddressController(await this.Account()) )
{
//Make Call to API to Get Addresses:
var addresses = api.Get();
//Return the list only to Connecting ID.
Clients.Client( Context.ConnectionId ).indexBack( addresses );
//Or, return to a list of specific Connection Ids - can also return to all Clients, instead of adding a parameter.
Clients.Clients( ( await this.ConnectionIds() ).ToList() ).postBack( Address );
}
}
}
The API Controller checks data integrity and sends a callback to the same SignalR Hub action.
public class AddressController
: AccountObjectController
{
...
// GET api/Address
public ICollection<Address> Get()
{
//This returns back the calling Hub action.
return Account.Addresses;
}
...
}
Your .NET application will need to use the same functions as your javascript-ran site. This will allow a modification from any client to then propagate to however many clients are needed (that single client who just loaded, as in this example, or to broadcast to everyone, or anywhere in between)
The end result is that the Hub receives changes/calls, calls the API, the API verifies the data and returns it back to the Hub. The Hub can then update all clients. You then successfully have real-time database changes and real-time client changes. The only catch is any change outside of this system will require the clients to refresh, which means all client calls, especially changes, must go through Hubs.
If you need more examples, I would be happy to show some. Obviously, security measures should be taken, and the code here is obviously only a small example.
If you want use signalr I think you should use push server.But you can use another way and send a request to the api and the api should know about db change.
For push server you can also see this.
There are some considerations that might help.
1- Since you are playing with the Access rights , so i would say that , you must check the access right at run time each time , user wants to access certain secured functionality , yes this will have some degradation in performance but ensure you the tighter granular security.
2- For sending periodic changes , i would say that , you can use Timer available in .Net and trigger changes at a certain interval.
3- I still don't like the idea of sending security related information to the client (thin) because anybody with basic knowledge of JavaScript and Html can change the security by running your site in debug mode or through some automated tools like Fiddler.
I've made a library that proxies between a server side eventaggregator / service bus. It makes it alot easier to stream line the events being sent to clients. Take a look at the demo project here
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/tree/master/SignalR.EventAggregatorProxy.Demo.MVC4
Open the demo .sln and there is both a .NET client (WPF) and a javascript client example
Install using nuget
Install-Package SignalR.EventAggregatorProxy
wiki
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki

reCaptcha and SSL web site

I using a reCaptcha on my web page under asp.net mvc. This web site have a SSL certificated, and I having and problem with reCaptcha.
This is my code on View:
<script type="text/javascript" src="https://api-secure.recaptcha.net/challenge?k=***Public key****"> </script>
<noscript>
<iframe src="https://api-secure.recaptcha.net/noscript?k=***Public key****" height="300" width="500" frameborder="0"></iframe><br />
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge" />
</noscript>
and this code is that I have on AccountController:
private bool PerformRecaptcha()
{
var validator = new RecaptchaValidator
{
PrivateKey = "**Private Key***",
RemoteIP = Request.UserHostAddress,
Response = Request.Form["recaptcha_response_field"],
Challenge = Request.Form["recaptcha_challenge_field"]
};
try
{
var validationResult = validator.Validate();
if (validationResult.ErrorMessage == "incorrect-captcha-sol")
ModelState.AddModelError("ReCaptcha", string.Format("Please retry the ReCaptcha portion again."));
return validationResult.IsValid;
}
catch (Exception e)
{
ModelState.AddModelError("ReCaptcha", "an error occured with ReCaptcha please consult documentation.");
return false;
}
}
and my library version is 1.0.5.0.
When I load the register form I have this alert on Opera:
The rules server certificate matches the server name. Do you want to accept?
If I accept this certificate, displays reCaptcha code, but if not, I don't view reCaptcha Code.
Can you help me with this?
If you need more information about my code, feel free to ask to me.
Regards.
I think you need to change the url you are using to include recaptcha. A number of people had the same problem in April. Recaptcha let the certificate expire for "api-secure.recaptcha.net". If you change it to use the "https://www.google.com/recaptcha/api/XXX" url instead of "https://api-secure.recaptcha.net/XXX", it should definitely fix your issue.
It looks like this one has actually been answered before: recaptcha https problem on https://api-secure.recaptcha.net/. Since you are using the .NET library, I think your answer is to upgrade your version.
Sharpening up on JasonStoltz's answer:
You are already using the latest DLL version, there's no need to update this
You can/should use RecaptchaControlMvc.GenerateCaptcha() method in your View instead of writing your own (it will use the new URL)

Categories