RSS

Tag Archives: security

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:

http://leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/

Advertisements
 
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: http://docs.mongodb.org/manual/administration/security/

 
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

[TestMethod]
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

oauth2-flows-1

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

Steps:

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

Implicit Flow

oauth2-flows-2

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).

Steps:

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

Resource Owner Credential Flow

oauth2-flows-3

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

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

Steps:

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

Client Credential Flow

oauth2-flows-4

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.

Steps:

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

Assertion Flow

oauth2-flows-5

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.

Steps:

  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.

Tools

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\

Preparation

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 "CN=dev.site" -pe -sv dev.site.pvk -a sha1 -len 2048 -b 01/01/2014 -e 12/31/2200 -sky exchange dev.site.cer -eku 1.3.6.1.5.5.7.3.1
C:\DevCert> pvk2pfx.exe -pvk dev.site.pvk -spc dev.site.cer -pfx dev.site.pfx

You can change certificate name, valid to and valid from dates (-n “CN=dev.site”, -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.site.cer (certificate)
  • dev.site.pvk (private key)
  • dev.site.pfx (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=*.dev.site" -pe -sv w.dev.site.pvk -a sha1 -len 2048 -b 01/01/2014 -e 12/31/2200 -sky exchange w.dev.site.cer -eku 1.3.6.1.5.5.7.3.1

Installation

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, “dev.site.pfx” 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 “dev.site”, the certificate CN’s name must also be “dev.site”.

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

 
2 Comments

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…")

windows-identity-foundation-wif-a-potentially-dangerous-request-form-value-was-detected-from-the-client-wresult

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:

<system.web>
    <httpRuntime requestValidationMode="2.0" />
</system.web>

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.

Solution

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

web.config

<system.web>
    <httpRuntime requestValidationType="WsFederationRequestValidator" />
</system.web>

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: , , ,

WCF Message and Transport Security

Transport

The encryption takes place when the message is about to send over, at transport layer.
Depends on the transport protocol, normally require HTTPS (if send over HTTP).

Message

The encryption takes place on the message itself, before it is sent.
For most part, it’s transport-independent.
More flexibility, you can use any type of security credential as long as client and service agree.

Code

<system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpEndpointBinding">
          <security mode="Transport">
          </security>
          <!--<security mode="Message">
          </security>-->
        </binding>
      </wsHttpBinding>
    </bindings>
</system.serviceModel>

Options the security mode are:

  • None
  • Message
  • Transport
  • Both
  • TransportWithMessageCredential
  • TransportCredentialOnly

More info on: What the difference between transport and message security?

 
Leave a comment

Posted by on June 3, 2013 in References

 

Tags: , ,

 
%d bloggers like this: