Tag Archives: security

Get Private Key and Certificate from .PFX

Export the private key from .PFX file

C:\> openssl pkcs12 -in filename.pfx -nocerts -out privatekey.pem

Decrypt the encrypted private key

C:\> openssl rsa -in privatekey.pem -out private.key

The final private.key file is the the private key file.

Export the certificate from the .PFX file

C:\> openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem

The cert.pem output from the command is the certificate file.

Leave a comment

Posted by on February 2, 2018 in General


Tags: , ,

Claims-Based Authorization in ASP.Net MVC and Web Api

Normally, I would re-write a blog post in hope to provide better explanation and concise the article, but since this is from Dominick Baier, I think he does it the best.

So, here’s it, how to apply claims based authorization in ASP.Net MVC and Web Api:

Leave a comment

Posted by on May 28, 2015 in General


Tags: , , , , ,

Add Authentication to MongoDB Database

To prevent un-authorized access to your MongoDB database, you can add security to it by requiring authentication whenever someone tries to connect.

It’s simple, run the mongod with --auth option. the command is:

// To add user
> use admin;
> db.addUser('admin','123456');

// Start mongod with --auth
$ sudo mongod --auth --dbpath /data

// Run mongo and login
$ mongo localhost:27017
> use admin
> db.auth('admin','123456');

// Include login in mongo command
$ mongo localhost:456789/admin -u admin-p 123456

More MongoDB security option:

1 Comment

Posted by on May 7, 2015 in General


Tags: , , ,

Unit Testing WIF’s ClaimsPrincipalPermission.CheckAccess

WIF 4.5 has ClaimsPrincipalPermission.CheckAccess method, very useful to check user’s authorization. You can use this as method call or attribute.

// Imperative method call
using System.IdentityModel.Services;
public ActionResult Index()
    ClaimsPrincipalPermission.CheckAccess("foo", "bar");

    return View();

// Attribute
[ClaimsPrincipalPermission(SecurityAction.Demand, Operation="foo", Resource="bar")]
public ActionResult ViewFoobar()
    return View();

Either way, how do we unit test this? My approach is to first abstract out ClaimsPrincipalPermission and create a new wrapper class that will be injected to the dependent class.

Abstract Out

using System.IdentityModel.Services;

public class ClaimsPrincipalWrapper : IClaimsPrincipalWrapper
    public void CheckAccess(string resource, string action)
        ClaimsPrincipalPermission.CheckAccess(resource, action);

Dependency Injection

using System.IdentityModel.Services;

public class HomeController : Controller
    private readonly IClaimsPrincipalWrapper _ClaimsPrincipalWrapper;

    public HomeController(IClaimsPrincipalWrapper claimsPrincipalWrapper)
        _ClaimsPrincipalWrapper = claimsPrincipalWrapper;

    public ActionResult Index()
        _ClaimsPrincipalWrapper.CheckAccess("foo", "bar");

        return View();

Unit Test

public void TestIndex()
    // Arrange
    var _claimsPrincipal = new Mock<IClaimsPrincipalWrapper>();
    _claimsPrincipal.Setup(m => m.CheckAccess(It.IsAny<string>, It.IsAny<string>));
    var _controller = new HomeController(_claimsPrincipalMock.Object);

    // Act
    var _result = _controller.Index() as ViewResult;

    // Assert
    Assert.IsTrue(_result.View != null);
Leave a comment

Posted by on May 4, 2015 in General


Tags: , , , , , , ,

OAuth2 Flows

Cliff notes from Dominick Baier’s OAuth2 Flows.

Authorization Code Flow


Characters: web application (server-based) clients, confidential and secured client where nobody can see user credential, human involves, consent screen, authorization happens in authorization server.

Apply to: web applications


  1. Request authorization.
  2. Request token.
  3. Access resource.

Implicit Flow


Characters: native / local clients, user-agent based clients, human involves, consent screen, authorization happens in authorization servers.

Apply to: third party native applications (JavaScript application is included).


  1. Request authorization & token.
  2. Access resource.

Resource Owner Credential Flow


Characters: trusted clients, no human involvement, no consent screen, authorization happens in client.

Apply to: official native applications (JavaScript application included).


  1. Request token with resource owner credentials.
  2. Access resource.

Client Credential Flow


Characters: client to Service communication, no human involvement, no consent screen, authorization happens in client.

Apply to: machine to machine communication, service communication to authorization server without act as.


  1. Request token with client credentials.
  2. Access resource.

Assertion Flow


Characters: use one of the ‘core’ flows, access another trusted system (partner).

Apply to: translate between identity management system (ADFS’s saml to ThinkTecture’s jwt), communication with partner’s resources using client’s credential.


  1. Request token using ‘core’ flow (Authorization Code, Implicit, Resource Owner Credential, Client Credential).
  2. Request token using ‘assertion’ flow.
  3. Use token.
Leave a comment

Posted by on September 24, 2014 in General


Tags: , , , , , ,

How to Create Valid and Trusted SSL Certificate (Wildcard) for Development

