This repository has been archived by the owner on Dec 14, 2017. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
SignInResponseGenerator.cs
227 lines (197 loc) · 9.39 KB
/
SignInResponseGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
* Copyright 2015 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IdentityModel.Tokens;
using IdentityServer3.Core;
using IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core.Models;
using IdentityServer3.Core.Services;
using IdentityServer3.WsFederation.Logging;
using IdentityServer3.WsFederation.Services;
using IdentityServer3.WsFederation.Validation;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Services;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
#pragma warning disable 1591
namespace IdentityServer3.WsFederation.ResponseHandling
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class SignInResponseGenerator
{
private readonly static ILog Logger = LogProvider.GetCurrentClassLogger();
private readonly IdentityServerOptions _options;
private readonly IUserService _users;
private readonly IDictionary<string, object> _environment;
private readonly ICustomWsFederationClaimsService _customClaimsService;
public SignInResponseGenerator(IdentityServerOptions options, IUserService users, OwinEnvironmentService owinEnvironment, ICustomWsFederationClaimsService customClaimsService)
{
_options = options;
_users = users;
_environment = owinEnvironment.Environment;
_customClaimsService = customClaimsService;
}
private string IssuerUri
{
get
{
return _environment.GetIdentityServerIssuerUri();
}
}
public async Task<SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult)
{
Logger.Info("Creating WS-Federation signin response");
// create subject
var outgoingSubject = await CreateSubjectAsync(validationResult);
// create token for user
var token = CreateSecurityToken(validationResult, outgoingSubject);
// return response
var rstr = new RequestSecurityTokenResponse
{
AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm),
Context = validationResult.SignInRequestMessage.Context,
ReplyTo = validationResult.ReplyUrl,
RequestedSecurityToken = new RequestedSecurityToken(token)
};
var serializer = new WSFederationSerializer(
new WSTrust13RequestSerializer(),
new WSTrust13ResponseSerializer());
var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();
mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();
var responseMessage = new SignInResponseMessage(
new Uri(validationResult.ReplyUrl),
rstr,
serializer,
new WSTrustSerializationContext(mgr));
return responseMessage;
}
protected async Task<ClaimsIdentity> CreateSubjectAsync(SignInValidationResult validationResult)
{
var profileClaims = new List<Claim>();
var mappedClaims = new List<Claim>();
// get all claims from user service
if (validationResult.RelyingParty.IncludeAllClaimsForUser)
{
var ctx = new ProfileDataRequestContext
{
Subject = validationResult.Subject,
AllClaimsRequested = true
};
await _users.GetProfileDataAsync(ctx);
profileClaims = ctx.IssuedClaims.ToList();
}
else
{
// get only claims that are explicitly mapped (if any)
var claimTypes = validationResult.RelyingParty.ClaimMappings.Keys;
if (claimTypes.Any())
{
var ctx = new ProfileDataRequestContext
{
Subject = validationResult.Subject,
RequestedClaimTypes = claimTypes
};
await _users.GetProfileDataAsync(ctx);
profileClaims = ctx.IssuedClaims.ToList();
}
}
foreach (var claim in profileClaims)
{
string mappedType;
// if an explicit mapping exists, use it
if (validationResult.RelyingParty.ClaimMappings.TryGetValue(claim.Type, out mappedType))
{
// if output claim is a SAML name ID - check is any name ID format is configured
if (mappedType == ClaimTypes.NameIdentifier)
{
var nameId = new Claim(ClaimTypes.NameIdentifier, claim.Value);
if (!string.IsNullOrEmpty(validationResult.RelyingParty.SamlNameIdentifierFormat))
{
nameId.Properties[ClaimProperties.SamlNameIdentifierFormat] = validationResult.RelyingParty.SamlNameIdentifierFormat;
}
mappedClaims.Add(nameId);
}
else
{
mappedClaims.Add(new Claim(mappedType, claim.Value));
}
}
else
{
// otherwise pass-through the claims if flag is set
if (validationResult.RelyingParty.IncludeAllClaimsForUser)
{
string newType = claim.Type;
// if prefix is configured, prefix the claim type
if (!string.IsNullOrWhiteSpace(validationResult.RelyingParty.DefaultClaimTypeMappingPrefix))
{
newType = validationResult.RelyingParty.DefaultClaimTypeMappingPrefix + newType;
}
mappedClaims.Add(new Claim(newType, claim.Value));
}
}
}
// The AuthnStatement statement generated from the following 2
// claims is manditory for some service providers (i.e. Shibboleth-Sp).
// The value of the AuthenticationMethod claim must be one of the constants in
// System.IdentityModel.Tokens.AuthenticationMethods.
// Password is the only one that can be directly matched, everything
// else defaults to Unspecified.
if (validationResult.Subject.GetAuthenticationMethod() == Constants.AuthenticationMethods.Password)
{
mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password));
} else {
mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Unspecified));
}
mappedClaims.Add(AuthenticationInstantClaim.Now);
var finalClaims = await _customClaimsService.TransformClaimsAsync(validationResult, mappedClaims);
return new ClaimsIdentity(finalClaims, "idsrv");
}
private SecurityToken CreateSecurityToken(SignInValidationResult validationResult, ClaimsIdentity outgoingSubject)
{
var descriptor = new SecurityTokenDescriptor
{
AppliesToAddress = validationResult.RelyingParty.Realm,
Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(validationResult.RelyingParty.TokenLifeTime)),
ReplyToAddress = validationResult.ReplyUrl,
SigningCredentials = new X509SigningCredentials(_options.SigningCertificate, validationResult.RelyingParty.SignatureAlgorithm, validationResult.RelyingParty.DigestAlgorithm),
Subject = outgoingSubject,
TokenIssuerName = IssuerUri,
TokenType = validationResult.RelyingParty.TokenType
};
if (validationResult.RelyingParty.EncryptingCertificate != null)
{
descriptor.EncryptingCredentials = new EncryptedKeyEncryptingCredentials(validationResult.RelyingParty.EncryptingCertificate);
}
return CreateSupportedSecurityTokenHandler().CreateToken(descriptor);
}
private SecurityTokenHandlerCollection CreateSupportedSecurityTokenHandler()
{
return new SecurityTokenHandlerCollection(new SecurityTokenHandler[]
{
new SamlSecurityTokenHandler(),
new EncryptedSecurityTokenHandler(),
new Saml2SecurityTokenHandler(),
new JwtSecurityTokenHandler()
});
}
}
}