public async Task<IEndpointResult> ProcessAsync(IdentityServerContext context) { _logger.LogVerbose("Start token request."); // validate HTTP if (context.HttpContext.Request.Method != "POST" || !context.HttpContext.Request.HasFormContentType) { // todo logging return new TokenErrorResult(OidcConstants.TokenErrors.InvalidRequest); } // validate client var clientResult = await _clientValidator.ValidateAsync(context.HttpContext); if (clientResult.Client == null) { return new TokenErrorResult(OidcConstants.TokenErrors.InvalidClient); } // validate request var requestResult = await _requestValidator.ValidateRequestAsync( context.HttpContext.Request.Form.AsNameValueCollection(), clientResult.Client); if (requestResult.IsError) { return new TokenErrorResult(requestResult.Error, requestResult.ErrorDescription); } // create response var response = await _responseGenerator.ProcessAsync(requestResult.ValidatedRequest); // return result return new TokenResult(response); }
// todo //protected readonly OwinEnvironmentService _owinEnvironmentService; /// <summary> /// Initializes a new instance of the <see cref="DefaultTokenService" /> class. This overloaded constructor is deprecated and will be removed in 3.0.0. /// </summary> /// <param name="options">The options.</param> /// <param name="claimsProvider">The claims provider.</param> /// <param name="tokenHandles">The token handles.</param> /// <param name="signingService">The signing service.</param> /// <param name="events">The events service.</param> public DefaultTokenService(IdentityServerContext context, IClaimsProvider claimsProvider, ITokenHandleStore tokenHandles, ITokenSigningService signingService, IEventService events, ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<DefaultTokenService>(); _context = context; _claimsProvider = claimsProvider; _tokenHandles = tokenHandles; _signingService = signingService; _events = events; }
public static void SetBasePath(this IdentityServerContext context, string value) { if (context == null) { throw new ArgumentNullException(nameof(context)); } context.HttpContext.Items[Constants.OwinEnvironment.IdentityServerBasePath] = value; }
public DiscoveryEndpoint(IdentityServerOptions options, IdentityServerContext context, IScopeStore scopes, ILogger<DiscoveryEndpoint> logger, ISigningKeyService keyService, CustomGrantValidator customGrants, SecretParser parsers) { _options = options; _scopes = scopes; _logger = logger; _keyService = keyService; _context = context; _customGrants = customGrants; _parsers = parsers; }
public async Task Invoke(HttpContext context, IdentityServerContext idsrvContext) { var request = context.Request; var host = request.Scheme + "://" + request.Host.Value; idsrvContext.SetHost(host); idsrvContext.SetBasePath(request.PathBase.Value.RemoveTrailingSlash()); await _next(context); }
public override async Task ExecuteAsync(IdentityServerContext context) { context.HttpContext.Response.ContentType = "text/html; charset=UTF-8"; context.HttpContext.Response.SetNoCache(); var html = _html; html = html.Replace("{uri}", Response.RedirectUri); html = html.Replace("{body}", BuildFormBody(Response)); await context.HttpContext.Response.WriteAsync(html, Encoding.UTF8); }
public Task ExecuteAsync(IdentityServerContext context) { var redirect = context.GetIdentityServerBaseUrl().EnsureTrailingSlash() + Path.RemoveLeadingSlash(); if (Id.IsPresent()) { redirect = redirect.AddQueryString("id=" + Id); } context.HttpContext.Response.Redirect(redirect); return Task.FromResult(0); }
public async Task ExecuteAsync(IdentityServerContext context) { var dto = new ErrorDto { error = Error, error_description = ErrorDescription }; context.HttpContext.Response.StatusCode = 400; context.HttpContext.Response.SetNoCache(); await context.HttpContext.Response.WriteJsonAsync(dto); }
public TokenValidator(IdentityServerOptions options, IdentityServerContext context, IClientStore clients, ITokenHandleStore tokenHandles, ICustomTokenValidator customValidator, ISigningKeyService keyService, ILogger<TokenValidator> logger) { _options = options; _context = context; _clients = clients; _tokenHandles = tokenHandles; _customValidator = customValidator; _keyService = keyService; _logger = logger; _log = new TokenValidationLog(); }
public async Task<IEndpointResult> ProcessAsync(IdentityServerContext context) { // validate HTTP if (context.HttpContext.Request.Method != "POST") { return new StatusCodeResult(405); } var scopeResult = await _scopeSecretValidator.ValidateAsync(context.HttpContext); if (scopeResult.Scope == null) { _logger.LogWarning("Scope unauthorized to call introspection endpoint. aborting."); return new StatusCodeResult(401); } var parameters = context.HttpContext.Request.Form.AsNameValueCollection(); var validationResult = await _requestValidator.ValidateAsync(parameters, scopeResult.Scope); var response = await _generator.ProcessAsync(validationResult, scopeResult.Scope); if (validationResult.IsActive) { await RaiseSuccessEventAsync(validationResult.Token, "active", scopeResult.Scope.Name); return new IntrospectionResult(response); } if (validationResult.IsError) { if (validationResult.FailureReason == IntrospectionRequestValidationFailureReason.MissingToken) { _logger.LogError("Missing token"); await RaiseFailureEventAsync(validationResult.ErrorDescription, validationResult.Token, scopeResult.Scope.Name); //todo return BadRequest("missing_token"); return new StatusCodeResult(400); } if (validationResult.FailureReason == IntrospectionRequestValidationFailureReason.InvalidToken) { await RaiseSuccessEventAsync(validationResult.Token, "inactive", scopeResult.Scope.Name); return new IntrospectionResult(response); } if (validationResult.FailureReason == IntrospectionRequestValidationFailureReason.InvalidScope) { await RaiseFailureEventAsync("Scope not authorized to introspect token", validationResult.Token, scopeResult.Scope.Name); return new IntrospectionResult(response); } } throw new InvalidOperationException("Invalid token introspection outcome"); }
async Task<IEndpointResult> ProcessAuthorizeAsync(IdentityServerContext context) { _logger.LogInformation("Start Authorize Request"); var values = context.HttpContext.Request.Query.AsNameValueCollection(); var user = await _context.GetIdentityServerUserAsync(); var result = await ProcessAuthorizeRequestAsync(values, user, null); _logger.LogInformation("End Authorize Request. Result type: {0}", result?.GetType().ToString() ?? "-none-"); return result; }
public async Task ExecuteAsync(IdentityServerContext context) { var dto = new TokenResponseDto { id_token = TokenResponse.IdentityToken, access_token = TokenResponse.AccessToken, refresh_token = TokenResponse.RefreshToken, expires_in = TokenResponse.AccessTokenLifetime, token_type = Constants.TokenTypes.Bearer }; context.HttpContext.Response.SetNoCache(); await context.HttpContext.Response.WriteJsonAsync(dto); }
public async Task Invoke(HttpContext context, IEndpointRouter router, IdentityServerContext idSvrContext) { var endpoint = router.Find(context); if (endpoint != null) { var result = await endpoint.ProcessAsync(idSvrContext); if (result != null) { await result.ExecuteAsync(idSvrContext); } return; } await _next(context); }
public Task<IEndpointResult> ProcessAsync(IdentityServerContext context) { // validate HTTP if (context.HttpContext.Request.Method != "GET") { // todo // return bad request or 405 ? } if (context.HttpContext.Request.Path.Value.EndsWith("/jwks")) { return ExecuteJwksAsync(context.HttpContext); } else { return ExecuteDiscoDocAsync(context.HttpContext); } }
public AuthorizeEndpoint( IEventService events, ILogger<AuthorizeEndpoint> logger, IdentityServerContext context, IAuthorizeRequestValidator validator, IAuthorizeInteractionResponseGenerator interactionGenerator, IAuthorizeEndpointResultFactory resultGenerator, IMessageStore<SignInResponse> signInResponseStore, IMessageStore<ConsentResponse> consentRequestStore) { _events = events; _logger = logger; _context = context; _validator = validator; _interactionGenerator = interactionGenerator; _resultGenerator = resultGenerator; _signInResponseStore = signInResponseStore; _consentResponseStore = consentRequestStore; }
public async Task<IEndpointResult> ProcessAsync(IdentityServerContext context) { if (context.HttpContext.Request.Method != "GET" && context.HttpContext.Request.Method != "POST") { return new StatusCodeResult(405); } _logger.LogVerbose("Start userinfo request"); var tokenUsageResult = await _tokenUsageValidator.ValidateAsync(context.HttpContext); if (tokenUsageResult.TokenFound == false) { var error = "No token found."; _logger.LogError(error); await RaiseFailureEventAsync(error); return Error(OidcConstants.ProtectedResourceErrors.InvalidToken); } _logger.LogInformation("Token found: {token}", tokenUsageResult.UsageType.ToString()); var tokenResult = await _tokenValidator.ValidateAccessTokenAsync( tokenUsageResult.Token, Constants.StandardScopes.OpenId); if (tokenResult.IsError) { _logger.LogError(tokenResult.Error); await RaiseFailureEventAsync(tokenResult.Error); return Error(tokenResult.Error); } // pass scopes/claims to profile service var subject = tokenResult.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject).Value; var scopes = tokenResult.Claims.Where(c => c.Type == JwtClaimTypes.Scope).Select(c => c.Value); var payload = await _generator.ProcessAsync(subject, scopes, tokenResult.Client); _logger.LogInformation("End userinfo request"); await RaiseSuccessEventAsync(); return new UserInfoResult(payload); }
public AuthorizeEndpointResultFactory( ILogger<AuthorizeEndpointResultFactory> logger, IdentityServerContext context, IAuthorizeResponseGenerator responseGenerator, ILocalizationService localizationService, IMessageStore<SignInRequest> signInRequestStore, IMessageStore<ConsentRequest> consentRequestStore, IMessageStore<ErrorMessage> errorMessageStore, ClientListCookie clientListCookie) { _logger = logger; _context = context; _responseGenerator = responseGenerator; _localizationService = localizationService; _signInRequestStore = signInRequestStore; _consentRequestStore = consentRequestStore; _errorMessageStore = errorMessageStore; _clientListCookie = clientListCookie; }
public static string GetIssuerUri(this IdentityServerContext context) { if (context == null) { throw new ArgumentNullException("context"); } // if they've explicitly configured a URI then use it, // otherwise dynamically calculate it var uri = context.Options.IssuerUri; if (uri.IsMissing()) { uri = context.GetIdentityServerBaseUrl(); if (uri.EndsWith("/")) { uri = uri.Substring(0, uri.Length - 1); } } return(uri); }
public Task ExecuteAsync(IdentityServerContext context) { if (CustomEntries != null && CustomEntries.Any()) { var jobject = JObject.FromObject(Document); foreach (var item in CustomEntries) { JToken token; if (jobject.TryGetValue(item.Key, out token)) { throw new Exception("Item does already exist - cannot add it via a custom entry: " + item.Key); } jobject.Add(new JProperty(item.Key, item.Value)); return context.HttpContext.Response.WriteJsonAsync(jobject); } } return context.HttpContext.Response.WriteJsonAsync(Document); }
public Task ExecuteAsync(IdentityServerContext context) { context.HttpContext.Response.StatusCode = 401; context.HttpContext.Response.SetNoCache(); if (Constants.ProtectedResourceErrorStatusCodes.ContainsKey(Error)) { context.HttpContext.Response.StatusCode = Constants.ProtectedResourceErrorStatusCodes[Error]; } var parameter = string.Format("error=\"{0}\"", Error); if (ErrorDescription.IsPresent()) { parameter = string.Format("{0}, error_description=\"{1}\"", parameter, ErrorDescription); } context.HttpContext.Response.Headers.Add("WwwAuthentication", new StringValues("Bearer")); //TODO logger.LogInformation("Returning error: " + Error); return Task.FromResult(0); }
public async Task<IEndpointResult> ProcessAsync(IdentityServerContext context) { if (context.HttpContext.Request.Method != "GET") { return new StatusCodeResult(HttpStatusCode.MethodNotAllowed); } if (context.HttpContext.Request.Path == Constants.RoutePaths.Oidc.Authorize.EnsureLeadingSlash()) { return await ProcessAuthorizeAsync(context); } if (context.HttpContext.Request.Path == Constants.RoutePaths.Oidc.AuthorizeAfterLogin.EnsureLeadingSlash()) { return await ProcessAuthorizeAfterLoginAsync(context); } if (context.HttpContext.Request.Path == Constants.RoutePaths.Oidc.AuthorizeAfterConsent.EnsureLeadingSlash()) { return await ProcessAuthorizeAfterConsentAsync(context); } return new StatusCodeResult(HttpStatusCode.NotFound); }
public MessageCookie(ILogger <MessageCookie <TModel> > logger, IdentityServerContext context, IDataProtectionProvider provider) { _logger = logger; _context = context; _protector = provider.CreateProtector(MessageType); }
public override Task ExecuteAsync(IdentityServerContext context) { context.HttpContext.Response.SetNoCache(); context.HttpContext.Response.Redirect(BuildUri(Response)); return Task.FromResult(0); }
public ClientListCookie(IdentityServerContext context) { _context = context; }
public SessionCookie(IdentityServerContext context) { _context = context; }
/// <summary> /// Gets the base path of IdentityServer. Can be used inside of Katana <c>Map</c>ped middleware. /// </summary> /// <param name="env">The OWIN environment.</param> /// <returns></returns> public static string GetBasePath(this IdentityServerContext context) { return(context.HttpContext.Items[Constants.OwinEnvironment.IdentityServerBasePath] as string); }
public Task ExecuteAsync(IdentityServerContext context) { return context.HttpContext.Response.WriteJsonAsync(new { keys = WebKeys }); }
public async Task ExecuteAsync(IdentityServerContext context) { context.HttpContext.Response.SetNoCache(); await context.HttpContext.Response.WriteJsonAsync(Claims); }
public static TokenValidator CreateTokenValidator(ITokenHandleStore tokenStore = null, IProfileService profile = null) { if (profile == null) { profile = new TestProfileService(); } var clients = CreateClientStore(); var options = TestIdentityServerOptions.Create(); var accessor = new HttpContextAccessor(); accessor.HttpContext = new DefaultHttpContext(); var idsrvContext = new IdentityServerContext(accessor, options); var logger = new Logger<TokenValidator>(new LoggerFactory()); var validator = new TokenValidator( options: options, clients: clients, tokenHandles: tokenStore, customValidator: new DefaultCustomTokenValidator( profile: profile, clients: clients, logger: new Logger<DefaultCustomTokenValidator>(new LoggerFactory())), keyService: new DefaultSigningKeyService(options), logger: logger, context: idsrvContext); return validator; }
public abstract Task ExecuteAsync(IdentityServerContext context);
internal async Task<IEndpointResult> ProcessAuthorizeAfterLoginAsync(IdentityServerContext context) { _logger.LogInformation("Start Authorize Request (after login)"); if (!context.HttpContext.Request.Query.ContainsKey("id")) { _logger.LogWarning("id query parameter is missing."); return await ErrorPageAsync(ErrorTypes.User, nameof(Messages.UnexpectedError), null); } var id = context.HttpContext.Request.Query["id"].First(); var message = await _signInResponseStore.ReadAsync(id); if (message == null) { _logger.LogWarning("signin message is missing."); return await ErrorPageAsync(ErrorTypes.User, nameof(Messages.UnexpectedError), null); } if (message.AuthorizeRequestParameters == null) { _logger.LogWarning("signin message is missing AuthorizeRequestParameters data."); return await ErrorPageAsync(ErrorTypes.User, nameof(Messages.UnexpectedError), null); } var user = await _context.GetIdentityServerUserAsync(); var result = await ProcessAuthorizeRequestAsync(message.AuthorizeRequestParameters.ToNameValueCollection(), user, null); await _signInResponseStore.DeleteAsync(id); _logger.LogInformation("End Authorize Request. Result type: {0}", result?.GetType().ToString() ?? "-none-"); return result; }
/// <summary> /// Gets the public base URL for IdentityServer. /// </summary> /// <param name="env">The OWIN environment.</param> /// <returns></returns> public static string GetIdentityServerBaseUrl(this IdentityServerContext context) { return(context.GetHost() + context.GetBasePath()); }
internal static async Task <ClaimsPrincipal> GetIdentityServerUserAsync(this IdentityServerContext context) { return(await context.HttpContext.Authentication.AuthenticateAsync(context.Options.AuthenticationOptions.EffectivePrimaryAuthenticationScheme)); }
public Task ExecuteAsync(IdentityServerContext context) { context.HttpContext.Response.StatusCode = StatusCode; return Task.FromResult(0); }
internal static void SetRequestId(this IdentityServerContext context, string id) { context.HttpContext.TraceIdentifier = id; }
public MockClientListCookie(IdentityServerContext context) : base(context) { }
public Task<IEndpointResult> ProcessAsync(IdentityServerContext context) { throw new NotImplementedException(); }
internal static string GetRequestId(this IdentityServerContext context) { return(context.HttpContext.TraceIdentifier); }