I want to know if I can modify the URL path if I try going the Application page for Oauth2 when I am not logged in. Basically, I want to reuse the Admin login for the user to login and then redirect them to the Application page.
# Current URL
http://localhost:8000/accounts/login/?next=/o/applications/
# Desired URL
# Change 'accounts' to 'admin'
http://localhost:8000/admin/login/?next=/o/applications/
Note:
I got the response I want with the following approach in my root urls.py:
urlpatterns = [
path('admin/', admin.site.urls, name="admin"),
path('accounts/', admin.site.urls, name="account_auth"),
path('o/', include('oauth2_provider.urls', namespace='oath2_provider')),
]
With this, I don't have to change the path but I feel like it's not the right way to do (2 paths/routes for 1 view).
Related
I am writing a Vue app that talks to a Wordpress back end. I am using a plugin called simple-jwt-login and I am able to log in by making a GET request using axios:
const login = await axios.get("http://localhost:10019/", {
params: {
rest_route: "/simple-jwt-login/v1/autologin",
JWT: token,
},
});
The plugin gives you certain variables that you can include in your redirect URL but this is on the back end and I do not use the redirect option because I am using Vue on the front end and want to do the redirect there once logged in.
How do I get those variable values in the front end so i can display the user's name and other information to the user?
I have rerouted all the traffic to my main domain let's say www.example.com and my first page is www.example.com/login so any entry in the subdomain will be redirected to main domain so something.example.com/login will end up on the same page as www.example.com/login (but the subdomain will stay in the url). The reason I am doing this is that i have multi 'clients' and 'users' every user is responsible for one or more client and its all set in the database and working perfectly so i can login with user1 i will see some tasks for user1 on client1 and when i login with user2 i will see tasks from user2 on client2 etc...
Now i need to do one more thing to make it look a bit better, when someone opens example.com and login with user1 credentials i want him to be redirected to client1.example.com and at the same time when someone opens client1.example.com i want him to see the logo from that client.
All the database queries and other login issues are handled but i am facing couple of issues:
how to redirect to the correct client (subdomain) ?
and vice versa if a (super admin) user which responsible for managing clients and users logs in how to redirect him to main domain (example.com) without?
One more issue but i think it will be solved when i can solve the other issues is when a user manages more than one client, i want to give him the ability to switch clients something like user1 have a menu to switch to client1 or client2 but any redirection i make is logging the user out. how can i maintain the session with this feature ?
p.s when different users logs in the (theme) colors and logos of the application are being called from database according to the client and thats why i need to read the subdomain on the first page so i can change the login logo according to the subdomain
this is a piece of my code to see how i am achieving this if anyone is interested
$currentUrl = $request->getHttpHost();
$baseUrl = $this->container->getParameter('base_url');
$subdomain = str_replace('.'.$baseUrl, '',$currentUrl);
if (sizeof($user->getClients()) > 0) {
$filter = $this->em->getFilters()->enable(Utils::CLIENT_FILTER_NAME);
if ($user->getLastLoggedInClient() !== null) {
$client = $user->getLastLoggedInClient();
} else {
$client = $user->getClients()->first();
}
if ($client == null) {
throw new ClientNotFoundException();
}
if(!$client->isActive()){
throw new ClientNotActiveException();
}
$this->session->set(Utils::CLIENT_ID_NAME, $client->getId());
$this->session->set('client', $client);
$filter->setParameter(Utils::CLIENT_ID_NAME, $client->getId());
$user->setLastLoggedInClient($client);
$this->em->persist($user);
$this->em->flush();
}
else{
return new RedirectResponse('/logout');
}
return new RedirectResponse('/');
so i think somewhere around here return new RedirectResponse('/'); i need to redirect to the correct subdomain.
Thanks!
When you first realise that a user needs to login (from client1.example.com), put the URL, or 'client1' client-name into a session, readable on www.example.com - or add it to the URL (like https://www.example.com/login/to/client1 - the route would be '/login/to/{clientname}'), or more simply /login?clientname=client1.
When a user has logged in, and been verified to be a member of 'client1', then the redirection would be to a route like 'client_app_dashboard', ['clientname' => 'client1'] - and a route definition of #Route("/", name="client_app_dashboard", host="{clientname}.example.com")
The Symfony docs have information on How to Match a Route Based on the Host.
As for a logo - that would be fetched and displayed based on the $clientname on the www. homepage.
I am trying to use the NelmioApiDocBundle for a Symfony 3.4 projects API documentation, while also trying to wrap my head around OAuth 2 authorization for the project API access to begin with.
So far I've followed this tutorial on how to get FOSOAuthServerBundle working. So far I can
1.) create a client using the command line command:
php bin/console fos:oauth-server:create-client --redirect-uri="___" --grant-type="authorization_code" --grant-type="password" --grant-type="refresh_token" --grant-type="token" --grant-type="client_credentials"
2.) I can also get an access token manually by visiting this url on my server
http://127.0.0.1:8000/oauth/v2/token?client_id=______&client_secret=________&grant_type=client_credentials
3.) I can use the token to access areas of my Symfony project requiring OAuth Access by including the token in a GET parameter
However, in the NelmioApiDocBundle Authorizations I cannot get this to work to completion. Here is a screenshot:
If enter my client_id and secret key it takes me to the Login Page, as expected. I can enter my login information and in takes me to the Approve or Deny Page, as expected. At this point if I click either Approve or Deny it tries to use a "redirect_uri" of http://localhost:3200/oauth2-redirect.html. No matter what I do I cannot change the redirect URI.
How to I get the a proper redirect URI?
Ok, this was actually easily fixed. You need to add a single line:
oauth2RedirectUrl: 'URLhere',
to the file init-swagger-ui.js which is located (Symfony 3.4) in web/bundles/nelmioapidoc/
The final file ended up looking like this:
window.onload = () => {
const data = JSON.parse(document.getElementById('swagger-data').innerText);
const ui = SwaggerUIBundle({
oauth2RedirectUrl: 'URLhere',
spec: data.spec,
dom_id: '#swagger-ui',
validatorUrl: null,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: 'StandaloneLayout'
});
window.ui = ui;
};
Also you likely are going to want to download the file oauth2-redirect.html from the Swagger project to include for the actual redirect.
I need to change the default URL for authenticated users. For example, a request for root site will response:
[site-root]/wellcome01 (default url, set by plone configuration interface), for an anonymous user
[site-root]/wellcome02 (set by some resource) for an authenticated user
So what's the best solution to implement this resource?
You got several options
1.
You can add a index_html Python Script in your plone root, with the following code.
if context.portal_membership.isAnonymousUser():
return context.REQUEST.RESPONSE.redirect('welcome01')
else:
return context.REQUEST.RESPONSE.redirect('welcome02')
2.
I personally don't like not versioned code on my site, so I advice you to write a BrowserView, which handles de redirect
from Products.Five.browser import BrowserView
from plone import api
class RootRedirector(BrowserView):
def __call__(self):
if api.user.is_anonymous()
return self.request.RESPONSE.redirect('welcome01')
else:
return self.request.RESPONSE.redirect('welcome02')
You may regsiter this view only for the SiteRoot (Products.CMFPlone.interfaces.siteroot.IPloneSiteRoot)
If you're willing to just react to login events, you can adapt the following, which will redirect on the first-ever login only (and you probably want IUserLoggedInEvent instead):
configure.zcml:
<subscriber for="Products.PlonePAS.events.IUserInitialLoginInEvent"
handler=".hellonewbie.showIntroPage" />
hellonewbie.py:
# -*- coding: utf-8 -*-
from zope.app.component.hooks import getSite
USER_ROLE = 'Member'
INTRO_PAGE_ID = 'new-user-info'
def showIntroPage(event):
"""Login event handler: first login.
For proper users (i.e. Member role) that have
never logged in before, redirect them to a page
that tells them about the system.
"""
user = event.object
if user.has_role(USER_ROLE):
# yup, redirect the guy, he/she's new.
portal = getSite()
request = getattr(portal, "REQUEST", None)
if request:
infopage = portal.restrictedTraverse(INTRO_PAGE_ID, None)
if infopage:
request.response.redirect(infopage.absolute_url())
Or, just use one view with two elements, one only visible if not logged-in, the other only, if logged-in, via TAL-conditions.
im trying to do external login with Google using Aspnet.
I created an mvc/webapi project with individual user accounts (vs2013). This will create some files like the 'AccountController' which contains GetExternalLogins action, after calling this action I get (because the google external login is set in the 'Startup' class) an object like this :
{
name: "Google",
state: null,
url: "/api/Account/ExternalLogin?provider=Google&response_type=token&client_id=self&redirect_uri=http%3A%2F%2Flocalhost%3A11166%2F"
}
The problem now : when i do another http request to "/api/Account/ExternalLogin?provider=Google&response_type=token&client_id=self&redirect_uri=http%3A%2F%2Flocalhost%3A11166%2F" I get the following error :
XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=my_client_id_here. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:11166' is therefore not allowed access
Im i doing something wrong ?
Thanks a lot.
I realized that its a silly question 5 seconds after posting it.
No need to do an http request, a simple redirection to the url works.