How to use System.IdentityModel in own client-server application

给你一囗甜甜゛ 提交于 2019-12-02 17:18:57
dtb

My Google foo was indeed weak. The answer is right behind the link in my question. So here are a couple of links to this blog in case somebody has the same question eventually.

First, you should try to understand "that claim set stuff":

Then, you need to know where claim sets come from:

Armed with this knowledge, it actually becomes quite simple.

If I understand it correctly, the basic workflow would be something like this:

  1. Client creates a SecurityToken using a SecurityTokenProvider
  2. Client serializes the SecurityToken using a SecurityTokenSerializer
  3. Server deserializes the SecurityToken using a SecurityTokenSerializer
  4. Server creates IAuthorizationPolicys using a SecurityTokenAuthenticator
  5. Server creates AuthorizationContext from IAuthorizationPolicys
  6. Done

Example:

// Create the SecurityTokenProvider
var p = new UserNameSecurityTokenProvider("username", "password");

// Get the SecurityToken from the SecurityTokenProvider
var t = p.GetToken(TimeSpan.FromSeconds(1.0)) as UserNameSecurityToken;

// ... transmit SecurityToken to server ...

// Create the SecurityTokenAuthenticator
var a = new CustomUserNameSecurityTokenAuthenticator(
    UserNamePasswordValidator.None);

// Create IAuthorizationPolicies from SecurityToken
var i = a.ValidateToken(t);

// Create AuthorizationContext from IAuthorizationPolicies
var c = AuthorizationContext.CreateDefaultAuthorizationContext(i);
ShowClaims(c.ClaimSets);

For X509SecurityTokens use a X509SecurityTokenProvider/Authenticator. For WindowsSecurityTokens there's a WindowsSecurityTokenAuthenticator but not a provider; instead, use the WindowsSecurityToken constructor:

var t = new WindowsSecurityToken(WindowsIdentity.GetCurrent());

This works quite well. The only thing I omitted so far above is the token serialization. There is a SecurityTokenSerializer class which has one implementation in the .NET framework: the WSSecurityTokenSerializer class which comes with WCF.

Serializing UserNameSecurityTokens and X509SecurityTokens works like a charm (haven't tried deserialization), but WindowsSecurityTokens are apparently not supported by the serializer. This leaves me with the two authentication methods that I already have (certificates and username/password) and, as I didn't want that AuthorizationContext anyway, I'll stick with what I have :)

I don't have the reputation to post a comment to the existing solution, but I'd like to post the new URLs to the blogs listed in the solution, since those don't work anymore. If someone can change this to a comment, I'd be much obliged.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!