SecurityTokenService Klass

Definition

Den abstrakta basklassen som definierar egenskaperna och metoderna för en säkerhetstokentjänst (STS).

public ref class SecurityTokenService abstract
public abstract class SecurityTokenService
type SecurityTokenService = class
Public MustInherit Class SecurityTokenService
Arv
SecurityTokenService

Exempel

Kodexemplen som används i ämnena SecurityTokenService tas från Custom Token exemplet. Det här exemplet innehåller anpassade klasser som möjliggör bearbetning av enkla webbtoken (SWT) och innehåller en implementering av en passiv STS som kan hantera en SWT-token. Ett exempel på hur du implementerar en aktiv STS kan du se Federation Metadata exemplet. Information om dessa exempel och andra exempel som är tillgängliga för WIF och var du kan ladda ned dem finns i WIF Code Sample Index. Följande kod visar implementeringen av en passiv STS med hjälp av SecurityTokenService klassen .

using System;
using System.IdentityModel;
using System.IdentityModel.Configuration;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;

namespace PassiveSTS
{
    /// <summary>
    /// Overrides the SecurityTokenService class to provide
    /// the relying party related information, such as encryption credentials to encrypt the issued
    /// token, signing credentials to sign the issued token, claims that the STS wants to issue for a 
    /// certain token request, as well as the claim types that this STS is capable
    /// of issuing.
    /// </summary>
    public class CustomSecurityTokenService : SecurityTokenService
    {
        // Certificate Constants
        private const string SIGNING_CERTIFICATE_NAME = "CN=localhost";
        private const string ENCRYPTING_CERTIFICATE_NAME = "CN=localhost";

        private SigningCredentials _signingCreds;
        private EncryptingCredentials _encryptingCreds;
        // Used for validating applies to address, set to URI used in RP app of application, could also have been done via config
        private string _addressExpected = "http://localhost:19851/";
        public CustomSecurityTokenService(SecurityTokenServiceConfiguration configuration)
            : base(configuration)
        {
            // Setup the certificate our STS is going to use to sign the issued tokens
            _signingCreds = new X509SigningCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SIGNING_CERTIFICATE_NAME));

