Can I auto login a user on the client that has already been authorized on the server? - api

I have an application that uses google's oauth system to authorize with youtube's api. The code for this is done on our server and we receive tokens without any problem. We'd like to move some of the api calls to the client using their javascript api.
Since we've already authorized the user with the correct scopes required for the youtube api (https://www.googleapis.com/auth/youtube) I assumed when I called authorize on the client it would know that my application was already authorized and allow auto login. Instead I receive a "immediate_failed" response. Does anyone know why? Thanks!
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);

If you have the token, you can just use setToken instead of going through OAuth2 again.

Related

Authentication with AzureAD via TestCafe Tests

I'm unable to authenticate / sign-in via AzureAD when running testCafe.
const testrole = Role(
'https://login.microsoftonline.com/',
async t => {
await t
.typeText(Selector('input').withAttribute('type', 'email'), *******)
.click(Selector('#idSIButton9'))
.typeText(Selector('input').withAttribute('type', 'password'), ********)
.click(Selector('#idSIButton9'));
},
{ preserveUrl: true }
);
The above steps work fine, however after entering the password I get a message saying:
"Unable to sign in to Outlook account, Error: AADSTS900561: The endpoint only accepts POST requests. Received a GET request."
From my initial search, it seems like something to do with 3rd party cookies on the browser. However, I'm unable to find a solution at this time.
Any idea how I get around this issue?
The Azure AD product team has always reminded me that it is a bad idea to try to automate sign in like that.
They will probably detect that you are a bot and start blocking your requests, even if you succeed.
Instead, to acquire access tokens you need to use either the client credentials flow (for app-only tokens) or the resource owner password credentials flow (for delegated user tokens).
Client credentials flow: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
ROPC flow: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
You have to take good care to secure the credentials used for testing.
And use a test tenant if possible.

How to track a user is logged in or not using api?

I am creating api using cakePHP. I have created an api for user log in. This log in functionality is working fine.
Here is the log in function -
public function login(){
if ($this->request->is('post')) {
$user = $this->Auth->identify();
}
}
Now, the I am facing problem is, how I can test from other api that is the user is logged in or not? In web application it can be done by default auth system ($this->Auth->user()). But I am not getting how I can check is this user logged in or not from another api. Do I need to send api parameter to each api request ? or any other suggestion ?
Note : I can't send any token in header. Because in header I am sending jwt token. Because in my application there are two kind of authentication. One is log in or not? and another one is depending some other input from user. That is handling by jwt. So jwt token I am already sending by header. So header is already used.
A couple of things to clarify.
In a regular app, the user logs in with a post request and on successful authentication a session is created. This session is a bit of information that the user supplies in each of the following requests and the server then recognises the user. This accomplished by the Auth component in it's default settings.
In an API you could do the same: the user logs in, receives the session and attaches the session cookie-like object on each following requests. (Example of such a Python client.) However, this is not considered good practice as APIs should be stateless (so without requiring something like cookies). The solution of working with tokens, for instance hashes of some secret token together with a timestamp. The Auth component also supports this pretty well. After setting it up, you can simply call $this->Auth->user(), like you would normally and it returns either false or an array of user information. See link below.
Note that by default this authentication type will block unauthenticated users, so you will never see ->user() return false unless you make pages as public.
See also:
(Cookbook > Authentication > Creating stateless authentication systems)

What does Ember-simple-auth check against?

I have been looking for answer of implementing ember-simple-auth (oauth2-password-grant) for days without luck. I use firebase to sign up users, which is successful. However on the log in page, the action of this.get('session').authenticate('authenticator:oauth2', credentials) seems to cause a json error (SyntaxError: Unexpected token < in JSON at position 0).
So my first question is, in theory, how does this authentication check if the user's email/password is correct? Meaning, in which file is the "answer" located? Am I supposed to define a token? If yes, I already tried "serverTokenEndpoint: 'http://localhost:4200/' or serverTokenEndpoint: 'http://localhost:4200/token" and nothing works. Thanks.
Ember simple auth sends login request to API(in your case Firebase). If entered credentials are valid your API will authenticate user, create and save auth token. Authenticated user with created token will be sent to Ember and token will be saved in local storage by Ember simple auth. Every subsequent request from Ember after login needs to include that token in its header and API will authenticate your request based on that token(comparing token from Ember with the one saved in API).

