django csrf for api that works with ios apps - ios

I am building an ios app that communicates with the server for getting the data.
If its just a normal app, I can send csrf token via forms (since all from same domain). But, for ios apps, I dont think I can set csrf token .
So, when making requests from ios apps, to the server, I am getting error regarding csrf. So, whats the solution for this? Disabling this csrf feature or some other better way ? This is my first ios app, so please tell me a better way so i will follow that.

For those URLs ("API end points") that your iOS app is accessing, you will need to specify #csrf_exempt on the corresponding view functions to disable csrf protection.
More details here - https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt
And protect those urls via other authentication methods, such as session authentication.
For your authentication purposes, you can easily take reference to what django rest framework and django tastypie has done. Both use SessionAuthentication classes to handle authentication and protect the exposed urls (API endpoints) that your iOS app can connect to.
References:-
http://django-rest-framework.org/api-guide/authentication.html
https://django-tastypie.readthedocs.org/en/latest/authentication_authorization.html
Django tastypie also has an authorization class, which is not to be confused with authentication. It also has an APIKey authorization class which becomes useful when you do want to expose your django URLs to other 3rd party developers who may want to build an app of their own to talk to your django URLs to access data (think "facebook APIs"). Each 3rd party developer can in essence be provided a unique API and because you have the APIKeyAuthorization class and a unique API Key provided to each 3rd party app, you can be sure that only "authorized" apps can consume your django URLs. This is the essence of how various big platforms like "Google+" or "Facebook" etc work.
Details of how django's csrf works
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-it-works
The CSRF protection is based on the following things:
A CSRF cookie that is set to a random value (a session independent
nonce, as it is called), which other sites will not have access to.
This cookie is set by CsrfViewMiddleware. It is meant to be permanent,
but since there is no way to set a cookie that never expires, it is
sent with every response that has called
django.middleware.csrf.get_token() (the function used internally to
retrieve the CSRF token).
A hidden form field with the name ‘csrfmiddlewaretoken’ present in all
outgoing POST forms. The value of this field is the value of the CSRF
cookie.
This part is done by the template tag.
For all incoming requests that are not using HTTP GET, HEAD, OPTIONS
or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’
field must be present and correct. If it isn’t, the user will get a
403 error.
This check is done by CsrfViewMiddleware.
In addition, for HTTPS requests, strict referer checking is done by
CsrfViewMiddleware. This is necessary to address a Man-In-The-Middle
attack that is possible under HTTPS when using a session independent
nonce, due to the fact that HTTP ‘Set-Cookie’ headers are
(unfortunately) accepted by clients that are talking to a site under
HTTPS. (Referer checking is not done for HTTP requests because the
presence of the Referer header is not reliable enough under HTTP.)
This ensures that only forms that have originated from your Web site
can be used to POST data back.

Related

How does keycloak determine which signature algorithm to use?

