Django Rest Framework / AngularJS - Users do not get redirected anywhere after logging in, even though I have set LOGIN_REDIRECT_URL in settings.py - angularjs

According to this link: http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-login-to-the-browsable-api
I need to add the following code to my URLs.py:
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
When I added this, users can log in by going to the "api-auth" URL and using the default DjangoRestFramework login interface. After a successful login, users are directed to "/test" because I have the following code in my settings.py:
LOGIN_REDIRECT_URL = '/test'
I wanted a way for users to be able to log-in using my own custom interface but by using DjangoRestFramework's built-in code for logging users in, so I created my own template. The login form in the template sends a post request to
api-auth/login/
and sends the user object (which consists of a username and password in JS) along with the POST request. No errors are returned, so I'm assuming the login is successful. However, it does not redirect to any URL (I was expecting it to redirect to "/test").
Any idea why it does not redirect anywhere, and how I can make it redirect to "/test"?
Edit: I am also using AngularJS on the frontend.

LOGIN_REDIRECT_URL is basically from django.contrib.auth so I wouldn't except other auth backends to use it, at least not necessarily/automatically
Also if you're logging through REST say from an AngularJS, even if after the REST API login is successful and returns a redirect response, there is no guarantee that the AngularJS app will navigate to that page because the login REST API was hit using an XHR request (from $http or $resource etc)
I'm using a slightly different REST auth lib than you, called django-rest-auth (not the BrowsableAPI that comes with DRF), I'm authenticating from AngularJS, and after the call is done with success, I simply navigate the app to a new URL
djangoAuth.login(username, password).then(function(){
// make angularJS navigate to new page when login is successful
// $location.path(...) or some other way
});
Bottom line is, since you have an auth API, you can make a small AngularJS page, with login form, then when login is successful redirect with AngularJS
Worth a look
I'm using these two libs that are meant to be used together, they offer REST auth over DRF, and optional a AngularJS lib to help with the frontend
https://github.com/Tivix/django-rest-auth
https://github.com/Tivix/angular-django-registration-auth

Related

Redirection error Laravel Passport PKCE - local