Laravel 5, how to send API token to mobile app

I have a mobile app which will call a REST API written using Laravel(5.2) framework.
This article on Laravel API authentication mentions how to authenticate users making calls to such an API. The caller should send the correct api_token to the server in the request.
My question is what would be a good way to get the api token to the mobile app? I'm currently thinking of creating a rest api which will authenticate the user based on username and password sent in the request and send the api_token in the response if the user sends a valid username/password pair. Is this method correct/secure? What things should I consider additionally if I do use this method?
You must use one of this methods to have a secure API
JWT TOKEN https://github.com/tymondesigns/jwt-auth
OAUTH2 https://github.com/lucadegasperi/oauth2-server-laravel
With this methods you only send once username and password and you obtain a token that is valid for a time you can decide. But as bigger is the time, more insecure.
To solve this, there are a renew token methods. With a valid token, you can obtain another valid and refresh the old. In this way, the username and password are more protected because they are not sent in every request.
Is not a good idea have the same token for each user all the time, as you saw in the example you provide. It´s very insecure. If someone get this token, he always will can send request in your name. The tokens must have a lifetime.
to answer your question how to send API token to mobile app i will recommend you that your mobile apps get a valid token and after refresh it.
Something as this works great to get a token in your app:
if ( thereAreTokenStored() )
{
if (! theTokenStoredIsValid() )
{
$authentication = refreshToken();
}
}
else
{
$authentication = authenticate();
}
To know all this issues I recommend you this book: https://apisyouwonthate.com/ . I learnt a lot of the 'API WORLD' with this book. It will help you to know all you need to create an API in a professional way and will provide the necessary tools and packages to achieve it and save a lot of work. And you will love your API!!
Yes this approach is safe. Additionally you also need to secure your connection to server by using HTTPS with a SSL certificate.

django rest framework - token authentication logout

I have implemented the Token Authentication according to the django rest framework Docs.
Form what I read, the Token Authentication of DRF is quite simple - one token per user, the token doesn't expire and is valid for use always (am I right?).
I understand that there are better practices out there, but for now the DRF token authentication is fine for me.
my question is- what is the best practice for logout with the normal DRF token authentication?
I mean, when the user logs out, should I delete the token from the client side? and then on login get the token again? should I delete the token and generate a new one?
Anyone with experience with this?
Here's a simple view that I'm using to log out:
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
class Logout(APIView):
def get(self, request, format=None):
# simply delete the token to force a login
request.user.auth_token.delete()
return Response(status=status.HTTP_200_OK)
Then add it to your urls.py:
urlpatterns = [
...
url(r'^logout/', Logout.as_view()),
]
WHOLE IDEA OF TOKEN AUTHENTICATION:
Normally in authentication services, there is a lifetime associated with a token. After a specific time, the token will get expired. Here, we get an access token which has an expiry time sent along with it by the server. Now the client needs to send this token everytime in the request header so that the server can identify who the user is. Either we can keep track of when it expires or we can just keep using it until we get an INVALID_TOKEN error. In that case we would have to again get the token from the server.
The lifetime of the access_token is independent of the login session of a user who grants access to a client. OAuth2,lets say, has no concept of a user login or logout, or a session. The token is just used to identify the user if he is who he says he is.
The token is unique for a user and client. You may save it to cookies to enable something like remember me but on the server you don't need to delete it. Whenever the token expires, the client need to send a request to the server to obtain the token again.
Token Expiry in DRF Token Authetication:
Currently, DRF Token authentication does not support this functionality. You would have to implement it yourself or use a third party package which provides this functionality. It should check for token expiry and raise an exception if the token has expired.
To implement it yourself, you can subclass from the DRF Token Authentication class and add your logic.
You can even use a third-party package django-rest-framework-expiring-tokens.
Some References:
1. Token Authentication for RESTful API: should the token be periodically changed?
2. How to Logout of an Application Where I Used OAuth2 To Login With Google?
It sounds like SessionAuthentication is what you are really looking. You can start(login) a session via BasicAuthentication or TokenAuthentication. Then use sessionid as your "token" for the rest of api calls. The "token" expires when you logout or exceed certain timing.
If you run into csrftoken issue using session authentication, this could be a very helpful.