            // Note: In this sample app only a si   ngle RP identity is shown, which is localhost, and the certificate of that RP is 
            // populated as _encryptingCreds
            // If you have multiple RPs for the STS you would select the certificate that is specific to 
            // the RP that requests the token and then use that for _encryptingCreds
            _encryptingCreds = new X509EncryptingCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, ENCRYPTING_CERTIFICATE_NAME));
        }

        /// <summary>
        /// This method returns the configuration for the token issuance request. The configuration
        /// is represented by the Scope class. In our case, we are only capable of issuing a token to a
        /// single RP identity represented by the _encryptingCreds field.
        /// </summary>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST</param>
        /// <returns></returns>
        protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
        {
            // Validate the AppliesTo address
            ValidateAppliesTo( request.AppliesTo );

            // Create the scope using the request AppliesTo address and the RP identity
            Scope scope = new Scope( request.AppliesTo.Uri.AbsoluteUri, _signingCreds );

            if (Uri.IsWellFormedUriString(request.ReplyTo, UriKind.Absolute))
            {
                if (request.AppliesTo.Uri.Host != new Uri(request.ReplyTo).Host)
                    scope.ReplyToAddress = request.AppliesTo.Uri.AbsoluteUri;
                else
                    scope.ReplyToAddress = request.ReplyTo;
            }
            else
            {
                Uri resultUri = null;
                if (Uri.TryCreate(request.AppliesTo.Uri, request.ReplyTo, out resultUri))
                    scope.ReplyToAddress = resultUri.AbsoluteUri;
                else
                    scope.ReplyToAddress = request.AppliesTo.Uri.ToString() ;
            }

            // Note: In this sample app only a single RP identity is shown, which is localhost, and the certificate of that RP is 
            // populated as _encryptingCreds
            // If you have multiple RPs for the STS you would select the certificate that is specific to 
            // the RP that requests the token and then use that for _encryptingCreds
            scope.EncryptingCredentials = _encryptingCreds;

            return scope;
        }
        /// <summary>
        /// This method returns the content of the issued token. The content is represented as a set of
        /// IClaimIdentity intances, each instance corresponds to a single issued token. Currently, the Windows Identity Foundation only
        /// supports a single token issuance, so the returned collection must always contain only a single instance.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST, we don't use this in our implementation</param>
        /// <returns></returns>
        protected override ClaimsIdentity GetOutputClaimsIdentity( ClaimsPrincipal principal, RequestSecurityToken request, Scope scope )
        {
            //
            // Return a default claim set which contains a custom decision claim
            // Here you can actually examine the user by looking at the IClaimsPrincipal and 
            // return the right decision based on that. 
            //
            ClaimsIdentity outgoingIdentity = new ClaimsIdentity();
            outgoingIdentity.AddClaims(principal.Claims);

            return outgoingIdentity;
        }
        /// <summary>
        /// Validates the appliesTo and throws an exception if the appliesTo is null or appliesTo contains some unexpected address.
        /// </summary>
        /// <param name="appliesTo">The AppliesTo parameter in the request that came in (RST)</param>
        /// <returns></returns>
        void ValidateAppliesTo(EndpointReference appliesTo)
        {
            if (appliesTo == null)
            {
                throw new InvalidRequestException("The appliesTo is null.");
            }

            if (!appliesTo.Uri.Equals(new Uri(_addressExpected)))
            {
                throw new InvalidRequestException(String.Format("The relying party address is not valid. Expected value is {0}, the actual value is {1}.", _addressExpected, appliesTo.Uri.AbsoluteUri));
            }
        }

    }
}

Följande kod visar hur du anropar en anpassad passiv STS för att bearbeta en WS-Federation begäran genom att anropa FederatedPassiveSecurityTokenServiceOperations.ProcessRequest(HttpRequest, ClaimsPrincipal, SecurityTokenService, HttpResponse) metoden från koden bakom i default.aspx.cs filen.

using System;
using System.IdentityModel.Services;
using System.Security.Claims;

namespace PassiveSTS
{
    public partial class _Default : System.Web.UI.Page
    {
        /// <summary>
        /// We perform the WS-Federation Passive Protocol processing in this method. 
        /// </summary>
        protected void Page_PreRender( object sender, EventArgs e ) 
        {
            FederatedPassiveSecurityTokenServiceOperations.ProcessRequest( Request, User as ClaimsPrincipal, CustomSecurityTokenServiceConfiguration.Current.CreateSecurityTokenService(), Response );
        }
    }
}

Kommentarer

Om du vill skapa en STS måste du härleda SecurityTokenService från klassen. I din anpassade klass måste du åtminstone åsidosätta GetScope metoderna och GetOutputClaimsIdentity . Med dessa åsidosättningar kan den STS som skapats med standardimplementeringen av alla andra metoder som definierats i klassen utfärda säkerhetstoken som svar på begäranden om säkerhetstoken (RST). Det innebär att problembindningen som definierats i WS-Trust-specifikationen implementeras. Den här bindningen implementeras i Issue -metoden. Ingen av de andra WS-Trust bindningar (Förnya, Avbryt och Verifiera) implementeras i standardfallet och ett lämpligt fel returneras till anroparen om en RST som motsvarar en av dessa bindningar påträffas. Du kan naturligtvis åsidosätta lämpliga metoder (Renew, Canceloch Validate) för att implementera dessa bindningar i din STS.

Important

Att implementera en produktionsklar STS innebär noggrann planering och betydande resurser för att minska de potentiella säkerhetsrisker som är förknippade med att exponera en sådan tjänst. De flesta utvecklare som använder Windows Identity Foundation (WIF) kommer att utveckla program som outsourcar identitetshantering till en STS i stället för att utveckla en STS själv. WIF tillhandahåller ett Visual Studio tillägg, identitets- och åtkomstverktyget för Visual Studio 2012, som hjälper utvecklare att testa lösningar i utvecklingsmiljön. Det här verktyget innehåller en STS, LocalSTS, som du kan konfigurera för att hantera specifika anspråk för det program som du utvecklar. Mer information om verktyget Identitet och åtkomst finns i Identity and Access Tool for Visual Studio 2012. I vissa scenarier LocalSTS kanske inte tillhandahåller de funktioner som krävs för att testa programmet på ett tillfredsställande sätt, till exempel i ett scenario som innebär att utveckla en anpassad tokenhanterare för användning av ett program. I dessa fall kan du härleda från SecurityTokenService för att skapa en eller flera enkla sts som kan distribueras i utvecklingsmiljön och som kan användas för att testa sådana funktioner i ditt program. Resten av det här avsnittet fokuserar på de metoder som exponeras av SecurityTokenService klassen som gör att du kan implementera en enkel STS och utöka pipelinen för tokenutfärdning.

Följande lista innehåller en kort översikt över de metoder som är av primär betydelse för utvecklaren för användning i en test- eller utvecklingsmiljö.

  • GetScope-metoden. Den här metoden returnerar ett Scope objekt som innehåller information om RP. Det här objektet används i resten av pipelinen för tokenutfärdande och innehåller information om signering och kryptering av autentiseringsuppgifter som ska användas i svaret, samt adresserna AppliesTo och ReplyTo (om det behövs). Du måste åsidosätta den här metoden.

  • GetOutputClaimsIdentity-metoden. Den här metoden returnerar ett ClaimsIdentity objekt som innehåller anspråken för att återgå till RP. Du måste åsidosätta den här metoden.

  • Issue-metoden. Den här metoden implementerar pipelinen för tokenbegäran, som bearbetar en inkommande begäran om säkerhetstoken (RST) och returnerar ett svar (RSTR) till anroparen som innehåller en token som kan användas för att autentisera med en RP. Många av de andra metoderna som definieras i SecurityTokenService klassen anropas från den här metoden, inklusive GetScope metoderna och GetOutputClaimsIdentity . Du behöver inte åsidosätta den här metoden, men en förståelse för pipelinen för tokenbegäran som implementeras kan vara till hjälp.

En STS konfigureras via SecurityTokenServiceConfiguration klassen.

Anteckningar till implementerare

Du måste åsidosätta både GetScope(ClaimsPrincipal, RequestSecurityToken) metoderna och GetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope) .

Konstruktorer

Name Description
SecurityTokenService(SecurityTokenServiceConfiguration)

Anropas från härledda klasser för att initiera SecurityTokenService klassen med hjälp av de angivna konfigurationsinställningarna.

Egenskaper

Name Description
Principal

Hämtar eller anger det huvudnamn som är associerat med den aktuella instansen.

Request

Hämtar eller anger den säkerhetstokenbegäran (RST) som är associerad med den aktuella instansen.

Scope

Hämtar eller anger det omfång som är associerat med den aktuella instansen.

SecurityTokenDescriptor

Hämtar eller anger den SecurityTokenDescriptor associerade med den aktuella instansen.

SecurityTokenServiceConfiguration

Hämtar ägarkonfigurationsinstansen.

Metoder

Name Description
BeginCancel(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

När den åsidosättas i en härledd klass börjar en asynkron WS-Trust Avbryt begäran.

BeginGetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope, AsyncCallback, Object)

När det åsidosättas i en härledd klass börjar ett asynkront anrop till GetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope) metoden.

BeginGetScope(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

När du åsidosättas i en härledd klass börjar ett asynkront anrop för GetScope(ClaimsPrincipal, RequestSecurityToken) metoden.

BeginIssue(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

När den åsidosättas i en härledd klass börjar en asynkron WS-Trust Ärendebegäran.

BeginRenew(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

När åsidosättas i en härledd klass börjar en asynkron WS-Trust Förnya begäran.

BeginValidate(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object)

När den åsidosättas i en härledd klass börjar en asynkron WS-Trust Validera begäran.

Cancel(ClaimsPrincipal, RequestSecurityToken)

När den åsidosättas i en härledd klass bearbetar en WS-Trust Avbryt begäran.

CreateSecurityTokenDescriptor(RequestSecurityToken, Scope)

Skapar en instans av en SecurityTokenDescriptor.

EndCancel(IAsyncResult)

När den åsidosättas i en härledd klass slutför den asynkrona WS-Trust Avbryt begäran.

EndGetOutputClaimsIdentity(IAsyncResult)

När det åsidosättas i en härledd klass slutför det asynkrona anropet BeginGetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope, AsyncCallback, Object) till metoden.

EndGetScope(IAsyncResult)

När det åsidosättas i en härledd klass slutför det asynkrona anropet BeginGetScope(ClaimsPrincipal, RequestSecurityToken, AsyncCallback, Object) till metoden.

EndIssue(IAsyncResult)

När den åsidosättas i en härledd klass slutför den asynkrona WS-Trust Ärendebegäran.

EndRenew(IAsyncResult)

När den åsidosättas i en härledd klass slutför den asynkrona WS-Trust Förnya begäran.

EndValidate(IAsyncResult)

När den åsidosättas i en härledd klass slutför den asynkrona WS-Trust Validera begäran.

Equals(Object)

Avgör om det angivna objektet är lika med det aktuella objektet.

(Ärvd från Object)
GetHashCode()

Fungerar som standard-hash-funktion.

(Ärvd från Object)
GetIssuerName()

Hämtar namnet på säkerhetstokentjänsten (STS).

GetOutputClaimsIdentity(ClaimsPrincipal, RequestSecurityToken, Scope)

När den åsidosättas i en härledd klass returnerar den här metoden en samling utdataämnen som ska ingå i den utfärdade token.

GetProofToken(RequestSecurityToken, Scope)

Hämtar bevistoken som ska ingå i svaret (RSTR).

GetRequestorProofEncryptingCredentials(RequestSecurityToken)

Hämtar begärandens autentiseringsuppgifter för korrekturkryptering.

GetResponse(RequestSecurityToken, SecurityTokenDescriptor)

Skapar svaret (RSTR) som innehåller den utfärdade token med hjälp av den angivna begäran (RST) och säkerhetstokenbeskrivningen.

GetScope(ClaimsPrincipal, RequestSecurityToken)

Hämtar ett Scope objekt som innehåller information om den förlitande part (RP) som är associerad med den angivna begäran (RST). Du måste åsidosätta den här metoden i implementeringen av SecurityTokenService klassen.

GetSecurityTokenHandler(String)

Hämtar lämplig säkerhetstokenhanterare för att utfärda en säkerhetstoken av den angivna typen.

GetTokenLifetime(Lifetime)

Hämtar livslängden för den utfärdade token.

GetType()

Hämtar den aktuella instansen Type .

(Ärvd från Object)
Issue(ClaimsPrincipal, RequestSecurityToken)

Utfärdar en säkerhetstoken.

MemberwiseClone()

Skapar en ytlig kopia av den aktuella Object.

(Ärvd från Object)
Renew(ClaimsPrincipal, RequestSecurityToken)

När den åsidosättas i en härledd klass bearbetar en WS-Trust Förnya begäran.

ToString()

Returnerar en sträng som representerar det aktuella objektet.

(Ärvd från Object)
Validate(ClaimsPrincipal, RequestSecurityToken)

När den åsidosättas i en härledd klass bearbetar en WS-Trust Verifiera begäran.

ValidateRequest(RequestSecurityToken)

Verifierar den säkerhetstokenbegäran (RST) som kapslas in av den här instansen.

Gäller för

Se även