Welcome to the first part of the tutorial for Security Token Service deployment and usage in ASP.NET.
This tutorial comes with compiled STS, associated services, and Test Application installer for your convenience however I have also included sources in a form of Visual Studio project.
The tutorial is based on this sources but in can also be used to give you an insight into the concept of STS as an integrated security sollution.
This tutorial comes with compiled STS, associated services, and Test Application installer for your convenience however I have also included sources in a form of Visual Studio project.
The tutorial is based on this sources but in can also be used to give you an insight into the concept of STS as an integrated security sollution.
Full installer can be downloaded here:
STS_Setup
STS_Setup
Source Code is available here:
STS_Sources
STS_Sources
What is Security Token Service?
Security Token Service (STS) acts as an ideal method for providing a common access and authorization control infrastructure. It is the ideal solution if web services need to verify clients’ identities and rights in heterogeneous environments using many different security domains, user databases etc.
STS evaluates user credentials (of any type) and issues Security Tokens that are an undeniable confirmation that the user is valid within the whole domain for which the token was issued.
These tokens are then used for communication between client application and services. They provide maximum safety since they are very secure (signed and encrypted) and do not contain vulnerable user data (such as passwords). Apart from that Security Tokens contain so called claims. These claims can store any user data such as personal information, roles, permissions etc. that can be used by the services that operate on the token for various purposes.
STS is deployed as a separate web service that issues tokens over SLL protocol (HTTPS).
STS is deployed as a separate web service that issues tokens over SLL protocol (HTTPS).
Deployment and Configuration of STS Service
Security Token Service for the purpose of this tutrial can deployed using provided installer application or can be build from sources (Visual Studio Solution also included). If installef rom the Installer it is by default placed in “STSService” virtual directory of IIS web server. If you are using sources you might have to manually create webservices corresponding to sollution project’s (STSService & WCFService).
After setup you can go to web browser and type in the following address to see if the STS is working properly:
Service will not by fully functional out of the box. It will require initial configuration described in the following parts. In spite of that, you can refer to the address above anytime to see if it is working. You should get a standard WCF service webpage if everything is correct.
Certificates
After proper installation STS needs to be provided with a valid certificate(s). Certificates are used for three purposes:
- Secure https communication (SSL)
- Signing tokens
- Encrypting tokens (can be turned off)
You can use three different certificates thus increasing security for each task as well as use one certificate for all tasks.
It is strongly suggested that certificates in production environment are valid certificates issued by some existing legitimate certificate center.For development and testing purposes self-signed certificates may be used, maintaining the same functionality. Self-signed certificates are issued using IIS web server manager application or makecert.exe application. Method is irrelevant. Just make sure generated certificate is issued for a proper domain name (common name must be correct).
It is strongly suggested that certificates in production environment are valid certificates issued by some existing legitimate certificate center.For development and testing purposes self-signed certificates may be used, maintaining the same functionality. Self-signed certificates are issued using IIS web server manager application or makecert.exe application. Method is irrelevant. Just make sure generated certificate is issued for a proper domain name (common name must be correct).
Generated certificates should be placed in following stores of the Local Machine (Computer) account as well as Personal:
- My (Personal)
- Trusted Root Certification Authorities
Another important thing is that a private key of the certificate needs to have proper access rights applied. Since it will be used by application running on IIS, its user has to have read access (typically IIS_ISUSR, NETWORK SERVICE or ASPNET – depending on IIS version). Please make double check which rights are valid for your computer configuration.
In case you do not want to bother with specific rights setting read rights for ‘Everyone’ should do the trick, although remember it is not regarded as a safe practice.
Sometimes when it is not possible to set rights from MMS or when STS keeps throwing “Keyset does not exist” exception it is necessary to set private key rights manually. In order to do this you need to locate proper file on the disk using FindPrivateKey.exeapplication and set its rights as mentioned above.
Example usage of FindPrivateKey.exe:
Example usage of FindPrivateKey.exe:
FindPrivateKey My LocalMachine -n “CN=John Doe”
Example output:
C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys\9e7f481ca4127144bc75102dabb32ad0_c18e0de9-0e80-4436-920c-4ab1cae7939a
Further description of this tool can be found here:
http://msdn.microsoft.com/en-us/library/ms732026.aspx
http://msdn.microsoft.com/en-us/library/ms732026.aspx
Membership Provider
Security Token Service uses pluggable Membership providers that supply necessary user credentials validation. This way it does not have to rely on one source of users but can have many different easily interchangeable sources. MembershipProvider must be delivered as a dll library and added in STS web.config file.
Properly written MembershipProvider inherits from System.Web.Security.MembershipProvider abstract class.
Methods that need to be overridden are at least:
Methods that need to be overridden are at least:
- ValidateUser(string user, string pass)
- GetUser(string userName, bool isOnline)
It is highly recommended that following properties have set proper values since they might be used when presenting provider within client application UI:
- Name
- Description
Compiled dll library must be added to STS in web.config assemblies section.
Example:
Example:
Last but not least MembershipProvider has to be registered in section in the following way:
There already is a MembershipProvider included in the STS installation. By default it validates credentials by matching username and password. If they are the same access is granted. This behaviour can be changed but you would have to modify MembershipProvider in included sources and rebuild the project to generate new dll’s.
Role Provider
Functionality of a RoleProvider is connected mainly with supplying STS with roles for a given user. STS refers to this provider to obtain user roles that are later embedded within the Security Token. RoleProvider must be delivered as a dll library and added in STS web.config file.
Properly written RoleProvider inherits from System.Web.Security.RoleProvider abstract class.
Methods that need to be overridden are at least:
Methods that need to be overridden are at least:
- GetRolesForUser(string username)
It is highly recommended that following properties have set proper values since they might be used when presenting provider within client application UI:
- Name
- Description
Compiled dll library must be added to STS in web.config assemblies section in the following way:
Last but not least RoleProvider has to be registered in section.
There already is a RoleProvider in the STS installation but it does not return any roles or rights. You could modify that behaviour again in the same way as in case of MembershipProvider by modifying sources and recreating dll libraries.
Windows Authentication
This type of authentication is handled automatically by STS service. Endpoint that needs to be utilized when using domain identity is described in the following section.
It is mandatory that the client host is allowed to delegate Identity to a remote service. This should be configured in the domain controller. Otherwise STS service will be accessed using anonymous user which may lead to authentication errors. Moreover setting in client application is needed.
In my design of STS Windows authentication can be used concurrently with membership providers. STS can be forced to perform authentication of domain users using currently active membership provider. So instead of being validated only by the domain, credentials are additionally checked by the provider.
This feature can be turned on or of using following entry in section (although I recommend to leave it turned off at the beginning until you manage to have a full working setup):
Mappings of AD users to external set accessed by membership provider are done using user SID. ValidateUser method of the provider must be able to properly check user mapping when invoked in the following way way: ValidateUser(null, sid)
Brief configuration file description
This section describes some critical parts of STS configuration file (web.config)
First important part involves certificates setting.
Issuer name – name identifying your Security Token Service (must be set).
SigningCertificateName – common name (CN) of a certificate used for signing tokens. EncryptingCertificateName – common name (CN) of a certificate used for encrypting tokens. If this value is commented Security Tokens will not be encrypted but you have to keep in mind that only tokens with Bearer keys may be sent unencrypted. You will have to change client configuration and form RequestSecurityToken properly to expect Bearer instead of Symmetric (default) or Asymmetric keys. Suggested practice is to leave this value uncommented and use Symmetric Keys (default) as it provides increased security level.
Friendly names – sometimes there are more than one certificates with the same CN. Friendly names are used to provide deeper distinction between certificates to find the proper one.
Friendly names – sometimes there are more than one certificates with the same CN. Friendly names are used to provide deeper distinction between certificates to find the proper one.
This is the logging section of Security Token Service. You can change initializeData parameter to whatever directory you like the log to go to. Logs are best viewed using SvcTraceViewer.exe application.
Allowed clients section is used to validate incoming request. With every request for a security token an AppliesTo parameter must be set. This value is extracted in STS and matched against a list of values from allowedClients section. Should there be no match client is rejected and no token is issued. You can disable this additional validation by setting active=”false”.
In client application relevant AppliesTo parameter is taken from .
In client application relevant AppliesTo parameter is taken from .
There are two crucial endpoints used by STS. One is used for Windows authentication and the other is used when sending username/password credentials. You may change binding names and addresses as you wish but keep in mind that relevant changes must be done in client and services configuration files. Bindings must always be of type ws2007HttpBinding.
Configuration of Client Application
Certificates In order to communicate with STS your client application needs to have the same certificates that are used by STS in https communication installed. Make sure they are stored in following certificates stores for Local Machine (Computer) account:
- My (Personal)
- Trusted Root Certification Authorities
Also be advised that specific permissions must be set exactly the same way as in case of STS service certificates configuration. Application configuration Configuration of a client application is quite straightforward. All you need to do is set client endpoint addresses and binding according to whatever was set in Security Token Service configuration. Example of application bindings configuration:
algorithmSuite="Default" establishSecurityContext="true" />
Example of application endpoints configuration:
Of course any standard parameters like timeouts, quotas etc. can also be set on bindings or endpoints as long as they are in compliance with those set in Security Token Service.
Enabling Forms Authentication
Forms authentication is necessary for proper collaboration using tokens in client application as the user must have some way of providing credentials. I assume you already know how to create your own controls in Visual Studio web projects. In order to enable it make sure that you have proper lines uncommented in configuration file.
Image 3: Minimalistic login form
One more important parameter in client application that needs to be mentioned is located in configuration file under .
ServicesDomain parameter from configuration is used as AppliesTo parameter when forming RequestSecurityToken. Unless this validation type is turned off, this parameter is checked against allowedClients section of STS. This is an additional security feature. For extended information on this please refer to STS configuration section.
Enabling Windows Authentication
To enable authentication using windows identity change authentication mode to Windows in application’s web.config file:
Configuration of external Service
Certificates
In order to read a Security Token properly external service needs to have the same certificates that are used by STS for signing and encrypting tokens. Make sure they are stored in following certificates stores for Local Machine (Computer) account:
- My (Personal)
- Trusted Root Certification Authorities
Moreover double check that specific permissions are set in exactly the same way as in case of STS Service and client application certificates configuration. If tokens from STS are not encrypted there is no need to install encrypting certificate on the machine where service resides.
Configuration file
If you are sending tokens by any other means than WCF channel (i.e. as request parameter or inside request headers) than no additional configuration is necessary for this service. Please refer to later part of this document where manual token de-serialization and reading is described. However, if you wish to use WCF channel you need to make your service aware that it needs to accept tokens through exposed endpoint. Below is the example of proper service configuration. Adding Microsoft.Identity model section (this is mandatory):
Example endpoints and bindings (you can either communicate over https or with certificate due to the fact that tokens may be sent only using a channel that is somehow secured) that need to be specified within section:
Bindings must always be of type ws2007federationHttpBinding. issuedKeytype – informs which Key type does the service expect. issuedTokenType – informs what is the type of the token that the service expects, leave this at default value.claimTypeRequirements – informs us what claims does the service expect, which are obligatory and which are not. issuer address and issuerMetadata must point to STS used to issue tokens which are consumed by the service. Next you must remember to specify proper binding behavior indicating a certificate that was used for token signing (also in section). You need to provide common name in findValue parameter and leave rest at default values.
Finally need to specify valid audienceUriMode (service address) or set audienceUriMode=”Never” to bypass this validation part. This setting is not a crucial security part so it can be safely turned off.
IIS Settings
The thing that needs to be kept in mind when configuring IIS web server is to allow HTTPS communication on respective virtual directories as well as to accept SSL Certificates.
Moreover you should double check that the Application Pool for STS is set to .NET Framework 4.0 and that IIS website accepts SSL certificates. This should be done with client application, Security Token Service and remote wcf services that will operate on SSL.
Moreover you should double check that the Application Pool for STS is set to .NET Framework 4.0 and that IIS website accepts SSL certificates. This should be done with client application, Security Token Service and remote wcf services that will operate on SSL.
Moreover in some cases you need to manually change authentication methods in IIS to allow either Forms or Windows authentication.
It also happens sometimes that after above configuration you might get errors with loading some dlls in STS. This happens on 64-bit systems. To resolve this error, set your sts application pool in IIS to allow 32bit applications. Open up IIS Manager, right click on the app pool, and select Advanced Settings (See below)
Requesting Security Token
Requesting a Token inside an application is done by preparing so called RequestSecurityToken and sending it to STS using previously configured channel (see previous sections).
A typical request code looks like this:
As you can see specific token parameters are set within RequestSecurityToken. Response is captured both – as an issued SecurityToken and RequestSecurityTokenResponse.
Issued token is of type System.IdentityModel.Tokens.SecurityToken and can be cast to System.IdentityModel.Tokens.GenericXmlSecurityToken which allows us to obtain token in a form of an xml like this:
It is worth to mention that Intergraph’s Security Token Service is designed to be able to include DisplayTokens which do not require as much overhead when in case of reading standard tokens.
Please refer to the description of RequestSecurityToken and RequestSecurityTokenResponse classes for more info about specific parameters.
Sending Security Token over WCF Channel
If you need to send token over a WCF channel a proper binding and endpoint configuration that is equivalent to the one set inside your service configuration.
Example of properly configured sections:
After correct configuration you can send token with a channel using these configured endpoints.
Sending over https:
After this you should have a channel with properly established configuration.
Sending a Security Token in HTTP Request
Sending a token with http request is quite easy. You can do this either by adding token xml as a request parameter or by adding it to http headers. In client application token can be sent using Authorization header after being previously encoded as base64 string:
Consuming Token within external service
When not using WCF channel (i.e. when the token is received through headers or as a request parameter) you need to manually deal with all the aspects of de-serializing tokens.
Below is the example of a method that fulfills that task perfectly. It takes following parameters:
Below is the example of a method that fulfills that task perfectly. It takes following parameters:
tokenXml – security token in a form of an xml string, usually obtained from
(Authentication.Token as GenericXmlSecurityToken).TokenXml.OuterXml;
stsSignatureName – common name (CN) of a certificate used for signing token
thumbprint – thumbprint of a certificate used by STS to sign token
encryptionName – common name (CN) of a certificate used by STS to encrypt token (may be null in case tokens are not encrypted)
(Authentication.Token as GenericXmlSecurityToken).TokenXml.OuterXml;
stsSignatureName – common name (CN) of a certificate used for signing token
thumbprint – thumbprint of a certificate used by STS to sign token
encryptionName – common name (CN) of a certificate used by STS to encrypt token (may be null in case tokens are not encrypted)
Method returns a set of claims that were read from the Token.
Troubleshooting
Here are some typical exceptions and log entries that you might get when trying to connect to STS service. Along with possible solutions.
Web browser output:
The protocol ‘https’ is not supported
You must add https site binding in IIS Server. To do that right click on “Default Web Site” tree entry in IIS Manager and select “Edit Bindings”. Make sure you select proper certificate for https binding.
Could not load file or assembly ‘xxxxx′ or one of its dependencies. An attempt was made to load a program with an incorrect format.
Could not load file or assembly ‘xxxxx′ or one of its dependencies. The system cannot find file specified.
Could not load file or assembly ‘xxxxx′ or one of its dependencies. The system cannot find file specified.
To resolve this error, set STS application pool in IIS to allow 32bit applications.
Open up IIS Manager, right click on the app pool, and select Advanced Settings (See IIS Settings section)
Open up IIS Manager, right click on the app pool, and select Advanced Settings (See IIS Settings section)
STS Logs:
Keyset does not exist
This is a common certificate error, make sure proper right are set to the certificates.
If everything seems to be correct make sure that proper users have access to certificates private key. It may happen during import or certificate copying that private key does not get copied alongside. You will need to make sure that private key resides in \Microsoft\Crypto\RSA\some_long_id\ folder.
In Windows 7 for example path would be C:\Users\Username\AppData\Microsoft\Crypto\RSA\some_long_id\
The security token could not be authenticated or authorized.
Invalid credentials are used to login to Security Token Service
ID4175: The issuer of the security token was not recognized by the IssuerNameRegistry.
To accept security tokens from this issuer, configure the IssuerNameRegistry to return a valid name for this issuer.
To accept security tokens from this issuer, configure the IssuerNameRegistry to return a valid name for this issuer.