I have a React site trying to get access token from my Laravel oAuth portal (using Passport). As I understand from the documentation, I create the state,code challenge and code verifier on my react app. I create a url with the required parameters and make a redirection to /oauth/authorize. The complete code for the redirection is window.location.replace('http://portal.test/oauth/authorize?' + paramsStr). http://portal.test is my oAuth portal (using Valet) and paramsStr contains all my parameters: client_id, redirect_uri, response_type, scope, state, code_verifier, code_challenge, code_challenge_method.
I am redirected to the portal as I should which redirects me to the login form. Once logged in, I have to approve the authorization request. After that step, I am supposed to be redirected to my React app to verify the state parameter and then make a POST request to my oAuth portal to request an access token. (again, from the documentation)
The url in my browser is still http://portal.test/login (the oAuth portal url) where it should be http://auth.localhost:3006 (the React app). I do have kind of a popup that opens, showing the content of the React app but I have a problem with my cookies. In the first step, after creating the state,code challenge and code verifier, I store those (using react-cookie). If I check the cookies right after, I can see them. If I go to another page of my React app, I can see them. If I manually go to another url (like google for example) and then go back to my React app, I can see them. So I know that setting the cookies does work. But in that weird popup I can't access the cookies.
I guess that a redirection issue and I can't access them because the url in the browser in not the url of my React app. How can I fix that ?
Relevant code for the login
const [cookies,setCookie,removeCookie] = useCookies([]);
setCookie('code_challenge',code_challenge);
setCookie('code_verifier',code_verifier);
setCookie('state',state);
console.log(cookies); // this shows the 3 values
window.location.replace('http://portal.test/oauth/authorize?' + paramsStr;
Page I am redirected to within React app
const [cookies,setCookie,removeCookie] = useCookies(["foo"]);
console.log(cookies); // empty
In the url to /oauth/authorize the parameter redirect_uri is http://auth.localhost:3006. In the DB in the oauth_clients table, the redirect value is the same.

How can i redirect to an Angular router link with oauth2 login?

I want to make an oauth2 login with Twitch on my website and I have an angular2 website and I'm working with router links.
When I want to log me in with twitch acc to say yes it is me and so everything is fine. Ok the end not xD
When i go to the twitch oauth2 for authorizing i need an redirectUri. My problem is now how can i make this in angular2? Because I can't type www.page.com/app/afterlogin/afterlogin.php or somethink like that.
I need this because I need from the user the access token, I dont want that he need to authorize himself x times.
Maybe this helps for helping me:
https://api.twitch.tv/kraken/oauth2/authorize?client_id=[client_id]&redirect_uri=http://www.page.com/app/AfterLogin/afterlogin.php&response_type=code&scope=user_read
I hope someone can help me with redirecting and some oauth2 logins :)
Let me assume a RESTful backend with Single Page Application front and answer the question. The process in general is like the following
Your SPA --> Your Server --> Your Provider --> Your Browser --> Your Provider --> Your Server --> Your SPA
Your SPA => initializes login and passess redirect_uri
Your Server => Stores redirect_uri in a cookie and sends request to
provider
Your Provider => Gets Success and Failure Urls and loads login page
to your browser
Your Browser => Loads the provider login page
Your Provider => Sends request to your server success or failure
handler
Your Server => Extracts the redirect_uri and redirects the browser
to it
Your SPA => Gets afterLoginUrl from redirect_uri and route the
user to it
Below are the steps to achieve this
When your front end sends the authentication request to your server,
append the redirect_uri. In that url, pass a afterLoginUrl query
parameter. That is used by your front end SPA to route the user to
the specific page that triggered the login. (i.e. If the request has
been triggered by a user trying to access
{base_uri}/profile/project/projects for example, it is a good
practice to route the user to this page rather than to the default
page that a normal login takes to like base_uri/profile/about). As
a result you will have a url that looks like the following.
`http://localhost:8080/oauth2/authorize/google?redirect_uri=http://localhost:4200/oauth2/redirect&afterLoginUrl=/profile/project/projects`
port 8080 being for the back end and 4200 for the front end.
Since you are using a RESTful service, you don't have a way by which you can save the redirect_uri on your server (since REST is stateless). Because of this you need to send it with the request you send to the provider as a cookie.
When the success is received from the provider, you will know which route of your SPA to hit by extracting the cookie you sent. Then you dedicate a route to handle your request from your own server (in my case oauth2/redirect) in your front end app.
On the component specified for the route in step 3 you will receive token and afterLoginUrl(if there is). You will have something like the following on the url
http://localhost:4200/oauth2/redirect?afterLoginUrl=/profile/project/projects&token={token value}
Verify your token, check whether or not there is afterLoginUrl and redirect to the route specified by afterLoginUrl if there is one or to the default profile page if there isn't.
I think a wonderful resource can be found here.
Authorization Code Grant flow is just one of several ways of how you can use OAuth2. It's not suited for applications running in a browser, because it requires a client secret which you cannot keep safe in a browser.
There is another flow - Implicit flow which is meant for JavaScript applications - you get an access token and/or ID token in a redirect URI - in the hash part (#...) so they don't get to a server. Then you can easily use any Angular route path as a redirect URI. So the redirect URL from OAuth2 server could look something like this:
http://example.com/myAngularApp/afterLogin#token=...
When you get to that URI, you just save the token and change the route to some real form.

Laravel 5 Middleware with angular routes

I'm using Laravel 5 with AngularJS for a project, in a way so that Laravel is used as an API and the API routes are in Laravel, while the client side routes are in AngularJS (app.js).
Is it possible to use Laravel Middleware to protect AngularJS routes, so for example, I want it to use the RedirectIfAuthenticated Middleware on the angular login form page route so people can't go to that page if they are logged in, except normally as far as I know, the middleware is specified in the Laravel controller, which doesn't have logic for angular side routes - hence, the problem.
So the question is, can I use Middleware or do I have to make angular send a get request asking laravel if the user is logged in on every page? Wouldn't that be less secure?
What I ended up doing was making a client-side cookie on login in angular to keep track of whether the user is logged in or not for user experience purposes (hiding information, redirecting before the view is rendered), and using Laravel Middleware to protect API calls to make sure the user can't interact or get information from the API on the server and to keep it secure in case the user changes their cookie to lie about their login status.
Alternatively, you could also send a request to the server before each page loads instead of the cookie check, but that adds quite a bit more overhead, and isn't any more secure - as far as I know, since that API call to check if the user is logged in is just for UX purposes too and the javascript for that can be removed by a malicious user.

Twitter oAuth in my RESTful API

I have an Angular JS front end app that is separately deployed at http://localhost:9002 and a Play Scala back end deployed at http://localhost:9000
I want to expose a RESTful URL from the backend like http://localhost:9000/authenticate/twitter which redirects the user to the Twitter oAuth app asking them to login with their Twitter details.
I then want to redirect back to the Angular front end app and be able to call any other backend REST urls I have secured with the Twitter auth login.
I am wondering how to 'redirect' the user to the Twitter auth login page without losing my current angular state. I.e. could I do this in a pop-up and if so, then how? And how do I return from the oAuth login and store the user session info in the backend as well?
The best thing for me would be to pass the twitter login details to the backend and have the backend call the twitter auth stuff and store a user session there, then just give the front end a token it can use for each auth request, but the whole redirect to Twitter login page ruins this. Any ideas for how to implement what I want?
This is definitely doable as I've done it before (sorry no example - commercial code)
I assume you can open twitter in popup so I won't write code for it
main window
js
window.DaSecretBirdy = function (token) {
//do something with token
}
popup
open twitter auth page, set redirection to a custom page
on a custom page get the twitter token from a query string and call
js
window.opener.DaSecretBirdy(hereIsMyToken)
that's the concept that is working, keep in mind that you will need angularjs $apply if you want to assign variable on scope from external code

Authenticated Angular JS apps

I want to conver my existing site to angularJS application. Its flow is like this.
My parent web site is having link to sign up or login page.
As per user selection signup or login page should open.So once user login or created account he pointed to dashboard page.So how to do this angularJS?
Please note my parent web site is not in angular.
Thanks in advnce.
Here is a suggested design and here is a little project I wrote that has Angular code authenticating with a PHP server. The code has both the Register and Log in options you are looking for.
Use token based authentication (Im assuming your angular requests are JSON)
After the user logs in or registers, send a bearer token back to Angular via the URL. On the server side set an expiry date for the token
Every http request you make can include the token in the http header
The sample code has this implemented.

Resources