public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Reject token requests that don't use grant_type=password or grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only grant_type=password and refresh_token " + "requests are accepted by this server."); return(Task.FromResult(0)); } if (string.Equals(context.ClientId, "AspNetContribSample", StringComparison.Ordinal)) { // Note: the context is marked as skipped instead of validated because the client // is not trusted (JavaScript applications cannot keep their credentials secret). context.Skip(); } else { // If the client_id doesn't correspond to the // intended identifier, reject the request. context.Reject(OpenIdConnectConstants.Errors.InvalidClient); } return(Task.FromResult(0)); }
// Validate the grant_type and the client application credentials public override async Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Reject the token requests that don't use grant_type=password or grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only grant_type=password or grant_type=refresh_token are accepted by this server."); return; } // Check if refresh-token exists in DB if (context.Request.IsRefreshTokenGrantType()) { var id = RefreshTokenProvider.GenerateId(context.Request.RefreshToken); if (!await RavenDatabaseProvider.IsEntityExists(id)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Invalid client."); return; } } // Since there's only one application and since it's a public client // (i.e a client that cannot keep its credentials private), call Skip() // to inform the server the request should be accepted without // enforcing client authentication. context.Skip(); return; }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Since there's only one application and since it's a public client // (i.e a client that cannot keep its credentials private), call Skip() // to inform the server that the request should be accepted without // enforcing client authentication. context.Skip(); return(Task.FromResult(0)); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only the resource owner password credentials and refresh token " + "grants are accepted by this authorization server"); return(Task.FromResult(0)); } context.Skip(); return(Task.FromResult(0)); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Unsupported Authentication");//Resources.Security.UnsupportedAuthentication return(Task.FromResult(0)); } context.Skip(); return(Task.FromResult(0)); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { if (string.IsNullOrEmpty(context.ClientId)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "Missing credentials: ensure that your credentials were correctly " + "flowed in the request body or in the authorization header"); return(Task.FromResult(0)); } #region Validate Client var application = _applicationservice.GetByClientId(context.ClientId); if (applicationResult == null) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Application not found in the database: ensure that your client_id is correct"); return(Task.FromResult(0)); } else { var application = applicationResult.Data; if (application.ApplicationType == (int)ApplicationTypes.JavaScript) { // Note: the context is marked as skipped instead of validated because the client // is not trusted (JavaScript applications cannot keep their credentials secret). context.Skip(); } else { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Authorization server only handles Javascript application."); return(Task.FromResult(0)); } } #endregion Validate Client var request = context.Request.RequestUri; return(Task.FromResult(0)); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Reject the token requests that don't use grant_type=password or grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Tipo de autenticación inválida"); return(Task.FromResult(0)); } context.Skip(); return(Task.FromResult(0)); }
private Task OnValidateTokenRequest(ValidateTokenRequestContext context) { if (context.Request.GrantType == "Password") { context.Skip(); return(Task.CompletedTask); } context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only grant_type=password" + "requests are accepted by this server."); return(Task.CompletedTask); }
public override async Task ValidateTokenRequest(ValidateTokenRequestContext context) { if (!context.Request.IsPasswordGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only the resource owner password credentials grant is accepted by this authorization server" ); await Task.FromResult(context.IsValidated); } context.Skip(); await Task.FromResult(context.IsValidated); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { if (!context.Request.IsPasswordGrantType()) { context.Reject(OpenIdConnectConstants.Errors.UnsupportedGrantType, "Only supports resource owner password credentials grant!"); } else { // Since there's only one application and since it's a public client // (i.e a client that cannot keep its credentials private), call Skip() // to inform the server the request should be accepted without // enforcing client authentication. context.Skip(); } return(Task.CompletedTask); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Reject token requests that don't use grant_type=password or grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only grant_type=password and refresh_token " + "requests are accepted by this server."); return(Task.FromResult(0)); } context.Skip(); return(Task.FromResult(0)); }
public override async Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Note: the OpenID Connect server middleware supports authorization code, refresh token, client credentials // and resource owner password credentials grant types but this authorization provider uses a safer policy // rejecting the last two ones. You may consider relaxing it to support the ROPC or client credentials grant types. if (!context.Request.IsAuthorizationCodeGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only authorization code and refresh token grant types " + "are accepted by this authorization server."); return; } // Reject the request if the client identifier is missing. if (string.IsNullOrEmpty(context.ClientId)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The mandatory 'client_id'/'client_secret' parameters are missing."); return; } var database = context.HttpContext.RequestServices.GetRequiredService <ApplicationContext>(); // Retrieve the application details corresponding to the requested client_id. var application = await(from entity in database.Applications where entity.ApplicationID == context.ClientId select entity).SingleOrDefaultAsync(context.HttpContext.RequestAborted); if (application == null) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "The specified client identifier is invalid."); return; } // Note: the client credentials cannot be safely stored in the Cordova application. // In this case, context.Skip() is called to inform the OIDC server that the client is not trusted. context.Skip(); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { //Valida apenas os tipos de requisição de token //Se for colocar pra receber token de terceiros, tem que alterar aqui if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Tipo de autenticaçao nao suportado pelo servidor."); return(Task.FromResult(0)); } //Mata o contexto caso não seja válido context.Skip(); return(Task.FromResult(0)); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { if (context.ClientId == "AureliaNetAuthApp") { // Note: the context is marked as skipped instead of validated because the client // is not trusted (JavaScript applications cannot keep their credentials secret). context.Skip(); } else { // If the client_id doesn't correspond to the // intended identifier, reject the request. context.Reject(OpenIdConnectConstants.Errors.InvalidClient); } return(Task.FromResult(0)); }
// Validate the grant_type and the client application credentials. public override async Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Reject the token requests that don't use grant_type=password or grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { // Handle response ourselves and return an object. context.HandleResponse(); context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.StatusCode = 400; await context.HttpContext.Response.WriteAsync( JsonConvert.SerializeObject( new { error = OpenIdConnectConstants.Errors.UnsupportedGrantType, error_description = "Only grant_type=password or grant_type=refresh_token are accepted by this server." })); return; } // Check if refresh-token exists in DB. if (context.Request.IsRefreshTokenGrantType()) { if (!await DatabaseProvider.IsRefreshTokenExists(context.Request.RefreshToken)) { // Handle response ourselves and return an object. context.HandleResponse(); context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.StatusCode = 400; await context.HttpContext.Response.WriteAsync( JsonConvert.SerializeObject( new { error = OpenIdConnectConstants.Errors.InvalidClient, error_description = "Invalid client." })); return; } } context.Skip(); return; }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Reject the token request that don't use grant_type=password or grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only resource owner password credentials and refresh token " + "are accepted by this authorization server"); return(Task.FromResult(0)); } // Since there's only one application and since it's a public client // (i.e a client that cannot keep its credentials private), call Skip() // to inform the server that the request should be accepted without // enforcing client authentication. context.Skip(); return(Task.FromResult(0)); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Note: the OpenID Connect server middleware supports authorization code, refresh token, client credentials // and resource owner password credentials grant types but this authorization provider uses a safer policy // rejecting the last two ones. You may consider relaxing it to support the ROPC or client credentials grant types. if (!context.Request.IsAuthorizationCodeGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only authorization code and refresh token grant types " + "are accepted by this authorization server"); return(Task.FromResult(0)); } // Note: we use a relaxed policy here as the client credentials cannot be safely stored in the Cordova Javascript application. // In this case, we call context.Skip() to inform the server middleware the client is not trusted. context.Skip(); return(Task.FromResult(0)); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Отвергаем запросы на аутенфикацию, которы не соотвествуют grant_type=password или grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only resource owner password credentials and refresh token " + "are accepted by this authorization server"); return(Task.CompletedTask); } // Так как мы реализуем аутенфикацию для нашего SPA // это значит что у нас будет только один клиент (Angular приложение) // Этот клиент не должен хранить клинтский секретный ключ, так ка кон легко будет доступен // для несанкционированого просмотра. // Поэтому в таких случаях сервер должен принимать запрос на аутинфекация без секретного ключа клиента // Просто пропускаем этот запрос дальше, если grant_type=password или grant_type=refresh_token context.Skip(); return(Task.CompletedTask); }
public override async Task ValidateTokenRequest([NotNull] ValidateTokenRequestContext context) { var options = (OpenIddictServerOptions)context.Options; // Reject token requests that don't specify a supported grant type. if (!options.GrantTypes.Contains(context.Request.GrantType)) { _logger.LogError("The token request was rejected because the '{GrantType}' " + "grant type is not supported.", context.Request.GrantType); context.Reject( error: OpenIddictConstants.Errors.UnsupportedGrantType, description: "The specified 'grant_type' parameter is not supported."); return; } // Reject token requests that specify scope=offline_access if the refresh token flow is not enabled. if (context.Request.HasScope(OpenIddictConstants.Scopes.OfflineAccess) && !options.GrantTypes.Contains(OpenIddictConstants.GrantTypes.RefreshToken)) { context.Reject( error: OpenIddictConstants.Errors.InvalidRequest, description: "The 'offline_access' scope is not allowed."); return; } // Optimization: the OpenID Connect server middleware automatically rejects grant_type=authorization_code // requests missing the redirect_uri parameter if one was specified in the initial authorization request. // Since OpenIddict doesn't allow redirect_uri-less authorization requests, an earlier check can be made here, // which saves the OpenID Connect server middleware from having to deserialize the authorization code ticket. // See http://openid.net/specs/openid-connect-core-1_0.html#TokenRequestValidation for more information. if (context.Request.IsAuthorizationCodeGrantType() && string.IsNullOrEmpty(context.Request.RedirectUri)) { context.Reject( error: OpenIddictConstants.Errors.InvalidRequest, description: "The mandatory 'redirect_uri' parameter is missing."); return; } // Note: the OpenID Connect server middleware allows returning a refresh token with grant_type=client_credentials, // though it's usually not recommended by the OAuth2 specification. To encourage developers to make a new // grant_type=client_credentials request instead of using refresh tokens, OpenIddict uses a stricter policy // that rejects grant_type=client_credentials requests containing the 'offline_access' scope. // See https://tools.ietf.org/html/rfc6749#section-4.4.3 for more information. if (context.Request.IsClientCredentialsGrantType() && context.Request.HasScope(OpenIddictConstants.Scopes.OfflineAccess)) { context.Reject( error: OpenIddictConstants.Errors.InvalidRequest, description: "The 'offline_access' scope is not valid for the specified 'grant_type' parameter."); return; } // Validates scopes, unless scope validation was explicitly disabled. if (!options.DisableScopeValidation) { var scopes = new HashSet <string>(context.Request.GetScopes(), StringComparer.Ordinal); scopes.ExceptWith(options.Scopes); // If all the specified scopes are registered in the options, avoid making a database lookup. if (scopes.Count != 0) { foreach (var scope in await _scopeManager.FindByNamesAsync(scopes.ToImmutableArray())) { scopes.Remove(await _scopeManager.GetNameAsync(scope)); } } // If at least one scope was not recognized, return an error. if (scopes.Count != 0) { _logger.LogError("The token request was rejected because invalid scopes were specified: {Scopes}.", scopes); context.Reject( error: OpenIddictConstants.Errors.InvalidScope, description: "The specified 'scope' parameter is not valid."); return; } } // Optimization: the OpenID Connect server middleware automatically rejects grant_type=client_credentials // requests when validation is skipped but an earlier check is made here to avoid making unnecessary // database roundtrips to retrieve the client application corresponding to the client_id. if (context.Request.IsClientCredentialsGrantType() && (string.IsNullOrEmpty(context.Request.ClientId) || string.IsNullOrEmpty(context.Request.ClientSecret))) { context.Reject( error: OpenIddictConstants.Errors.InvalidRequest, description: "The 'client_id' and 'client_secret' parameters are " + "required when using the client credentials grant."); return; } // At this stage, skip client authentication if the client identifier is missing // or reject the token request if client identification is set as required. // Note: the OpenID Connect server middleware will automatically ensure that // the calling application cannot use an authorization code or a refresh token // if it's not the intended audience, even if client authentication was skipped. if (string.IsNullOrEmpty(context.ClientId)) { // Reject the request if client identification is mandatory. if (!options.AcceptAnonymousClients) { _logger.LogError("The token request was rejected becaused the " + "mandatory client_id parameter was missing or empty."); context.Reject( error: OpenIddictConstants.Errors.InvalidRequest, description: "The mandatory 'client_id' parameter is missing."); return; } _logger.LogDebug("The token request validation process was partially skipped " + "because the 'client_id' parameter was missing or empty."); context.Skip(); return; } // Retrieve the application details corresponding to the requested client_id. var application = await _applicationManager.FindByClientIdAsync(context.ClientId); if (application == null) { _logger.LogError("The token request was rejected because the client " + "application was not found: '{ClientId}'.", context.ClientId); context.Reject( error: OpenIddictConstants.Errors.InvalidClient, description: "The specified 'client_id' parameter is invalid."); return; } // Reject the request if the application is not allowed to use the token endpoint. if (!options.IgnoreEndpointPermissions && !await _applicationManager.HasPermissionAsync(application, OpenIddictConstants.Permissions.Endpoints.Token)) { _logger.LogError("The token request was rejected because the application '{ClientId}' " + "was not allowed to use the token endpoint.", context.ClientId); context.Reject( error: OpenIddictConstants.Errors.UnauthorizedClient, description: "This client application is not allowed to use the token endpoint."); return; } if (!options.IgnoreGrantTypePermissions) { // Reject the request if the application is not allowed to use the specified grant type. if (!await _applicationManager.HasPermissionAsync(application, OpenIddictConstants.Permissions.Prefixes.GrantType + context.Request.GrantType)) { _logger.LogError("The token request was rejected because the application '{ClientId}' was not allowed to " + "use the specified grant type: {GrantType}.", context.ClientId, context.Request.GrantType); context.Reject( error: OpenIddictConstants.Errors.UnauthorizedClient, description: "This client application is not allowed to use the specified grant type."); return; } // Reject the request if the offline_access scope was request and if // the application is not allowed to use the refresh token grant type. if (context.Request.HasScope(OpenIddictConstants.Scopes.OfflineAccess) && !await _applicationManager.HasPermissionAsync(application, OpenIddictConstants.Permissions.GrantTypes.RefreshToken)) { _logger.LogError("The token request was rejected because the application '{ClientId}' " + "was not allowed to request the 'offline_access' scope.", context.ClientId); context.Reject( error: OpenIddictConstants.Errors.InvalidRequest, description: "The client application is not allowed to use the 'offline_access' scope."); return; } } // Unless permission enforcement was explicitly disabled, ensure // the client application is allowed to use the specified scopes. if (!options.IgnoreScopePermissions) { foreach (var scope in context.Request.GetScopes()) { // Avoid validating the "openid" and "offline_access" scopes as they represent protocol scopes. if (string.Equals(scope, OpenIddictConstants.Scopes.OfflineAccess, StringComparison.Ordinal) || string.Equals(scope, OpenIddictConstants.Scopes.OpenId, StringComparison.Ordinal)) { continue; } // Reject the request if the application is not allowed to use the iterated scope. if (!await _applicationManager.HasPermissionAsync(application, OpenIddictConstants.Permissions.Prefixes.Scope + scope)) { _logger.LogError("The token request was rejected because the application '{ClientId}' " + "was not allowed to use the scope {Scope}.", context.ClientId, scope); context.Reject( error: OpenIddictConstants.Errors.InvalidRequest, description: "This client application is not allowed to use the specified scope."); return; } } } if (await _applicationManager.IsPublicAsync(application)) { // Note: public applications are not allowed to use the client credentials grant. if (context.Request.IsClientCredentialsGrantType()) { _logger.LogError("The token request was rejected because the public client application '{ClientId}' " + "was not allowed to use the client credentials grant.", context.Request.ClientId); context.Reject( error: OpenIddictConstants.Errors.UnauthorizedClient, description: "The specified 'grant_type' parameter is not valid for this client application."); return; } // Reject token requests containing a client_secret when the client is a public application. if (!string.IsNullOrEmpty(context.ClientSecret)) { _logger.LogError("The token request was rejected because the public application '{ClientId}' " + "was not allowed to send a client secret.", context.ClientId); context.Reject( error: OpenIddictConstants.Errors.InvalidRequest, description: "The 'client_secret' parameter is not valid for this client application."); return; } _logger.LogDebug("The token request validation process was not fully validated because " + "the client '{ClientId}' was a public application.", context.ClientId); // If client authentication cannot be enforced, call context.Skip() to inform // the OpenID Connect server middleware that the caller cannot be fully trusted. context.Skip(); return; } // Confidential and hybrid applications MUST authenticate // to protect them from impersonation attacks. if (string.IsNullOrEmpty(context.ClientSecret)) { _logger.LogError("The token request was rejected because the confidential or hybrid application " + "'{ClientId}' didn't specify a client secret.", context.ClientId); context.Reject( error: OpenIddictConstants.Errors.InvalidClient, description: "The 'client_secret' parameter required for this client application is missing."); return; } if (!await _applicationManager.ValidateClientSecretAsync(application, context.ClientSecret)) { _logger.LogError("The token request was rejected because the confidential or hybrid application " + "'{ClientId}' didn't specify valid client credentials.", context.ClientId); context.Reject( error: OpenIddictConstants.Errors.InvalidClient, description: "The specified client credentials are invalid."); return; } context.Validate(); await _eventDispatcher.DispatchAsync(new OpenIddictServerEvents.ValidateTokenRequest(context)); }
public override async Task ValidateTokenRequest([NotNull] ValidateTokenRequestContext context) { var applications = context.HttpContext.RequestServices.GetRequiredService <OpenIddictApplicationManager <TApplication> >(); var logger = context.HttpContext.RequestServices.GetRequiredService <ILogger <OpenIddictProvider <TApplication, TAuthorization, TScope, TToken> > >(); var options = context.HttpContext.RequestServices.GetRequiredService <IOptions <OpenIddictOptions> >(); // Reject token requests that don't specify a supported grant type. if (!options.Value.GrantTypes.Contains(context.Request.GrantType)) { logger.LogError("The token request was rejected because the '{Grant}' " + "grant is not supported.", context.Request.GrantType); context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "The specified grant_type is not supported by this authorization server."); return; } // Reject token requests that specify scope=offline_access if the refresh token flow is not enabled. if (context.Request.HasScope(OpenIdConnectConstants.Scopes.OfflineAccess) && !options.Value.GrantTypes.Contains(OpenIdConnectConstants.GrantTypes.RefreshToken)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The 'offline_access' scope is not allowed."); return; } // Optimization: the OpenID Connect server middleware automatically rejects grant_type=authorization_code // requests missing the redirect_uri parameter if one was specified in the initial authorization request. // Since OpenIddict doesn't allow redirect_uri-less authorization requests, an earlier check can be made here, // which saves the OpenID Connect server middleware from having to deserialize the authorization code ticket. // See http://openid.net/specs/openid-connect-core-1_0.html#TokenRequestValidation for more information. if (context.Request.IsAuthorizationCodeGrantType() && string.IsNullOrEmpty(context.Request.RedirectUri)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The mandatory 'redirect_uri' parameter was missing."); return; } // Note: the OpenID Connect server middleware allows returning a refresh token with grant_type=client_credentials, // though it's usually not recommended by the OAuth2 specification. To encourage developers to make a new // grant_type=client_credentials request instead of using refresh tokens, OpenIddict uses a stricter policy // that rejects grant_type=client_credentials requests containing the 'offline_access' scope. // See https://tools.ietf.org/html/rfc6749#section-4.4.3 for more information. if (context.Request.IsClientCredentialsGrantType() && context.Request.HasScope(OpenIdConnectConstants.Scopes.OfflineAccess)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The 'offline_access' scope is not allowed when using grant_type=client_credentials."); return; } // Optimization: the OpenID Connect server middleware automatically rejects grant_type=client_credentials // requests when validation is skipped but an earlier check is made here to avoid making unnecessary // database roundtrips to retrieve the client application corresponding to the client_id. if (context.Request.IsClientCredentialsGrantType() && (string.IsNullOrEmpty(context.Request.ClientId) || string.IsNullOrEmpty(context.Request.ClientSecret))) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "Client applications must be authenticated to use the client credentials grant."); return; } // At this stage, skip client authentication if the client identifier is missing // or reject the token request if client identification is set as required. // Note: the OpenID Connect server middleware will automatically ensure that // the calling application cannot use an authorization code or a refresh token // if it's not the intended audience, even if client authentication was skipped. if (string.IsNullOrEmpty(context.ClientId)) { // Reject the request if client identification is mandatory. if (options.Value.RequireClientIdentification) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The mandatory 'client_id' parameter was missing."); return; } logger.LogDebug("The token request validation process was partially skipped " + "because the 'client_id' parameter was missing or empty."); context.Skip(); return; } // Retrieve the application details corresponding to the requested client_id. var application = await applications.FindByClientIdAsync(context.ClientId, context.HttpContext.RequestAborted); if (application == null) { logger.LogError("The token request was rejected because the client " + "application was not found: '{ClientId}'.", context.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Application not found in the database: ensure that your client_id is correct."); return; } if (await applications.IsPublicAsync(application, context.HttpContext.RequestAborted)) { // Note: public applications are not allowed to use the client credentials grant. if (context.Request.IsClientCredentialsGrantType()) { logger.LogError("The token request was rejected because the public client application '{ClientId}' " + "was not allowed to use the client credentials grant.", context.Request.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.UnauthorizedClient, description: "Public clients are not allowed to use the client credentials grant."); return; } // Reject tokens requests containing a client_secret when the client is a public application. if (!string.IsNullOrEmpty(context.ClientSecret)) { logger.LogError("The token request was rejected because the public application '{ClientId}' " + "was not allowed to send a client secret.", context.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "Public clients are not allowed to send a client_secret."); return; } logger.LogInformation("The token request validation process was not fully validated because " + "the client '{ClientId}' was a public application.", context.ClientId); // If client authentication cannot be enforced, call context.Skip() to inform // the OpenID Connect server middleware that the caller cannot be fully trusted. context.Skip(); return; } // Confidential applications MUST authenticate // to protect them from impersonation attacks. if (string.IsNullOrEmpty(context.ClientSecret)) { logger.LogError("The token request was rejected because the confidential application " + "'{ClientId}' didn't specify a client secret.", context.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Missing credentials: ensure that you specified a client_secret."); return; } if (!await applications.ValidateClientSecretAsync(application, context.ClientSecret, context.HttpContext.RequestAborted)) { logger.LogError("The token request was rejected because the confidential application " + "'{ClientId}' didn't specify valid client credentials.", context.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Invalid credentials: ensure that you specified a correct client_secret."); return; } context.Validate(); }
public override async Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Note: OpenIdConnectServerHandler supports authorization code, refresh token, // client credentials, resource owner password credentials and custom grants // but this authorization server uses a stricter policy rejecting custom grant types. if (!context.Request.IsAuthorizationCodeGrantType() && !context.Request.IsRefreshTokenGrantType() && !context.Request.IsPasswordGrantType() && !context.Request.IsClientCredentialsGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only authorization code, refresh token, client credentials " + "and password grants are accepted by this authorization server."); return; } // Note: though required by the OpenID Connect specification for the refresh token grant, // client authentication is not mandatory for non-confidential client applications in OAuth2. // To avoid breaking OAuth2 scenarios, OpenIddict uses a relaxed policy that allows // public applications to use the refresh token grant without having to authenticate. // See http://openid.net/specs/openid-connect-core-1_0.html#RefreshingAccessToken // and https://tools.ietf.org/html/rfc6749#section-6 for more information. // Skip client authentication if the client identifier is missing. // Note: ASOS will automatically ensure that the calling application // cannot use an authorization code or a refresh token if it's not // the intended audience, even if client authentication was skipped. if (string.IsNullOrEmpty(context.ClientId)) { context.Skip(); return; } //var database = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>(); var clientMgr = context.HttpContext.RequestServices.GetRequiredService <OidcClientManager>(); // Retrieve the application details corresponding to the requested client_id. var application = clientMgr.FindByClientId(context.ClientId); if (application == null) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Application not found in the database: ensure that your client_id is correct"); return; } // Openiddict的做法不同,而是区分Public 和 Confidential,public的禁止传送client_secret if (!string.Equals(context.ClientSecret, application.Secret, StringComparison.Ordinal)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Invalid credentials: ensure that you specified a correct client_secret"); return; } context.Validate(); }
// // Summary: // Represents an event called for each request to the token endpoint to determine // if the request is valid and should continue to be processed. // // Parameters: // context: // The context instance associated with this event. // // Returns: // A System.Threading.Tasks.Task that can be used to monitor the asynchronous operation. public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { // Reject the token request if it doesn't specify grant_type=authorization_code, // grant_type=password or grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType() && !context.Request.IsClientCredentialsGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only authorization code, refresh token, client credentials grant types " + "are accepted by this authorization server."); return(Task.CompletedTask); } // Note: client authentication is not mandatory for non-confidential client applications like mobile apps // (except when using the client credentials grant type) but this authorization server uses a safer policy // that makes client authentication mandatory and returns an error if client_id or client_secret is missing. // You may consider relaxing it to support the resource owner password credentials grant type // with JavaScript or desktop applications, where client credentials cannot be safely stored. // In this case, call context.Skip() to inform the server middleware the client is not trusted. if (context.Request.IsClientCredentialsGrantType()) { if (string.IsNullOrEmpty(context.ClientId) || string.IsNullOrEmpty(context.ClientSecret)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The mandatory 'client_id'/'client_secret' parameters are missing."); return(Task.CompletedTask); } var client = _authService.FindUser(u => u.Id.ToString() == context.ClientId); if (client == null) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "The specified client identifier is invalid."); return(Task.CompletedTask); } // Note: to mitigate brute force attacks, you SHOULD strongly consider applying // a key derivation function like PBKDF2 to slow down the secret validation process. // You SHOULD also consider using a time-constant comparer to prevent timing attacks. // For that, you can use the CryptoHelper library developed by @henkmollema: // https://github.com/henkmollema/CryptoHelper. if (!_authService.ValidateRequestedClientCredentials(client, context.ClientId, context.ClientSecret)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "The specified client credentials are invalid."); return(Task.CompletedTask); } context.Validate(); } else { context.Skip(); } return(Task.CompletedTask); }
public override async Task ValidateTokenRequest(ValidateTokenRequestContext context) { var request = context.Request; if (!request.IsAuthorizationCodeGrantType() && !request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: InvalidGrantMessage ); return; } if (string.IsNullOrWhiteSpace(context.ClientId)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: InvalidClientMessage ); return; } var application = await BookingContext.Applications .Where(a => a.Id == context.ClientId) .SingleOrDefaultAsync(context.HttpContext.RequestAborted); if (application == null || application.Type == ApplicationType.Introspection) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: InvalidClientMessage ); return; } if (application.Type == ApplicationType.Public) { if (!string.IsNullOrEmpty(context.ClientSecret)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: InvalidClientMessage ); return; } context.Skip(); return; } if (!PasswordHasher.VerifyHashedPassword(application.Secret, context.ClientSecret)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: InvalidClientMessage ); return; } context.Validate(); }
public override async Task ValidateTokenRequest([NotNull] ValidateTokenRequestContext context) { var services = context.HttpContext.RequestServices.GetRequiredService <OpenIddictServices <TUser, TApplication> >(); // Note: OpenIdConnectServerHandler supports authorization code, refresh token, // client credentials, resource owner password credentials and custom grants // but this authorization server uses a stricter policy rejecting custom grant types. if (!context.Request.IsAuthorizationCodeGrantType() && !context.Request.IsRefreshTokenGrantType() && !context.Request.IsPasswordGrantType() && !context.Request.IsClientCredentialsGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only authorization code, refresh token, client credentials " + "and password grants are accepted by this authorization server."); return; } // Note: though required by the OpenID Connect specification for the refresh token grant, // client authentication is not mandatory for non-confidential client applications in OAuth2. // To avoid breaking OAuth2 scenarios, OpenIddict uses a relaxed policy that allows // public applications to use the refresh token grant without having to authenticate. // See http://openid.net/specs/openid-connect-core-1_0.html#RefreshingAccessToken // and https://tools.ietf.org/html/rfc6749#section-6 for more information. // Skip client authentication if the client identifier is missing. // Note: ASOS will automatically ensure that the calling application // cannot use an authorization code or a refresh token if it's not // the intended audience, even if client authentication was skipped. if (string.IsNullOrEmpty(context.ClientId)) { context.Skip(); return; } // Retrieve the application details corresponding to the requested client_id. var application = await services.Applications.FindApplicationByIdAsync(context.ClientId); if (application == null) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Application not found in the database: ensure that your client_id is correct."); return; } // Reject tokens requests containing a client_secret if the client application is not confidential. if (await services.Applications.IsPublicApplicationAsync(application) && !string.IsNullOrEmpty(context.ClientSecret)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "Public clients are not allowed to send a client_secret."); return; } // Confidential applications MUST authenticate // to protect them from impersonation attacks. else if (await services.Applications.IsConfidentialApplicationAsync(application)) { if (string.IsNullOrEmpty(context.ClientSecret)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Missing credentials: ensure that you specified a client_secret."); return; } if (!await services.Applications.ValidateSecretAsync(application, context.ClientSecret)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Invalid credentials: ensure that you specified a correct client_secret."); return; } } context.Validate(); }
public override Task ValidateTokenRequest(ValidateTokenRequestContext context) { context.Skip(); return(Task.FromResult <object>(null)); }
public override async Task ValidateTokenRequest([NotNull] ValidateTokenRequestContext context) { var services = context.HttpContext.RequestServices.GetRequiredService <OpenIddictServices <TUser, TApplication, TAuthorization, TScope, TToken> >(); // Reject token requests that don't specify a supported grant type. if (!services.Options.GrantTypes.Contains(context.Request.GrantType)) { services.Logger.LogError("The token request was rejected because the '{Grant}' " + "grant is not supported.", context.Request.GrantType); context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "The specified grant_type is not supported by this authorization server."); return; } // Reject token requests that specify scope=offline_access if the refresh token flow is not enabled. if (context.Request.HasScope(OpenIdConnectConstants.Scopes.OfflineAccess) && !services.Options.IsRefreshTokenFlowEnabled()) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The 'offline_access' scope is not allowed."); return; } // Note: the OpenID Connect server middleware allows returning a refresh token with grant_type=client_credentials, // though it's usually not recommended by the OAuth2 specification. To encourage developers to make a new // grant_type=client_credentials request instead of using refresh tokens, OpenIddict uses a stricter policy // that rejects grant_type=client_credentials requests containing the 'offline_access' scope. // See https://tools.ietf.org/html/rfc6749#section-4.4.3 for more information. if (context.Request.IsClientCredentialsGrantType() && context.Request.HasScope(OpenIdConnectConstants.Scopes.OfflineAccess)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The 'offline_access' scope is not allowed when using grant_type=client_credentials."); return; } // Note: the OpenID Connect server middleware rejects grant_type=client_credentials requests // when validation is skipped but an early check is made here to avoid making unnecessary // database roundtrips to retrieve the client application corresponding to the client_id. if (context.Request.IsClientCredentialsGrantType() && (string.IsNullOrEmpty(context.Request.ClientId) || string.IsNullOrEmpty(context.Request.ClientSecret))) { services.Logger.LogError("The token request was rejected because the client credentials were missing."); context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "Client applications must be authenticated to use the client credentials grant."); return; } // Note: though required by the OpenID Connect specification for the refresh token grant, // client authentication is not mandatory for non-confidential client applications in OAuth2. // To avoid breaking OAuth2 scenarios, OpenIddict uses a relaxed policy that allows // public applications to use the refresh token grant without having to authenticate. // See http://openid.net/specs/openid-connect-core-1_0.html#RefreshingAccessToken // and https://tools.ietf.org/html/rfc6749#section-6 for more information. // At this stage, skip client authentication if the client identifier is missing. // Note: the OpenID Connect server middleware will automatically ensure that // the calling application cannot use an authorization code or a refresh token // if it's not the intended audience, even if client authentication was skipped. if (string.IsNullOrEmpty(context.ClientId)) { services.Logger.LogInformation("The token request validation process was skipped " + "because the client_id parameter was missing or empty."); context.Skip(); return; } // Retrieve the application details corresponding to the requested client_id. var application = await services.Applications.FindByClientIdAsync(context.ClientId); if (application == null) { services.Logger.LogError("The token request was rejected because the client " + "application was not found: '{ClientId}'.", context.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Application not found in the database: ensure that your client_id is correct."); return; } if (await services.Applications.IsPublicAsync(application)) { // Note: public applications are not allowed to use the client credentials grant. if (context.Request.IsClientCredentialsGrantType()) { services.Logger.LogError("The token request was rejected because the public client application '{ClientId}' " + "was not allowed to use the client credentials grant.", context.Request.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.UnauthorizedClient, description: "Public clients are not allowed to use the client credentials grant."); return; } // Reject tokens requests containing a client_secret when the client is a public application. if (!string.IsNullOrEmpty(context.ClientSecret)) { services.Logger.LogError("The token request was rejected because the public application '{ClientId}' " + "was not allowed to send a client secret.", context.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "Public clients are not allowed to send a client_secret."); return; } services.Logger.LogInformation("The token request validation process was not fully validated because " + "the client '{ClientId}' was a public application.", context.ClientId); // If client authentication cannot be enforced, call context.Skip() to inform // the OpenID Connect server middleware that the caller cannot be fully trusted. context.Skip(); return; } // Confidential applications MUST authenticate // to protect them from impersonation attacks. if (string.IsNullOrEmpty(context.ClientSecret)) { services.Logger.LogError("The token request was rejected because the confidential application " + "'{ClientId}' didn't specify a client secret.", context.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Missing credentials: ensure that you specified a client_secret."); return; } if (!await services.Applications.ValidateSecretAsync(application, context.ClientSecret)) { services.Logger.LogError("The token request was rejected because the confidential application " + "'{ClientId}' didn't specify valid client credentials.", context.ClientId); context.Reject( error: OpenIdConnectConstants.Errors.InvalidClient, description: "Invalid credentials: ensure that you specified a correct client_secret."); return; } context.Validate(); }