RSS

Tag Archives: wif

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/

 
Leave a comment

Posted by on May 28, 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: , , , , , , ,

Learning Paths

With so many tutorials, articles and resources available out there on the Internet, learning new programming language, framework and library become much more easier. However, as much as its advantage, readily available resources have also become its own problem: where should I start?

With so many options available, it can be confusing to even start learning. I present you my learning paths to solve this problem. Learning paths will guide you through learning programs for each subject of your interests. Think of this as a curriculum to the degree you want to get.

Most of the courses are from Pluralsight.com, but this learning paths are not limited to just Pluralsight.com. I also include some free courses from other sources. While I understand that you may have to pay for some of these courses, I can assure you that paying the subscription is worth it (especially Pluralsight!).

I will update this learning paths to include more subjects and courses in the future. Stay tuned!

Android

Level Course
0100 Get the Android SDK (http://developer.android.com/sdk/index.html)
0101 Prerequisite: 0100
Getting Started (http://developer.android.com/training/index.html)
0102 Introduction to Android Development (http://pluralsight.com/training/Courses/TableOfContents/android-intro)
0200 Prerequisite: 0101 or 0102
Android Async Programming and Services (http://pluralsight.com/training/Courses/TableOfContents/android-services)

AngularJS

Level Course
0100 AngularJS Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/angularjs-fundamentals)
0200 Prerequisite: 0100
AngularJS In-Depth (http://pluralsight.com/training/Courses/TableOfContents/angularjs-in-depth)
0201 Prerequisite: 0100
Testing AngularJS From Scratch (http://pluralsight.com/training/Courses/TableOfContents/testing-angularjs-from-scratch)

ASP.NET MVC

Level Course
0100 ASP.NET MVC Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/aspdotnet-mvc)
0200 Prerequisite: 0100
ASP.NET MVC 5 Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/aspdotnet-mvc5-fundamentals)

ASP.NET Web API

Level Course
0100 Introduction to the ASP.NET Web API (http://pluralsight.com/training/Courses/TableOfContents/aspnetwebapi)
0200 Prerequisite: 0100
Web API v2 Security (http://pluralsight.com/training/Courses/TableOfContents/webapi-v2-security)
0201 Prerequisite: 0100
Web API Design (http://pluralsight.com/training/Courses/TableOfContents/web-api-design)

C#

Level Course
0100 C# Basic (http://csharp-station.com/Tutorial/CSharp)
0101 C# From Scratch (http://pluralsight.com/training/Courses/TableOfContents/csharp-from-scratch)
0102 Prerequisite: 0101
C# From Scratch – Part 2 (http://pluralsight.com/training/Courses/TableOfContents/csharp-from-scratch-part2)
0200 Prerequisite: 0100 or 0102
Object-Oriented Programming Fundamentals in C# (http://pluralsight.com/training/Courses/TableOfContents/object-oriented-programming-fundamentals-csharp)

Entity Framework

Level Course
0100 Getting Started with Entity Framework 5 (http://pluralsight.com/training/Courses/TableOfContents/entity-framework5-getting-started)
0200 Prerequisite: 0100
Entity Framework Code First Migrations (http://pluralsight.com/training/Courses/TableOfContents/efmigrations)

JavaScript & jQuery

Level Course
0100 W3Schools’s JavaScript Tutorial (http://www.w3schools.com/js/default.asp)
0101 JavaScript Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/jscript-fundamentals)
0120 Prerequisite: 0100 or 0101
DO Factory’s JavaScript + jQuery Design Pattern Framework – JavaScript & Pattern Essentials (http://www.dofactory.com/products/javascript-jquery-design-pattern-framework)
0200 Prerequisite: 0100 or 0101
JavaScript Design Patterns (http://pluralsight.com/training/Courses/TableOfContents/javascript-design-patterns)
0300 Prerequisite: 0200
jQuery Fundamentals (http://pluralsight.com/training/Courses/TableOfContents/jquery-fundamentals)

WIF, Claims-based Identity, OAuth2

Level Course
0100 Introduction to Identity and Access Control in .NET 4.5 (http://pluralsight.com/training/Courses/TableOfContents/iac-intro)
0200 Prerequisite: 0100
Identity and Access Control in ASP.NET 4.5 (http://pluralsight.com/training/Courses/TableOfContents/iac-aspnet)
0201 Prerequisite: 0100
Identity and Access Control in WCF 4.5 (http://pluralsight.com/training/Courses/TableOfContents/iac-wcf)
0202 Prerequisite: 0100
Web API v2 Security (http://pluralsight.com/training/Courses/TableOfContents/webapi-v2-security)
0300 Prerequisite: 0200 or 0201 or 0202
Introduction to OAuth2, OpenID Connect and JSON Web Tokens (JWT) (http://pluralsight.com/training/Courses/TableOfContents/oauth2-json-web-tokens-openid-connect-introduction)
 
1 Comment

Posted by on September 15, 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: , , ,

An Unsecured or Incorrectly Secured Fault Was Received From The Other Party

an-unsecured-or-incorrectly-secured-fault-was-received-from-the-other-party

The inner FaultException goes something like: System.ServiceModel.FaultException: The message could not be processed because the action ‘http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT&#8217; is invalid or unrecognized.

It’s caused by WCF service configured to not communicate in WS-SecureConversation while the client is. Or vice versa. In my case, the client is an ASP.NET MVC 4 application that is trying to pass token (identity delegation) over to a WCF 4.5 service through WSTrustChannelFactory protocol.

Both of the client and the service must be configured to use same security context. If you want to turn WS-SecureConversation off, turn off on both config. Same applies to turning on WS-SecureConversation.

<ws2007FederationHttpBinding>
    <binding>
        <security mode="TransportWithMessageCredential">
            <message establishSecurityContext="false" />
        </security>
    </binding>
</ws2007FederationHttpBinding>
 
1 Comment

Posted by on May 28, 2013 in General

 

Tags: , , ,

WCF Client Config Template with Identity Delegation (WSTrust)

A minimal config for a client (for example, ASP.NET MVC application, ASP.NET Web Form application, or another WCF service application), that is a relying party to WIF (or any STS), to consume a WCF service (SOAP) using Identity Delegation (with WSTrust protocol). Identity Delegation allows the client to call WCF service and pass in the claims as if it’s being called by the user of the client. Compare Identity Delegation to Trusted Subsystem.

This config is auto-generated with “Add Service Reference” wizard from WCF service config in WCF Config Template for Identity Delegation with WIF.

This config DOES NOT include setting integrating the client with WIF. For example of this, see WIF 3.5 Relying Party Config Template.

Note that:
http://localhost:11000 is the Secure Token Service (STS) URL.
http://localhost:58829 is service’s endpoint address.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <ws2007FederationHttpBinding>
                <binding name="WS2007FederationHttpBinding_IService">
                    <security>
                        <message>
                            <issuer address="http://localhost:11000/Issue.svc" binding="ws2007HttpBinding"
                                bindingConfiguration="http://localhost:11000/Issue.svc">
                                <identity>
                                    <dns value="IdentityTKStsCert" />
                                </identity>
                            </issuer>
                            <issuerMetadata address="http://localhost:11000/Issue.svc/mex" />
                            <tokenRequestParameters>
                                <trust:SecondaryParameters xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
                                    <trust:KeyType xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey</trust:KeyType>
                                    <trust:KeySize xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">256</trust:KeySize>
                                    <trust:KeyWrapAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p</trust:KeyWrapAlgorithm>
                                    <trust:EncryptWith xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptWith>
                                    <trust:SignWith xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2000/09/xmldsig#hmac-sha1</trust:SignWith>
                                    <trust:CanonicalizationAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/10/xml-exc-c14n#</trust:CanonicalizationAlgorithm>
                                    <trust:EncryptionAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptionAlgorithm>
                                </trust:SecondaryParameters>
                            </tokenRequestParameters>
                        </message>
                    </security>
                </binding>
            </ws2007FederationHttpBinding>
            <ws2007HttpBinding>
                <binding name="http://localhost:11000/Issue.svc">
                    <security>
                        <message clientCredentialType="Certificate" negotiateServiceCredential="false" />
                    </security>
                </binding>
            </ws2007HttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:58829/Service.svc" binding="ws2007FederationHttpBinding"
                bindingConfiguration="WS2007FederationHttpBinding_IService"
                contract="ServiceReference.IService" name="WS2007FederationHttpBinding_IService">
                <identity>
                    <certificate encodedValue="AwAAAAEAAAAUAAAAQKHSYiv" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

To create ChannelFactory and pass in the secured token from the client:

// Get the token
WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory( stsBinding, stsAddress );
WSTrustChannel channel = (WSTrustChannel) trustChannelFactory.CreateChannel();
RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Issue);
rst.AppliesTo = new EndpointAddress(serviceAddress);
RequestSecurityTokenResponse rstr = null;
SecurityToken token = channel.Issue(rst, out rstr);

// Use the token, pass in to WCF service
IHelloService serviceChannel = channelFactory.CreateChannelWithIssuedToken<IHelloService>( token ); serviceChannel.Hello(“Hi!”);

Additional resource: MSDN WSTrustChannelFactory and WSTrustChannel

 
Leave a comment

Posted by on May 28, 2013 in General

 

Tags: , , , , , ,

WCF Config Template for Identity Delegation with WIF 3.5

A minimal config for WCF (.Net 4.5) service. The binding allows Identity Delegation with WIF 3.5. For WIF 4.5, use Identity and Access Tool.

The config template includes WIF configuration. It’s necessary because the WCF service, in this case, is a relying party.

Note that:
http://localhost:11000 is the Secure Token Service (STS) URL.
http://localhost:58829 is service’s endpoint address (the relying party).

The downside with this is that you can’t invoke the service with WCF Test Client. It will complain about “SOAP security negotiation failed.” with inner exception “Client certificate is not provided”. This is because WCF Test Client is not configured with SOAP security negotiation (maybe there’s a way?).

<?xml version="1.0"?>
<configuration>
    <configSections>

        <!--For WIF 3.5-->
        <section name="microsoft.identityModel" type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

    </configSections>

    <system.web>
        <compilation debug="true" targetFramework="4.5" />
    </system.web>

    <system.serviceModel>
        <bindings>

            <!--For Identity Delegation-->
            <ws2007FederationHttpBinding>
                <binding name="ws2007FederationHttpBinding_IService">
                    <security mode="Message">
                    <!--TransportWithMessageCredential requires HTTPS-->
                    <!--<security mode="TransportWithMessageCredential">-->
                        <message>
                            <issuerMetadata address="http://localhost:11000/Issue.svc/mex" />
                        </message>
                    </security>
                </binding>
            </ws2007FederationHttpBinding>

        </bindings>

        <services>

            <!--For Identity Delegation-->
            <service name="Acme.AccountService.Service" behaviorConfiguration="AcmeService.Service_Behavior">
                <endpoint binding="ws2007FederationHttpBinding" bindingConfiguration="ws2007FederationHttpBinding_IService" contract="Acme.AccountService.Contracts.IService" />
            </service>

        </services>

        <behaviors>
            <serviceBehaviors>

                <!--For Identity Delegation-->
                <behavior name="AcmeService.Service_Behavior">
                    <federatedServiceHostConfiguration />
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                    <serviceCredentials>
                        <serviceCertificate findValue="40A1D2622BFBDAC80A38858AD8001E09454987AD" storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" />
                    </serviceCredentials>
                    <serviceAuthorization principalPermissionMode="Always" />
                </behavior>

            </serviceBehaviors>
        </behaviors>

        <!--For Identity Delegation-->
        <extensions>
            <behaviorExtensions>
                <add name="federatedServiceHostConfiguration" type="Microsoft.IdentityModel.Configuration.ConfigureServiceHostBehaviorExtensionElement, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            </behaviorExtensions>
        </extensions>

        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>

    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>

    <!--For WIF 3.5-->
    <microsoft.identityModel>
        <service saveBootstrapTokens="true">
            <audienceUris>
                <add value="http://localhost:58829/" />
            </audienceUris>

            <federatedAuthentication>
                <wsFederation passiveRedirectEnabled="true" issuer="http://localhost:11000/Issue.svc" realm="http://localhost:58829/" requireHttps="false"/>
                <cookieHandler requireSsl="false"/>
            </federatedAuthentication>

            <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
                <trustedIssuers>
                    <add thumbprint="40A1D2622BFBDAC80A38858AD8001E09454987AD" name="http://localhost:11000/Issue.svc"/>
                </trustedIssuers>
            </issuerNameRegistry>
        </service>
    </microsoft.identityModel>
</configuration>
 
1 Comment

Posted by on May 28, 2013 in General

 

Tags: , , , ,

 
%d bloggers like this: