An easy way to redirect certain roles in zope - zope

I have a section of my zope 2 site which uses an interim macro between the 'content' and the site-wide macro. I don't want to apply security to the folder, but I would like the interim macro to redirect users to a login screen if they try to load a page that uses it.
An example of this would be this:
page_html contains the content, it uses the macro in special_template, which then slots into a macro in standard_template. Therefore I want it to redirect to the login screen. If page_html didn't use special_template, but went straight to standard_template (which is what most of the pages on the site do), I would not want it to redirect.
How could I achieve this?

First of all, why not restructure your site to put all these pages that require authentication in locations you can protect with Zope permissions? A custom (local) workflow can apply permissions on a state-by-state and location-by-location basis, thus using Zope's own automatic authentication framework. If you don't use a workflow, a custom type can still apply permissions that are acquired by anything below it in URL space.
You can create a method (a Zope3 view, a Python Script in a skin layer, a method on a content class in your acquisition context, an External Method, in rough order of best practices) that is called from your special_template macro by means of a tal:define statement. I'll assign the output to a dummy variable here because you don't care about that, we'll use it for it's side effects. The following example assumes you've gone the Z3 view way:
<body tal:define="dummy context/##redirect_if_anonymous">
This will instanciate the view registered with the name redirect_if_anonymous. In the view you can then test if your web visitor has been authenticated, using standard Zope API methods or a test for a cookie, depending on your application. Here is a standard API example, it'll raise Unauthorized to force a login.
from Products.Five import BrowserView
from AccessControl import getSecurityManager, Unauthorized
from AccessControl.SpecialUsers import nobody
class RedirectAnonymous(BrowserView):
def __call__(self):
sm = getSecurityManager()
user = sm.getUser()
if user is None or user is nobody:
raise Unauthorized
If all you want is a redirect to another location, simply use response.redirect():
url = self.request['URL0'] + '/login.html'
self.request.response.redirect(url)
If you want to test for cookies first, cookies are part of the request variables:
if 'mycookie' not in self.request.cookies:
self.request.response.redirect(url)

Related

How can I figure out if the authenticated user is authorized to access an area/controller/action?

Being in a view and you know the area-name, controller-name and action-name of a destination to which you want the user to provide a link to, how can I figure out if the area/controller/action is authorized for the authenticated user.
Imaginary Use-case:
I have a table with a list of books (the result of bookscontroller.index). To the far right are some icons to edit or delete a specific book. The edit link refers to bookscontroller.edit and the delete link to bookscontroller.delete.
On the actions there are custom authorizationattributes and this works perfect. If a user want to access books/edit/1 and the user is not allowed to edit books, the user gets redirected to the logon page.
It is a bit stupid to have that edit-icon there if the user is not allowed to edit books. So at view level I would like to be able to figure out if the user is allowed to use the edit action of the bookscontroller. If he is, show the icon if not, do not show the action.
Goal: use that knowledge to create a custom tag-helper.
The go-to method is reactive, i.e. you check if a user can do action when the user tries to do. Since you do not want to go that way, here is how. (yet, this is anti-pattern)
Have the authentication token of the user send back to backend. The backend should have an API end point for each button on the page user can click. With the authentication token, the back-end resolve whether to dim or enable the buttons.
Now, what the backend does to resolve this is not very efficient. The backend needs to literally attempt certain actions and aborts the transaction. For create and retrieve, it is trivial (you can pre-resolve them) but for edit and delete, this requires a lot of resources.
The standard way of controlling such actions on UI is to use role based authorization.
For the buttons or other such UI elements, setup role tags, e.g. "admin:edit", "viewer:readonly" etc.
When you are authenticating a user, send the applicable roles from the backend server, store them in a way that is globally accessible to your UI and use them for filtering UI elements across your application.

Keycloak - Multi/2FA Factor - OTP - QR Code - Custom Login Screen - Rest API

