Not able to call web service protected by gatekeeper- keycloak via ajax request - keycloak

I have webservice protected by gatekeeper(louketo-proxy). When I call protected service via ajax request it won't redirect me to login page. It's showing me message "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:3000/app-name/api/getSession. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."
Below is the gatekeeper configuration file:
client-id: app_id
client-secret: app_secret
discovery-url: http://127.0.0.1:8080/auth/realms/app_realm
redirection-url: http://127.0.0.1:3000
upstream-url: http://127.0.0.1:8043
enable-logging: true
enable-json-logging: true
verbose: true
enable-session-cookies: true
skip-upstream-tls-verify: true
skip-openid-provider-tls-verify: true
encryption-key: enc_key
listen: 0.0.0.0:3000
secure-cookie: false
enable-logging: true
enable-json-logging: true
enable-refresh-tokens: true
enable-session-cookies: true
enable-cors: true
cors-max-age : 1000
cors-headers:
- Accept
- Content-Type
- Cache-Control
- Pragma
- X-Custom-Header
- Source
debug: true
resources:
- uri: /app/api/v5/stylesheets/key=CSS
white-listed: true
- uri: /app/api/v5/images/key=FAVICON
white-listed: true
- uri: /app/api/v5/*
Keycloak version which I am using is 10.0.2

Did you try to define some allowed CORS origins, like
cors-origins:
- '*'
to try out what happens if you allow everything?

Related

ContainerApp Revision Failed when using dapr

I have created containerapp environment with one containerapp using Bicep template and here is a snippet of how I configured the environment
ingress: {
external: true
targetPort: 80
allowInsecure: false
transport:'http2'
traffic:[
{
latestRevision: true
weight: 100
}
]
}
registries: [
{
server: acr_login_server
username: acr_name
passwordSecretRef: 'myregistrypassword'
}
]
dapr: {
appId: containerapp_name
appPort: 80
appProtocol: 'http'
enabled: true
}
}
I am using http2 transport cause we expose grpc service as well, then when checking the revision, it shows failed and the logs shows that there is issue with dapr
time="2022-10-19T10:35:35.391746798Z" level=fatal msg="error loading configuration: rpc error: code = Unavailable desc = connection error: desc = \"transport: authentication handshake failed: x509: certificate signed by unknown authority (possibly because of \\\"x509: ECDSA verification failure\\\" while trying to verify candidate authority certificate \\\"cluster.local\\\")\"" app_id=containerapp-a instance=containerapp-a--t1gheb2-77c44cf6c6-rxjwx scope=dapr.runtime type=log ver=1.8.4-msft-2

JWT token not found 401

When I try to get JWT token with Symfony 6 / Api-plateform / lexik/jwt-authentication-bundle on the endpoint defined on my route.yaml
authentication_token:
path: /api/login
methods: ['POST']
The return of API is this :
{
"code": 401,
"message": "JWT Token not found"
}
The key was setting in my .env and the file of the key was already created.
security.yaml
main:
stateless: true
provider: app_user_provider
json_login:
check_path: /authentication_token
username_path: email
password_path: password
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
jwt: ~
I have checked if all the config files was present and if the jwt config key and files was created.
The endpoint was created and security.yaml if configured.

Create Symfony Bundle for rest API

I'm working on symfony 3 project , I have a bundle for Admin dashboard and I want to create another bundle for a rest API , the main route for the dashboard is : evaluation.dev/app_dev.php/ , for the API bundle i defined a route with fosrestBundle like that : evaluation.dev/app_dev.php/api/ .
The route for the api work well but the main rout for my admin panel does not work anymore and show me an internal server error. can any one give some help ? I think I should change some thing on the configuration or routing file.
This is my routing.yml file :
fos_user_security:
resource: "#FOSUserBundle/Resources/config/routing/security.xml"
fos_user_profile:
resource: "#FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile
fos_user_register:
resource: "#FOSUserBundle/Resources/config/routing/registration.xml"
prefix: /register
fos_user_resetting:
resource: "#FOSUserBundle/Resources/config/routing/resetting.xml"
prefix: /resetting
fos_user_change_password:
resource: "#FOSUserBundle/Resources/config/routing/change_password.xml"
prefix: /profile
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
eval:
resource: "#EvalBundle/Controller/"
type: annotation
prefix: /
app:
resource: '#AppBundle/Controller/'
type: annotation
api:
resource: "#APIBundle/Controller/"
type: annotation
prefix: /api
here is my config.yml file :
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "#EvalBundle/Resources/config/services.yml" }
- { resource: "#EvalBundle/Resources/config/entities.yml" }
# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: en
assetic:
debug: '%kernel.debug%'
use_controller: '%kernel.debug%'
filters:
cssrewrite: ~
framework:
#esi: ~
#translator: { fallbacks: ['%locale%'] }
secret: '%secret%'
router:
resource: '%kernel.root_dir%/config/routing.yml'
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
templating:
engines: ['twig']
default_locale: '%locale%'
trusted_hosts: ~
trusted_proxies: ~
session:
# http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
handler_id: session.handler.native_file
save_path: "%kernel.root_dir%/../var/sessions/%kernel.environment%"
fragments: ~
http_method_override: true
assets: ~
php_errors:
log: true
translator: ~
serializer:
enabled: true
# Twig Configuration
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
cache: false
form_themes :
- bootstrap_3_layout.html.twig
- bootstrap_3_horizontal_layout.html.twig
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
mapping_types:
enum: string
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/../var/data/data.sqlite"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
#path: '%database_path%'
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: EvalBundle\Entity\Collaborator
from_email:
address: amer.ff19#gmail.com
sender_name: amer ff
knp_paginator:
page_range: 1 # default page range used in pagination control
default_options:
page_name: page # page query parameter name
sort_field_name: sort # sort field query parameter name
sort_direction_name: direction # sort direction query parameter name
distinct: true # ensure distinct results, useful when ORM queries are using GROUP BY statements
template:
pagination: 'KnpPaginatorBundle:Pagination:twitter_bootstrap_v3_pagination.html.twig' # sliding pagination controls template
sortable: 'KnpPaginatorBundle:Pagination:sortable_link.html.twig' # sort link template
fos_rest:
routing_loader:
include_format: false
view:
view_response_listener: true
format_listener:
rules:
- { path: '^/', priorities: ['json'], fallback_format: 'json' }

Custom WebserviceUserProvider and FOSAuthServerBundle

I'm using an SF2.8 API based on this tutorial https://gist.github.com/tjamps/11d617a4b318d65ca583 except i'm using MongoDB.
When a FOSUser (created on my DB A with oAuth tables) is connected to my API, i don't have all infos what i need because there are an other database.
I found a SF doc which explain how to custom symfony default authentication by replacing the default FOS User provider with a custom user provider.
So I decided to create the same architecture on this doc : http://symfony.com/doc/2.8/security/custom_provider.html
Before asking my oAuth token in /oauth/v2/token by HTTP Post request, my overrided loadUserByUsername method call an external API and instanciate a WebserviceUser which contain a user companies's collection in addition to having basic fields like username, password, salt etc. needed to connect.
After loadUserByUsername call, oAuth try to flush the generated accesstoken to the connected user into DB, but an exception is thrown because the User document to persist in AccessToken document is a AppBundle\Security\User\WebserviceUser instead of AppBundle\Document\User (child of FOSUser Document) so the mapping fail while persisting.
I got this :
The class 'AppBundle\Security\User\WebserviceUser' was not found in the chain configured namespaces AppBundle\Document, FOS\UserBundle\Document, FOS\OAuthServerBundle\Document (500 Internal Server Error)
Did I do something wrong ?
EDIT : My new loadUserByUsername method :
public function loadUserByUsername($username)
{
$apiUser = $this->manager->getRepository('AppBundle:User')->findOneByUsername($username);
if (is_null($apiUser)) {
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
$userData = $this->client->httpGetList("user", ['filter_usrMail' => $apiUser->getEmail()]);
$userData = $userData[array_keys($userData)[0]];
$companies = isset($userData['usrCompany']) ? $userData['usrCompany'] : [];
if ($userData) {
$role = isset($userData['usrRole']) ? [$userData['usrRole']] : ['ROLE_USER'];
$user = new WebserviceUser($apiUser->getUsername(), $apiUser->getPassword(), $apiUser->getSalt(), $apiUser->getRoles());
$user->setCompanies($companies);
$user->setApiUsername($apiUser->getUsername());
return $user;
}
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
fos_oauth_server yml conf :
db_driver: mongodb
client_class: AppBundle\Document\Client
access_token_class: AppBundle\Document\AccessToken
refresh_token_class: AppBundle\Document\RefreshToken
auth_code_class: AppBundle\Document\AuthCode
service:
user_provider: app.webservice_user_provider
services.yml conf :
app.webservice_user_provider:
class: AppBundle\Security\User\WebserviceUserProvider
arguments: ['#my_communicator.client', '#session', '#doctrine.odm.mongodb.document_manager', '%session_refresh_ttl%']
security.yml conf :
encoders:
AppBundle\Security\User\WebserviceUser: bcrypt
FOS\UserBundle\Model\UserInterface: bcrypt
providers:
webservice:
id: app.webservice_user_provider
#in_memory:
# memory: ~
fos_userbundle:
id: fos_user.user_provider.username
role_hierarchy:
ROLE_ADMIN: ROLE_USER
firewalls:
oauth_token: # Everyone can access the access token URL.
pattern: ^/oauth/v2/token
security: false
api:
pattern: ^\/api(?!\/doc|\/v[0-9][\.0-9]*\/core(\/createaccount|\/clients)) # All URLs are protected (except api doc and api create account)
fos_oauth: true # OAuth2 protected resource
stateless: true # Do no set session cookies
anonymous: false # Anonymous access is not allowed
access_denied_handler: app.listener.access_denied.handler
apidoc:
pattern: ^\/api\/doc
anonymous: false
security: false
access_control:
- { path: ^\/api\/v[0-9][\.0-9]*\/(?!(admin|core)), roles: ROLE_USER }
- { path: ^\/api\/v[0-9][\.0-9]*\/(admin|core)(?!(\/createaccount|\/clients)), roles: ROLE_ADMIN }
- { path: ^\/api\/v[0-9][\.0-9]*\/core(\/createaccount|\/clients), roles: IS_AUTHENTICATED_ANONYMOUSLY, ips: [127.0.0.1, localhost, ::1] }
- { path: ^\/api\/v[0-9][\.0-9]*\/core(\/createaccount|\/clients), roles: ROLE_NO_ACCESS }
access_decision_manager:
strategy: unanimous

Issues with Symfony2 and Sonata Admin Bundle - Dashboard Login Area

I have a issues about configuration Symfony 2.5 and Sonata Admin Bundle. I have tried to fix it [by searching on google.com, reading carefully on sonata-project.org ] but the issues still appear. So I hope everyone will support me to fix it.
Please see the detail below what I configured:
Configuration of security.yml
parameters:
security.acl.permission.map.class: Sonata\AdminBundle\Security\Acl\Permission\AdminPermissionMap
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
SONATA:
# if you are not using acl then this line must be uncommented
- ROLE_SONATA_PAGE_ADMIN_PAGE_EDIT
#- ROLE_SONATA_PAGE_ADMIN_BLOCK_EDIT
providers:
fos_userbundle:
id: fos_user.user_manager
firewalls:
# Disabling the security for the web debug toolbar, the profiler and Assetic.
dev:
pattern: ^/(_(profiler|wdt)|css|images|js|admin/_(wdt|profiler)|api/_(wdt|profiler))/
security: false
# This firewall is used to handle the admin login area
# This part is handled by the Sonata User Bundle
admin:
pattern: /admin(.*)
context: user
form_login:
provider: fos_userbundle
login_path: /admin/login
use_forward: false
check_path: /admin/login_check
default_target_path: /admin/dashboard
failure_path: null
always_use_default_target_path: true
logout:
path: /admin/logout
target: /admin/login
anonymous: true
# This firewall is used to handle the public login area
# This part is handled by the FOS User Bundle
access_control:
# Admin login page needs to be access without credential
- { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/login-check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
# Secured part of the site
# This config requires being logged for the whole site and having the admin role for the admin part.
# It also secures the shop checkout process
# Change these rules to adapt them to your needs
- { path: ^/admin, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN] }
- { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
acl:
connection: default
Configuration of sonata/sonata_admin.yml [ this file is be include at config.yml ]
sonata_admin:
security:
handler: sonata.admin.security.handler.acl
# acl security information
information:
GUEST: [VIEW, LIST]
STAFF: [EDIT, LIST, CREATE]
EDITOR: [OPERATOR, EXPORT]
ADMIN: [MASTER]
# permissions not related to an object instance and also to be available when objects do not exist
# the DELETE admin permission means the user is allowed to batch delete objects
admin_permissions: [CREATE, LIST, DELETE, UNDELETE, EXPORT, OPERATOR, MASTER]
# permission related to the objects
object_permissions: [VIEW, EDIT, DELETE, UNDELETE, OPERATOR, MASTER, OWNER]
dashboard:
blocks:
- { position: left, type: sonata.block.service.text, settings: { content: "<div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>Welcome!</h3></div><div class='panel-body'>You can customize this dashboard by editing the <code>sonata_admin.yml</code> file. The current dashboard presents the recent items from the NewsBundle and a non-statistical e-commerce information.</div></div>"} }
- { position: right, type: sonata.block.service.rss, settings: { title: Sonata Project's Feeds, url: http://sonata-project.org/blog/archive.rss, template: SonataAdminBundle:Block:block_rss_dashboard.html.twig }}
groups:
sonata.admin.group.administration:
label: sonata_administration
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-cogs"></i>'
items:
- sonata.user.admin.user
- sonata.user.admin.group
Configuration of sonata/sonata_block.yml [ this file is be include at config.yml ]
sonata_block:
default_contexts: [cms]
blocks:
sonata.admin.block.admin_list:
contexts: [admin]
sonata.block.service.text:
sonata.block.service.rss:
Configuration of fos/fos_user.yml [ this file is be include at config.yml ]
fos_user:
db_driver: orm # can be orm or odm
firewall_name: main
# if you change the class configuration, please also alter the sonata_user.yml file
user_class: Application\Sonata\UserBundle\Entity\User
group:
group_class: Application\Sonata\UserBundle\Entity\Group
Configuration of routing.yml
_admin:
resource: routing_admin.yml
prefix: /admin
Configuration of routing_admin.yml [ this file is be include at routing.yml ]
admin:
resource: '#SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
_sonata_admin:
resource: .
type: sonata_admin
soanata_user_admin:
resource: '#SonataUserBundle/Resources/config/routing/admin_security.xml'
A part of require in composer.json
"require": {
"php": ">=5.3.3",
"symfony/symfony": "2.5.*",
"doctrine/orm": "~2.2,>=2.2.3",
"doctrine/doctrine-bundle": "~1.2",
"twig/extensions": "~1.0",
"symfony/assetic-bundle": "~2.3",
"symfony/swiftmailer-bundle": "~2.3",
"symfony/monolog-bundle": "~2.4",
"sensio/distribution-bundle": "~3.0",
"sensio/framework-extra-bundle": "~3.0",
"incenteev/composer-parameter-handler": "~2.0",
"sonata-project/admin-bundle": "dev-master",
"sonata-project/doctrine-orm-admin-bundle": "dev-master",
"sonata-project/easy-extends-bundle": "dev-master",
"sonata-project/user-bundle": "~2.2#dev
Screenshot of Issue
Please visit at : https://plus.google.com/u/0/110571324794293900613/posts/fHW9fz2sYHH?pid=6032630377545776242&oid=110571324794293900613
Finally, I very thanks for everyone.
Waiting a good news from u !
Thanks
You should override the standard_layout.html.twig file to make change according to you ..