RestSharp AddBody adding double quote in JSON parameter

I am calling API with RESTSharp

I am calling API with RESTSharp

  var client = new RestClient("http://demoservice.com");
  var request = new RestRequest("callapi", "put");          
  request.RequestFormat = DataFormat.Json;

string jsonaction = "{"tokenid":"x123x45","userid":"2456","ip":"192.168.1.20","transaction":"6","actionCode":"78","jtoken":"systemtoken"}";
request.AddBody(new { action = "SAVE", data = "savedata", token = "systemtoken", jsonaction = jsonaction });

I am checking in debug data passing in request. and my expected output as follows

{"action":"SAVE","data":"savedata","token":"systemtoken","jsonaction":{"tokenid":"x123x45","userid":"2456","ip":"192.168.1.20","transaction":"6","actionCode":"78","jtoken":"systemtoken"}}

But getting

{"action":"SAVE","data":"savedata","token":"systemtoken","jsonaction":"{"tokenid":"x123x45","userid":"2456","ip":"192.168.1.20","transaction":"6","actionCode":"78","jtoken":"systemtoken"}"}

If anybody can guide how to post for JSON I have tried with Addbody and AddJsonBody but nothing works.

Building Authenticated Web app with C#, Blazor and ASP.NET Core 3.0

Building Authenticated Web app with C#, Blazor and ASP.NET Core 3.0

Goodbye Javascript! Now, i can Building an Authenticated Web App in C# with Blazor + ASP.NET Core 3.0.

Curious what the experience would be like to trade in Javascript for C# on the front end? You are about to find out!

Table of Contents

  • Build a Basic Website with ASP.NET Core 3.0 + Blazor
  • Add User Authentication your Blazor Web App
  • Set Up Your Okta Account to handle the ASP.NET Core 3.0 Blazor App
  • Configure Your Blazor App to use Okta as the External Auth Provider
  • Add User Login to your Blazor Web App UI
  • Test Okta Registration and Login for Your Blazor App
  • Learn More about ASP.NET Core, Blazor and Authentication

For many years, Javascript (and it’s child frameworks) have had their run of the DOM (Document Object Model) in a browser, and it took having that scripting knowledge to really manipulate client-side UI. About 2 years ago, all of that changed with the introduction of Web Assembly - which allows compiled languages to be interpreted client-side and is fully supported across all browsers now. Microsoft’s answer to this was the creation of Blazor. Allowing C# developers to build their entire stack in .NET, including UI, was an exciting proposition. For some time Blazor has been in preview but is now included as a general release on September 23rd, 2019 along with the next iteration of .NET Core - version 3.0.

In order to build with Blazor and ASP.NET Core 3.0, you need the following prerequisites installed and ready to go:

Build a Basic Website with ASP.NET Core 3.0 + Blazor

Now that you have your dev environment handy, let’s get familiar with what a basic website walkthrough would be like. There are two ways you can utilize this technology: client-side or server-side Blazor. For this example, the server-side option is the best choice for stability, as client-side Blazor is still new and working on the final release. Stay tuned for that implementation!

First, you’ll need to create a Blazor project. To get the latest Blazor project templates to work with Visual Studio or VS Code, simply install them from the command line/terminal from your base repo directory:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview9.19424.4

Visual Studio (16.3 or later) will detect that the templates have been installed and surface them to you without the need for any additional extensions. Now it’s time to scaffold your new project. From your parent directory of code repositories, execute the following command:

dotnet new blazorserver -o OktaBlazorAspNetCoreServerSide

Once it’s been run, open up the OktaBlazorAspNetCoreServerSide folder in Visual Studio Code. Once loaded, if you look in the bottom right-hand corner of the IDE you will see a permission request to add assets to the build. Select Yes.

Now that everything has been loaded up, return to your command line/terminal and run the project.

dotnet run

Launch your browser of choice and navigate to https://localhost:5001. You should see a templated website.

Add User Authentication your Blazor Web App

ASP.NET Core 3.0 has brought along with it some hefty changes to the libraries and dependencies from previous versions of .NET Core. To get started with using an external OAuth provider, like Okta, there is a NuGet package you need to add to the project. Fire up your command line/terminal window in VS Code and add the Okta .NET SDK:

dotnet add package Okta.Sdk --version 1.4.0

In 3.0, ASP.NET Core ships as part of the .NET Core shared framework. The metapackage that was used for 2.x apps is no longer used. The first line of your project file that references the Web SDK is what pulls in the shared assemblies for ASP.NET Core.

For user authentication with OAuth, there is an additional layer of information you will use, called Open ID Connect (OIDC). While much of handling authentication is baked into the new 3.0 framework, OIDC is not included, so you’ll need to add a quick reference to that.

dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect --version 3.0.0-preview9.19424.4

Authentication works by redirecting users to the Okta website, where they will log in with their credentials, and then be returned to your site via the URL you will configure in the next section. Add the following code to the very top of your appsettings.json file, inside of the first brackets, and separate it from the rest of the settings by adding a comma after it.

"Okta": {
    "Issuer": "https://okta.okta.com/oauth2/default",
    "ClientId": "{yourClientId}",
    "ClientSecret": "{yourClientSecret}"
  }

Your file should look like this:

Just to make sure everything still can run, go ahead and execute dotnet run again.

Set Up Your Okta Account to handle the ASP.NET Core 3.0 Blazor App

Execute the following steps to configure Okta so that users can register themselves for an account.

  1. From the Administrative Dashboard, hover over Users and click Registration
  2. Click Enable Registration
  3. Save the changes

Once you have access to your account you can proceed to the Dashboard using a link like the one below: https://okta.okta.com/admin/dashboard

On the Dashboard, click Applications in the main menu and on the Application screen, click Add Application. Then select Web and click Next.

On the Create New Application screen, set the following values:

  • Name: OktaBlazorAspNetCoreServerSide

  • Base URIs: https://localhost:5001/

  • Login redirect URIs: https://localhost:5001/authorization-code/callback

Click Done, then click Edit next to General Settings on your newly created Okta app. Edit the following values: Logout redirect URIs: https://localhost:5001/signout-callback-oidc Initiate login URI: https://localhost:5001/authorization-code/callback

Once you’ve saved those values, scroll down and take note of the ClientID and ClientSecret.

ClientId refers to the client ID of the Okta application ClientSecret refers to the client secret of the Okta application Issuer will need the text {yourOktaDomain} replaced with your Okta domain, found at the top-right of the Dashboard page.

You will use your Okta account settings to update those values in the appsettings.json file in your project.

Configure Your Blazor App to use Okta as the External Auth Provider

Great! Now that Okta has been configured and is ready to go, there are a few changes that need to be made to the application startup.

Add these using statements to your Startup.cs file:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;

Replace all the code in the ConfigureServices method with the code below.

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<WeatherForecastService>();
    services.AddAuthorizationCore();
    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.ClientId = Configuration["okta:ClientId"];
        options.ClientSecret = Configuration["okta:ClientSecret"];
        options.Authority = Configuration["okta:Issuer"];
        options.CallbackPath = "/authorization-code/callback";
        options.ResponseType = "code";
        options.SaveTokens = true;
        options.UseTokenLifetime = false;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name"
        };
    });
}

ASP.NET Core 3.0 has new options to configure the services in this file. UseAuthorization has been newly added to 3.0 project templates.

In the Configure() method of your Startup.cs file add this line just before the app.UseEndpoints() method:

app.UseAuthentication();
app.UseAuthorization();

In this example, you'll see there's a new UseEndpoints method in Startup.cs. This is what enables the new endpoint routing system in ASP.NET Core. All 3.0 project templates use that now. Think of this as a more performant routing system.

NOTE: In the context of Blazor apps, endpoint routing is the more holistic way of handling redirects. This is covered here in depth. Also, see this documentation to learn more about it. Endpoint routing shipped in ASP.NET Core 2.2, but it didn't become the default in the templates until 3.0.

Add User Login to your Blazor Web App UI

Time to add some user personalization to this app! Open Shared/MainLayout.razor and add the following HTML right before the About link.

<AuthorizeView>
<Authorized>
            <a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a>
            <a href="Identity/Account/LogOut">Log out</a>
    </Authorized>
    <NotAuthorized>
            <a href="Identity/Account/Register">Register</a>
            <a href="Identity/Account/Login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

Using <AuthorizeView> is the easiest way to access authentication data, and is useful when you need to display a user’s name. The <AuthorizeView> component exposes a context variable of type AuthenticationState. In order to add this state to our app, open App.razor and wrap the HTML you see with <CascadingAuthenticationState> tags at the parent level. It should look like this:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        ...
    </Router>
</CascadingAuthenticationState>
Test Okta Registration and Login for Your Blazor App

That’s it! To test it out, go back to the command line/terminal and execute dotnet run.

Then navigate to http://localhost:5001 in your browser. Click Login and you should be redirected to the Okta Sign-In Page.

Because you configured your Okta org for self-registration, there should be an option at the bottom of the widget to allow users to register for a new account.

Now you have a website with a working login and user registration form. Your website also allows users to recover lost passwords. By repeating these steps you can create a network of tools that your users can access all with the same login.

All of that and not one line of Javascript. The future is looking bright for C#, give it a go with Blazor!

Thank for reading! Originally published on scotch.io

Understanding JSON Web Token Authentication

Understanding JSON Web Token Authentication

In this article, you'll learn the ‘Why’, ‘What’ and ‘How’ for Authentication in Web App using JWT (JSON Web Token)

In this article, you'll learn the ‘Why’, ‘What’ and ‘How’ for Authentication in Web App using JWT (JSON Web Token)

When making a website, you may have come across an array of problems. Among which, authentication while logging in a User, comes as a major headache to developers, primarily to those who are just starting out. Tokens and Sessions were created to ease with this very problem.

A Token is a piece of data that has no meaning or use on its own, but when combined with the correct Tokenization system(a process of replacing sensitive data with unique identification symbols that retain all the essential information about the data without compromising its security) becomes a powerful tool for authentication. Whereas, a Session is a system to manage the duration after which a user is logged out automatically.

Usually, we use HTTP protocols while developing and browsing web applications. For proper implementation of tokenization, we need the server to retain some information or status about the user for the duration of multiple requests, but HTTP is stateless protocol, meaning HTTP does not require the server to store information. If you login for one request, the server will have already forgotten you and you will need to login again to make another request. As you can imagine, this can get pretty annoying when performed repeatedly.

To overcome the stateless nature of HTTP requests, we could use either a session-based or token-based authentication.

So, how is session-based authentication implemented for overcoming the stateless nature of HTTP? Session-Based authentication is implemented in two parts:

  • An object is stored on the server that remembers if a user is still logged in, it can be a reference to the user profile or maybe a session_ID.
  • Cookies on the client-side store's session_ ID that can be referenced on the server against the session _ID stored on the server.

Now you might be wondering how token based authentication helps to overcome the stateless nature of HTTP?

With token based authentication whenever the user sends a request to a server, each request is accompanied by a signed token which the server verifies for authenticity and only then responds to the request.

Most people will prefer token-based authentication(like JWT) for two major reasons; scalability and flexibility. With session-based authentication, the sessions are stored in the server’s memory so scaling becomes an issue when there is a huge number of users using the system at the same time. But with token-based authentication, there is no issue with scaling because the token is stored on the client side. Also, token generation is decoupled from token verification, allowing you the option to handle the signing of tokens on a separate server or even through a different company such us Auth0 and within the token payload you can easily specify user roles and permissions as well as resources that the user can access.

What is JWT?

JSON Web Token (JWT) as the name suggests is token based authentication which is an open, industry standard (RFC 7519) method for representing claims securely between two parties. "Open" meaning anybody can use it. In JWT, the token is encoded from a data payload using a secret. Since the token is encoded you should avoid keeping sensitive information on the payload. The token, when generated, is passed to the client. Whenever the client sends a request to the server, the token is passed along with a request, then the server validates the token and sends back the response. The following diagram shows how JWT works:

The summarization of the above picture is given below:

  1. A client signs-in using a valid username/password combination to the server.
  2. The server validates the authentication. If validation is successful, the server creates a JWT token and the client gets JWT token in the response body, else gives an error response.
  3. Client stores that token in local storage or session storage. Now if the client wants to make any request, JWT token must be passed in request headers like this. Authorization: Bearer
  4. Server upon receiving the JWT token validates its authenticity and sends the successful response or error response based on its validity.

If you want to know more about JWT and its structure please refer to its official documentation https://jwt.io/introduction/

How to use JWT?

There are many libraries available for JWT. The main function of any of these libraries is to generate JWT and validate JWT. You may use any one of these libraries.

Here, I have picked NPM library called jsonwebtoken. This library is primarily for Node.js.

Firstly, let's start by installing jsonwebtoken.


Installing JWT

After installing jsonwebtoken we need to import it to start using it.


Verifying JWT

The above code generates a JWT token which is encoded but not encrypted, so be careful not to include any sensitive information. The jwt.sign function takes the payload, secret and options, as its arguments. The payload contains information about the user and can be used to find out which user is the owner of the token. Options can have an expire time, until which, a token is deemed as valid. The generated JWT token is a string, which may look something like this:


JWT Token

After generating JWT token, it is returned to the client and it must be passed in Authorization header in order to make any request, access resources or to verify that client. The server must always verify the token before giving any success response or an error response.


Verifying JWT

Since JWT token is encoded it can be easily decoded and hence, easily altered. This may come as a disadvantage to most people, but when some changes are made to token, the signature of the token also changes. A Signature is the function of encoded payload, secret, and algorithm. Which is already being used for the validation of the JWT, so you need not worry about it.

All of this technical jargon is to show you how JWT is better than using a Session-based authentication, and why JWT has become an essential tool for authentication in the privacy-stricken world of today, where data is becoming more and more valuable.