I have my own Login page where user enters username/password.
This username/password are used to login through Keycloak Rest API.
http://localhost:8080/auth/realms/Demo/protocol/openid-connect/token
input - {username,password,grant_type,client_secret,client_id}
And in response i get access token.
Now i wish to enable Authenticator (Google Authenticator). I have enabled it from backend. Now if user wishes to login thorugh my application, my login page i need to get below details.
1.) Somehow i need to include QR Code that appears on keycloak login page post username/password validation to show on my login screen for the first time login once user enter username/password. So do we have any API which return Keycloak QR code image in response.
2.) Subsequent login i will have OTP field, so need a REST api to pass OTP along with username/password.
Please help with REST API if keycloak has any. Integrating through Javascript.
Similar flow as described in use case 1 here
Just want to use keycloak as a database, doing all operation for me, input will be my screen. I do want redirection of URL's while login in and yet should be standalone deployed.
I've managed to implement this through the rest API of Keycloak. To realize this, you need to extend Keycloak yourself with a SPI. To do this create your own Java project and extend org.keycloak.services.resource.RealmResourceProvider and org.keycloak.services.resource.RealmResourceProviderFactory. You can find more information in the official docs (https://www.keycloak.org/docs/latest/server_development/#_extensions), github examples and other stack overflow posts how to do this.
Once you got this up and running you can implement it like this:
#GET
#Path("your-end-point-to-fetch-the-qr")
#Produces({MediaType.APPLICATION_JSON})
public YourDtoWithSecretAndQr get2FASetup(#PathParam("username") final String username) {
final RealmModel realm = this.session.getContext().getRealm();
final UserModel user = this.session.users().getUserByUsername(username, realm);
final String totpSecret = HmacOTP.generateSecret(20);
final String totpSecretQrCode = TotpUtils.qrCode(totpSecret, realm, user);
return new YourDtoWithSecretAndQr(totpSecret, totpSecretQrCode);
}
#POST
#Path("your-end-point-to-setup-2fa")
#Consumes("application/json")
public void setup2FA(#PathParam("username") final String username, final YourDtoWithData dto) {
final RealmModel realm = this.session.getContext().getRealm();
final UserModel user = this.session.users().getUserByUsername(username, realm);
final OTPCredentialModel otpCredentialModel = OTPCredentialModel.createFromPolicy(realm, dto.getSecret(), dto.getDeviceName());
CredentialHelper.createOTPCredential(this.session, realm, user, dto.getInitialCode(), otpCredentialModel);
}
The secret received with the GET must be send back with the POST. The initial code is the one from your 2FA app (e.g. Google Authenticator). The QR code is a string which can be displayed in an img with src 'data:image/png;base64,' + qrCodeString;
I know this is an old question, but I've recently been looking at something similar, and so thought it would be potentially valuable to share what I have found for others who may be looking into this and wondered what the possibilities are.
TL;DR
You can only really use the existing Keycloak actions to do this or embed the user account management page found at https://{keycloak server URL}/auth/realms/{realm name}/account in an iframe. That's it, I'm afraid. In my opinion it is currently best to just assign actions directly to accounts or use the Credential Reset emails to assign actions; both of these can be done via the Admin API if desired:
Send Credential Reset email containing assigned actions:
https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_executeactionsemail
Set actions directly on the account (include the actions in the requiredActions portion of the user JSON that you send in the body to the endpoint):
https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_updateuser
Background is that as part of a project that I have been working on we wanted to see if we could have an integrated way for users to set up their initial password and OTP device when a new account has been created for them, since the default method of sending them an email from Keycloak using the "Credential Reset" functionality has the limitations that a) it doesn't provide a link to the application itself unless you override the theme, and if you have multiple instances of the application for different users you have no way of knowing which instance to provide the link for, so may have to end up including a list of them, and b) it often doesn't feel truly native to the application, even with changes to the theme. If you're sensible though, I'd suggest you stop and just use this functionality - please see the TL;DR section above for details.
So, in short there is NO API endpoint for receiving a QR code to set up an OTP device. There are two places, however, where the QR code can be retrieved from - the OTP device setup screen when you log in as a user who has had a "Configure OTP" action assigned to their account, and the user's own account management screen.
The first option of the Configure OTP action screen is a non-starter. It only shows up when you log in, and so by definition the user has to log in to Keycloak via the Keycloak login page in order to trigger the page to be displayed. At this point you're already on a Keycloak page instead of one of your app's pages, and so unless you can get very creative with changes to these Keycloak pages via a custom theme, tapping into this page isn't really an option.
The second option is more interesting, but far from ideal. Every user who has logged in has access to an account management page that can be found at https://{keycloak server URL}/auth/realms/{realm name}/account. This page allows you to do things like change your name, password, etc. and it also allows you to add an OTP device if you don't already have one, or delete any existing OTP devices associated with your account. This OTP device tab of the account management page can be reached directly via https://{keycloak server URL}/auth/realms/{realm name}/account/totp.
As I mentioned, there isn't an API that you can access to view the QR code that shows up on this page. The only way it is accessible is via the GET request to https://{keycloak server URL}/auth/realms/{realm name}/account/totp, which returns the HTML for the page I've already mentioned. Okay great, so can we scrape the QR code programmatically and then put it in our own page on our application? Err, no, not really. You see, whilst a lot of the Keycloak API endpoints rightly allow you to send a bearer token (e.g. access token) in the authorization header to access and endpoint, this page will not accept a bearer token as a means of authentication/authorization. Instead it uses a session cookie that is locked down to the Keycloak URL. This cookie is set when you log in to your application via the Keycloak login page, and so is available to this account management page when you navigate to it, having already logged in, and since the account management page uses the same server and domain name as the original Keycloak login page, it has access to the cookie and can let you in. This cookie cannot be sent by your application to e.g. your own REST API to then programmatically call the account management page and scrape the QR code, because your application doesn't have access to it for good security reasons. This might be something you can change in Keycloak somewhere, but if there is I would strongly recommend against changing it.
So if we can't scrape the page from our own server, can we do something on the front-end? Well, as mentioned, your application doesn't have access to the session cookie but if you make a request (e.g. using fetch or axios) in your front-end JavaScript to the account management page then that request will send the cookie along with it, so that could work right? Umm, well actually you will get hit with an error message in this scenario due to CORS. CORS is Cross-Origin-Resource-Sharing and in order to allow the Keycloak page to be accessed then you would have to open up the settings on the server to allow it to be accessed from your website's address. I've seen some articles that look at how you can open up your CORS settings on Keycloak if you wish but I'd be very nervous about doing this. I don't know enough about the internals of Keycloak and how it operates to comment on how much of a security risk this is, but I certainly wouldn't recommend it. There some information here (Keycloak angular No 'Access-Control-Allow-Origin' header is present) on changing the "Web Origins" setting of your application's Keycloak client, but this opens up your application to some serious potential abuse. There is also the MAJOR issue that even if you scraped the QR code, the device isn't actually added to the user's account (even though it appears in the authenticator app) until you enter a code into the page that the QR code is on and click Save. Since there isn't an API endpoint that you can use to complete this operation, I therefore don't think that this option is viable either. I've tried out whether or not you can use the token retrieval endpoint at https://{keycloak server URL}/auth/realms/{realm name}/protocol/openid-connect/token to see if making a request with your username/password/otp code will somehow "register" your device and complete the process, but although you can get a token this way, and it doesn't complain about the otp code, it doesn't actually take any notice of the code because as far as it's concerned the user's account doesn't have a device registered with it. So we have to use the form on the account management page in order to complete this registration process.
So the final way of possibly doing this is.... an iframe. Sorry, yeah it's rubbish but that's all your left with. You can have the iframe point at your account management page, and because the user is logged in then they will be able to see the contents from your application's page. You can use relative positioning, fixed width and height and remove scroll bars to ensure that you ONLY show the QR code and the fields for the one time code, device name, and the Save/Cancel buttons. This, sadly, seems to be the only option at the moment, and due to how nasty and unreliable iframes can be in general - they certainly don't feel native to your application, and you'll need to override your Keycloak theme to get the page in question to look more like your app - I'd recommend steering clear of this and using the standard approach of using Keycloak actions and the Admin API instead.
If you've made it this far, congratulations, you win at Stack Overflow :-)