I'm writing an application that uses keycloak as its user authentication service. I have normal users, who log in to keycloak from the frontend (web browsers), and service users, who log in from the backend (PHP on IIS). However, when I log in from the backend, keycloak uses HS256 as its signature algorithm for the access token, and thus rejects it for further communication because RS256 is set in the realm and client settings. To get around this issue, I would like to "pretend to be the frontend" to get RS256 signed access tokens for my service users.
For security reasons, I cannot give the HS256 key to the application server, as it's symmetrical and too many people can access the server's code.
I am currently debugging the issue using the same user/pw/client id/grant type both on the frontend and the backend, so that cannot be the issue.
So far I have tried these with no luck:
copying the user agent
copying every single HTTP header (Host, Accept, Content-Type, User-Agent, Accept-Encoding, Connection, even Content-Length is the same as the form data is the same)
double checking if the keycloak login is successful or not - it is, it's just that it uses the wrong signature algorithm
So how does keycloak determine which algorithm to sign tokens with? If it's different from version to version, where should I look in keycloak's code for the answer?
EDIT: clarification of the flow of login and reasons why backend handles it.
If a user logs in, this is what happens:
client --[login data]--> keycloak server
keycloak server --[access and refresh token with direct token granting]--> client
client --[access token]--> app server
(app server validates access token)
app server --[data]--> client
But in some occasions the fifth step's data is the list of users that exist in my realm. The problem with this is that keycloak requires one to have the view-users role to list users, which only exists in the master realm, so I cannot use the logged in user's token to retrieve it.
For this case, I created a special service user in the master realm that has the view-users role, and gets the data like this:
client --[asks for list of users]--> app server
app server --[login data of service user]--> keycloak server
keycloak server --[access token with direct granting]-->app server
app server --[access token]--> keycloak server's get user list API endpoint
(app server filters detailed user data to just a list of usernames)
app server --[list of users]--> client
This makes the the list of usernames effectively public, but all other data remains hidden from the clients - and for security/privacy reasons, I want to keep it this way, so I can't just put the service user's login data in a JS variable on the frontend.
In the latter list, step 4 is the one that fails, as step 3 returns a HS256 signed access token. In the former list, step 2 correctly returns an RS256 signed access token.
Thank you for the clarification. If I may, I will answer your question maybe differently than expected. While you focus on the token signature algorithm, I think there are either mistakes within your OAuth2 flows regarding their usage, or you are facing some misunderstanding.
The fact that both the backend and frontend use "Direct Access Granting" which refers to the OAuth2 flow Resources Owner Credentials Grant is either a false claim or is a mistake in your architecture.
As stated by Keycloak's own documentation (but also slightly differently in official OAuth.2 references):
Resource Owner Password Credentials Grant (Direct Access Grants) ... is used by REST clients that want to obtain a token on behalf of a
user. It is one HTTP POST request that contains the credentials of the
user as well as the id of the client and the client’s secret (if it is
a confidential client). The user’s credentials are sent within form
parameters. The HTTP response contains identity, access, and refresh
tokens.
As far as I can see the application(s) and use case(s) you've described do NOT need this flow.
My proposal
Instead what I'd have seen in your case for flow (1) is Authorization Code flow ...
assuming that "Client" refers to normal users in Browser (redirected to Keycloak auth. from your front app)
and assuming you do not actually need the id and access tokens back in your client, unless you have a valid reasonable reason. As the flows allowing that are considered legacy/deprecated and no more recommended. In this case, we would be speaking of Implicit Flow (and Password Grant flow is also discouraged now).
So I think that the presented exchange (first sequence with points 1 to 5 in your post) is invalid at some point.
For the second flow (backend -> list users), I'd propose two modifications:
Allow users to poll the front end application for the list of users and in turn the front-end will ask the backend to return it. The backend having a service account to a client with view-roles will be able to get the required data:
Client (logged) --> Request list.users to FRONTEND app --> Get list.users from BACKEND app
(<--> Keycloak Server)
<----------------------------------------- Return data.
Use Client Credentials Grant (flow) for Backend <> Keycloak exchanges for this use case. The app will have a service account to which you can assign specific scopes+roles. It will not work on-behalf of any user (even though you could retrieve the original requester another way!) but will do its work in a perfectly safe manner and kept simple. You can even define a specific Client for these exchanges that would be bearer-only.
After all if you go that way you don't have to worry about tokens signature or anything like that. This is handled automatically according to the scheme, flow and parties involved. I believe that by incorrectly making use of the flows you end up having to deal with tricky token issues. According to me that is the root cause and it will be more helpful than focusing on the signature problem. What do you think?
Did I miss something or am I completely wrong...?
You tell me.

Is there an OpenID Connect grant type or mechanism for an app to poll for the auth-code when redirect_uri doesn't apply?

If you have an on-device application (e.g. desktop program, mobile device app) you can use OpenID Connect with some caveats:
Using Resource Owner Credentials (grant_type: password) is the simplest, but might not be possible if the authentication server operator won't let you use that grant-type because of trust reasons (i.e. they don't want you collecting the user's username+password yourself) - or if they have a dynamic or custom authentication UI that would be hard to replicate in a native app.
With the interactive flows (implicit, hybrid) the authentication sever's authentication page is shown in an in-app web-view. Most users will have no idea that the application can snoop on the authentication page and capture their username and password, especially on mobile devices - but this way the application code can easily capture the authorization code and/or access token, and automatically dismiss the web-view without any additional user interaction. (I'm surprised I haven't heard of more cases of users' details being captured by malicious apps this way.)
...so the advice is to always open the authentication page using the system's web-browser, but on the Windows desktop there is no good, standard way for the system web-browser to return the server response to the application code, though there are a number of approaches currently in use:
The authentication success page instructs the user to copy and paste a blob of text (containing the authorization code or access_token response) back into the desktop application.
Show the page in an app-hosted web-view, as per the notes above.
If the authentication process always only needs a username and password (for example) the application could still capture the user's username and password with its own UI and then make its own HTTP requests to make it seem like a user's web-browser session, and get the authorization code and/or access_token that way.
On Windows only:
Have a small utility program authHelper.exe that when invoked forwards its command-line arguments to a named-pipe in the user's session.
The main client-application will register authHelper.exe as a temporary URI scheme handler in the per-user HKCU\Software\Classes key, e.g. my-application: such that the contents of any my-application: URI are passed as arguments into authHelper.exe.
The URI passed to the system web-browser to open the authentication page has the redirect_uri parameter set to my-application:, so after the user authenticates in the browser, the browser will request the custom URI scheme which is handled by Windows, which invokes authHelper.exe "access_token=..." which then sends the data down the named-pipe to the running application.
If the user doesn't have permission to write to their own HKCU\Software\Classes key, or if they're using a version of Windows that doesn't support custom URI scheme handlers with EXE registrations then this doesn't work.
Windows UWP applications can also use the Web Authentication Broker.
I was wondering if a different approach could be used: why can't the application simply poll the authentication server for the status of the authentication attempt? Or does this approach already exist, and if so, what is the name of the flow or grant?
Here's the flow I'm proposing:
When the user wants to authenticate, the application opens the system web-browser as before, but with another parameter for a one-time-use opaque ID provided by the application.
As soon as the system browser is open, the application makes requests every 500ms or so (i.e. a polling loop) to the authentication server using its own HTTP client that asks for the status of the active authentication attempt associated with the same opaque ID as before.
The initial few responses from the authentication server to the application will presumably be status: pending, but eventually after the user successfully authenticates within a timeout window then the application's poll request would indicate a successful attempt and also contains the access_token or authorization code as is applicable. If the user failed to authenticate (e.g. 3 incorrect attempts) or left the window open long enough causing a timeout then the poll response would indicate failure.
Does this already exist and does it have a name? Are there any potential security risks or vulnerabilities with this approach?
It exists and has a name, "OAuth 2.0 Device Flow for Browserless and Input Constrained Devices", but is not yet fully standardized, see: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-device-flow
Google also implemented this flow avant-la-lettre in a vendor-specific way:
https://developers.google.com/identity/protocols/OAuth2ForDevices