For development purpose, sometime you need trusted SSL certificate that won’t give you certificate validation error. To avoid this problem, you can buy valid certificate from trusted CA. Another way is to create your own. This will guide you how to create trusted root certificate authority and self-signed certificate.


Following are required tools:

  • makecert.exe
  • pvk2pfx.exe

Both of these files can be found in your Microsoft SDKs folder, or try search in one of the following folder. If your machine is 32-bit, search under “Program Files (x86)” folder instead.

  • C:\Program Files\Microsoft SDKs\Windows\
  • C:\Program Files\Microsoft Visual Studio 8\
  • C:\Program Files\Microsoft Visual Studio 11.0\
  • C:\Program Files\Windows Kits\
  • C:\Program Files\Microsoft.NET\SDK\
  • C:\Program Files (x86)\Microsoft Visual Studio 9.0\
  • C:\Program Files (x86)\Microsoft Visual Studio 8\


It’s a good idea to create a new folder and place all files in the new folder. When running the commands to create the certificates, run it under the new folder as well.

Root Certificate Authority

C:\DevCert> makecert.exe -r -n "CN=dev.root" -pe -sv dev.root.pvk -a sha1 -len 2048 -b 01/01/2014 -e 12/31/2200 -cy authority dev.root.cer
C:\DevCert> pvk2pfx.exe -pvk dev.root.pvk -spc dev.root.cer -pfx dev.root.pfx

You can change certificate name, valid to and valid from dates (-n “CN=dev.root”, -b 01/01/2014, -e 12/31/2200, respectively), to whatever you like.
You may be prompted to create a password. This is the password to your private key.

This command will generate 3 certificates:

  • dev.root.cer (certificate)
  • dev.root.pvk (private key)
  • dev.root.pfx (certificate containing private key)

Install “dev.root.cer” root certificate to the store (Computer Account), under “Trusted Root Certification Authorities” folder.

SSL Certificate

C:\DevCert> makecert.exe -iv dev.root.pvk -ic dev.root.cer -n "" -pe -sv -a sha1 -len 2048 -b 01/01/2014 -e 12/31/2200 -sky exchange -eku
C:\DevCert> pvk2pfx.exe -pvk -spc -pfx

You can change certificate name, valid to and valid from dates (-n “”, -b 01/01/2014, -e 12/31/2200, respectively), to whatever you like.
You may be prompted to create a password. This is the password to your private key.

This command will generate 3 certificates:

  • (certificate)
  • (private key)
  • (certificate containing private key)

Wildcard Certificate

You can create a wilcard certificate by prepend “*” (asterisk) on certificate name, for example:

C:\DevCert> makecert.exe -iv dev.root.pvk -ic dev.root.cer -n "CN=*" -pe -sv -a sha1 -len 2048 -b 01/01/2014 -e 12/31/2200 -sky exchange -eku


In Certificate snap-in of Management Console (mmc):

  • For root CA certificate, “dev.root.cer” must be imported into “Trusted Root Certification Authorities” folder.
  • For regular (or wildcard) certificate, “” must be imported into “Personal” folder.

SSL / TLS Usage

To use certificate as SSL certificate, the CN name must match host name of the site. For example, if the site has host name “”, the certificate CN’s name must also be “”.

To use wildcard certificate in multiple sites as SSL certificate for the same IP address, it must have valid host name (ie, * With this approach, each site using the wildcard certificate must have different host name (ie, and


Posted by on August 13, 2014 in General


Tags: , , , ,

Windows Identity Foundation (WIF): A Potentially Dangerous Request.Form Value Was Detected from the Client (wresult=”<trust:RequestSecuri…")


On WIF 3.5, the token is sent in XML-like format, contains tags. The error is caused by request validation in ASP.NET feature to reject request with any tag. This feature prevents cross-site scripting attack (XSS).

Quick Workaround

To workaround this issue, add the following config in your ASP.NET application’s web.config:

    <httpRuntime requestValidationMode="2.0" />

This tells the ASP.NET to only perform request validation on .aspx pages – (2.0 represents ASP.NET 2.0). The request validation will not apply to all other pages / routings, so if you are on ASP.NET MVC (2, 3 or 4), disabling this open your application to the cross-site scripting attack.


To properly handle the exception error, create a class to validate the request.

This is what I have on my ASP.NET MVC 4.0


    <httpRuntime requestValidationType="WsFederationRequestValidator" />

Request validator class

public class WsFederationRequestValidator : RequestValidator
    protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
        validationFailureIndex = 0;
        if (requestValidationSource == RequestValidationSource.Form && !String.IsNullOrEmpty(collectionKey) && collectionKey.Equals(WSFederationConstants.Parameters.Result, StringComparison.Ordinal))
            var _unvalidatedFormValues = System.Web.Helpers.Validation.Unvalidated(context.Request).Form;

            SignInResponseMessage _message = WSFederationMessage.CreateFromNameValueCollection(WSFederationMessage.GetBaseUrl(context.Request.Url), _unvalidatedFormValues) as SignInResponseMessage;

            if (_message != null)
                return true;

        return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
Leave a comment

Posted by on June 12, 2013 in General


Tags: , , ,

%d bloggers like this: