ASP.Net MVC and WCF Identity (Claims) Integration

We are creating a platform where the client is ASP.Net MVC one, using ASP Net Identity 2.0 for authentication and authorization (using claims), which works great on a web page.

We also have a WCF service that allows you to perform CRUD operations in a database (for several client applications) that receives requests from this ASP.Net MVC client. Since we want to verify (authenticate and authorize) the user before performing certain CRUD actions on the WCF side, we need to receive user complaints from the client and perform checks (preferably very clean, using headers or whatever that WCF can support this issue).

I was looking for different forums, but without a simple answer to this tutorial. Can anyone help on this?

Thanks, Nir.

+6
source share
1 answer

I like it:

in your implementation of IEndpointBehavior do this on the client side:

public object BeforeSendRequest(ref Message request, IClientChannel channel) { request.Headers.Add(MessageHeader.CreateHeader("token", "http://myurl.com/service/token", _theToken)); return null; } 

then at the end of the service add this to your ServiceAuthenticationManager

 public override ReadOnlyCollection<IAuthorizationPolicy> Authenticate( ReadOnlyCollection<IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message) { IPrincipal user = new MyUserPrincipal(null); if(_currentServiceContractType.GetInterfaces() .Any(x => x == typeof(IMySecuredService))) { var tokenPosition = message.Headers.FindHeader("token", "http://myurl.com/service/token"); if (tokenPosition >= 0 && tokenPosition <= 5) { var encryptedToken = message.Headers.GetHeader<string>(tokenPosition); if (!string.IsNullOrWhiteSpace(encryptedToken)) { var serializedToken = new MyEncryptionUtility().Decrypt(encryptedToken); var token = MyTokenSerializer.Deserialize(serializedToken); var expire = new DateTime(token.ValidToTicks); if (expire > DateTime.Now) { user = new MyUserPrincipal(token); } } } } message.Properties["Principal"] = user; Thread.CurrentPrincipal = user; return authPolicy; } 

This gives you the ability to use built-in claims or WIF claims authentication. Otherwise, it is very simple. A token is created by the service and sent to the client (network) and stored in a cookie. when there are any requests, the token is extracted from the cookie and then sent to the service, where inevitably you can start adding the permission service rather than doing it on the web / mvc side, making a much cleaner code base using every favorite friend, SOA> = :)

+1
source

Source: https://habr.com/ru/post/989066/


All Articles