Is the implicit client security is fragile or my concerns is not valid

I am using the implicit client in the identity server, in the other hand there is a native android app,
My security concerns is:
1- App reverse engineering: if the attacker get access to the client_Id
, redirect_uri and/or response_type, he will be able to mimic the login request.
by doing this he is impersonating the original client
2- Man in the middle: those client_id,... is send to the identity server through the https URI which is not encrypted, why not hiding them in the Header?
3- Browser will resend the token in the URI revealing it to the man in the middle if the redirect URI is not oob or localhost, the browser default behavior is redirecting to the Location, so can we force the developers when they register a client to use oob,
You can say ohh no the app is reading the token and close the browser so fast, before the browser sends the request,
Can we really rely on the app speed of closing the browser, this is sounds squishy?
Which question is legitimate concerns and which is not, also how to solve the legitimate concerns.
About point 1: how google is protecting it's services like google Map, the client Quote is vital and it has to be very secure, Right !!?
Edit
if we pass the client_id in the header to encrypt it, we will violate the http 1.1 spec and oauth2 spec, still we didn't do much, because the client_id is reside inside the handset, by small reverse engineering you can get it
Regarding point number 3:
The token response after a successful authentication will be something like this:
HTTP/1.1 302 Found
Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA
&state=xyz&token_type=example&expires_in=3600
The user-agent will redirect to the URL provided in the location parameter. Here there is no need to worry about MiTM attacks because the access-token is included in the URL hash fragment & hash fragments are not sent in the HTTP request messages, in other words the hash fragment will not leave the client machine.
Yes, but the token service will only return the user to the pre-registered callback uri for the client.
2 & 3. You should use HTTPS for most everything on the web these days.

Rails API authentication - sanity check and advise

I want to create a Rails application which exposes an API to be consumed by only authorised client applications (will be mobile apps for iOS / android). I've not started working on the app yet, but the primary method of accessing the underlying data will be through the api. I've been looking at using the grape gem, but would need to add an authentication layer to it. I was thinking about using devise and adding another model for storing client details, api key and secret key. Upon sign in through the api, the api key and secret are returned. The API key is transmitted with each request, but the secret key is not. Instead, it is used to sign each request; the request parameters are ordered by name, hashed using the secret key as the hash key. This signature is then added as a parameter to the request.
Does this system of authentication sound logical and secure?
I tried to prototype the system earlier, but ran into difficulty signing up a user using JSON with devise. At first I was getting a CSRF error. I then turned off protect_from_forgery and was getting another error. Is it safe to turn this off if I am authenticating in this way?
Yes you can turn off rails CSRF protection since you are using a different authenticity method as long as a date or timestamp is always inside the parameters that are being signed. You can use this to compare the request time to the server time and make sure you aren't undergoing a replay attack.
protect_from_forgery helps you protect your HTML forms. If you're consuming JSON from mobile clients, you don't need it.
Here's what I would do if I were you:
on user's account page, have a button that says "(re)generate API key"
client then embeds this key into his calling code and passes with each request.
your API server checks whether this API key can be used with this client id.
Very easy to implement and serves well.
Signing parameters also works and I used it in several projects with success. But it increases code complexity without any real gain (secret key is on the client, attacker already knows it).

how to login to an authlogic rails form from an iphone client

I have a server side app written in Rails using the authlogic plugin. I am not sure how to login to the rails app from my iphone client. I think I know how to write get/post code in Obj C, but I'm not sure what the best approach is of authenticating with my rails server. Here is what the server side HTML looks like when you go to this URL:http://localhost:3000/user_sessions/new : http://pastie.org/596279
To authenticate from your iPhone app you will need to:
Disable cross site request forgery for the form actions
HTTP POST user_session[username] and user_session[password] to your FQDN + '/user_sessions'
Capture the session cookies returned from the site (and return these with subsequent requests) to take further actions in the application.
Depending on what your overall goal is, it might be better to write a custom authentication piece that would use the iPhone's internal ID and a combination of the username and password to create unique token to use for the session on the site.

Resources