How to use friend with compojure?

I'm fairly new to clojure, and I'm trying to add an authentication system to a compujure app and for that I'm using cemerick.friend.
All the routes are working fine, but I'm never able to login, even when using a dummy in memory database (if you can call it that).
The problem, I believe, is on the cemerick.friend.credentials/bcrypt-credential-fn, which is never validating my credentials.
Here's a gist with the relevant code: https://gist.github.com/zamith/5940965
Any help on how to solve this problem would be nice.
Thanks.
You want to use workflows/interactive-form where currently you specify workflows/interactive-login-redirect.
The latter function's purpose is to serve as the default :login-failure-handler. What it does is perform the redirect after a failed login attempt; it certainly makes no attempt to log a user in.
You also need to remove the (resp/redirect "/signup") from the body of the friend/authenticated form in your "/dashboard" route, as it's unconditionally redirecting logged in users to the signup page. (That the redirect happens is in fact proof of the user being authenticated, since otherwise the body of friend/authenticated would not be evaluated and there's nothing else in the code which could cause a redirect to "/signup".)
With these two changes, the app works for me.

GWT: Authentication for some part of application using GWT login page

My application has some features that are accessible to all users, and some other features to which access should be restricted to authenticated users only. All these restricted features exists within some set of GWT Places, thus, all Places available in application can be divided into two groups: "accessible for all", and "restricted". In my opinion, places with restricted access, could implement some interface (let's say it would be RestrictedAccess), and if user proceeds to one of them, and it has not been authenticated yet, it will be redirected to the login screen - it's more OO-approach than applying filters basis on URL.
What I'm trying to achieve is:
Information about if user has been
authenticated or not should be
stored on server (it's not something
that could be stored in a cookie...)
Login page is a standard GWT place+view+activity (!)
User name & password validation is done on the server side.
So far, I've introduced RestrictedAccess interface, which is implemented by some set of places. My FilteredActivityMapper.Filter implementation, which is passed to the FilteredActivityMapper wrapping application activity mapper has the following logic:
Place filter(Place place) {
if (place instanceof RestrictedAccess && !userHasBeenAuthenticated()) {
return new LoginPlace();
}
// return the original place - user has been already authenticated or
// place is accesible for all users
return place;
}
private boolean userHasBeenAuthenticated() {
// remote call - how to do ???
}
The problem is with userHasBeenAuthenticated() method (user should not be redirected to the LoginPlace, if it has been already authenticated). If I want to store this information on the server-side, I have to do GWT RPC/request factory call here, but both are asynchronous, so I cannot work on its result in the filter method.
I know that I can use web.xml filters or some external framework (e.g. spring security), but none of this approach allows me to have login page as a standard GWT - based form, or indicating in the more OO way that access to some place should be restricted.
Thanks in advance for any hints
EDIT: I've started to wondering if places filtering (restricted/not restricted) should take place on the client side at all. If, as it was suggested, there is a possibility to hack code indicating if user has been authenticated or not, there is also possibility to hack places filtering code, so that it will be possible to access restricted places without signing in.
Piotrek,
I think there is a security issue with calling userHasBeenAuthenticated() - it would be possible to hack the client side code to return true every time this function is called.
The solution I've implemented is to simply return SC_UNAUTHORIZED if an unauthenticated user attempts to access any remote service. I've overridden the RequestFactory onResponseReceived function which redirects to a login page if the response is SC_UNAUTHORIZED. Idea taken from:
http://code.google.com/p/google-web-toolkit/source/browse/trunk/samples/expenses/src/main/java/com/google/gwt/sample/gaerequest/client/GaeAuthRequestTransport.java
This works for our situation where the Activities and Places are all data-centric - each place change retrieves data from the server. If a user isn't authenticated they simply don't get the data and get redirected to a login page.
I realize your situation is slightly different in that some places are accessible to everyone, in which case you could configure only the restricted services to return SC_UNAUTHORIZED.
I have a similar application with the same requirements. As yet I have not got round to to the implementation but I was thinking along the same lines.
What I was planning on doing is storing the authentication state client side in an AuthenticationManager class. When the app starts I was going to request the login info from the server (I was thinking of running on app engine so I would get the authentication state and also get the open id login/logout URLs) and store this in the AuthenticationManager. Acegi/Spring Security works in a simlar way so this info is available server side if you use those too.
When the user logs in/out they will be redirected by the server and the new state will be retrieved. This should keep the client authentication state in line with the server. Each RPC request on the server has to be checked for authentication too. I was using the gwt-dispacth library and this has some rudimentary authentication checking and cross site script protection in in too (although I think latest GWT has this for generic RPC).
One issue is session timeouts. Again the gwt-dispath library has some code that detects this and returns session expired exceptions to the client which can be intercepted and the auth manager updated.
Hope that makes some sense.

Redirecting back to a page after authentication through OpenID, Oauth, or Facebook Connect

I'm allowing users to login to my site with either OpenID, Twitter OAuth or FBConnect. If the user attempts to go to a page that requires them to be logged in, after that user logs in I want to send them BACK to that page. Is there an easy way to accomplish this with all of these or should I simply just write the redirect page to a cookie and upon a successful login send them to that page? I'm using Django so if there are any nice tips or tricks involving that specifically that would be great.
Thanks for the input in advance!
You could thread that parameter (the page they were at) through as a parameter to your return_to. As noted in the spec:
Note: The return_to URL MAY be used as a mechanism for the Relying Party to attach context about the authentication request to the authentication response. This document does not define a mechanism by which the RP can ensure that query parameters are not modified by outside parties; such a mechanism can be defined by the RP itself.
For example:
def sendOpenIDCheck(...):
# after getting an AuthRequest from Consumer.begin
return_to = oidutil.appendArgs(return_to,
{'destination_url': that_place_they_tried_to_go})
return redirect(auth_request.redirectURL, realm, return_to))
def handleReturnTo(request):
# after doing Consumer.complete and receiving a SuccessResponse:
return redirect(request.GET['destination_url'])
If there's some other state you need to track (like POST data), or you have an extraordinarily long URL that you can't fit in as a query parameter, or you need to have the destination_url tampered with by the user, you store that information server-side, send the key as a query parameter instead of a URL, and look it up when they get back.
Not very different from storing it in the session, unless the user's got several simultaneous tabs in one session that run in to this, and then having it in the query helps.
Sadly OAuth and OpenID aren't really aware of your app states (while OAuth WRAP can be). So you have to take the following assumption:
The user will complete the sign-in WITHOUT switching tabs/windows or doing other requests on your site.
Then you can do the following:
Once you detect the access of a protected site, store the full query in the session. This won't work at all if it's a POST request, you have to prepare for this problem (show them a warning site with a lik that they must login first).
Store a timestamp of when this request happend.
On your OpenID callback check whether the session variables are set and redirect the user to the stored query. Check the timestamp (don't redirect if the timestamp is older than 5 minutes or so). After that clear both variables from the session.
This will lead to odd behaviour if the user violates against the assumption, but I don't think there is any way you can circumvent that.