We covered the Upload Demos in my GitHub File Upload Download with Jersey Demo App, so we'll complete the series by looking at the Secure Downloads Demo in this post.
Before going to the code, we'll walk through the process of how Secure Download works in the Demo App. First is our menu of both Public and Secure Downloads. There are two Secure Files for Download, one for those with a USER Role and a more secure file for those with an ADMIN Role.
When a user clicks on one of the Secure Files they are routed to the Login Page where the two available Demo Users are listed.
On login they are redirected back to the Downloads Menu with an alert (in green) stating what files they now have permission to download. Why go back to the Downloads Menu and not directly downloading the file? Because going directly to the download would indeed download the file but would be the total Response from the Server, with the bonus of the user staring at a blank browser window.
Now the files that the User can access are downloaded normally. On the other hand, if User KEN logs in with a USER Role and tries to download an ADMIN file they are shown the Unauthorized Page.
Shiro Config Code
We'll now throw up the essential code machinations for this particular Secure Downloads example. First the redirection to the Login Page is all Apache Shiro, with a little help from our Bootique YAML Config file.
This is a good time to mention how users are re-routed to the Unauthorized Page, as it, too, is all Shiro. We create a Roles Filter that extends Shiro's RolesAuthorizationFilter to handle it. I blogged about creating Shiro Custom Roles in this post.
Redirection on Login
I blogged about Redirection on Login with Shiro in this post. We're going to customize that logic for this demo where we redirect back to the Downloads Menu Page and display the user's Role in an alert message.
In the Login Submit Controller method we add a Redirect Url to our Mustache Templating Model. Here's the code for redirecting to the Downloads Menu with the appropriate Role Message.
We go to /downloads?msg=[ROLE] rather than simply /downloads. We first send the Url to our redirect.html page.
Then add the Query Parameter Role Name to our Mustache Model on the Downloads Page.
The Download Code
All Security Logic is handled by Shiro outside of the download logic, so both roles can share the same download method.
Source Code Notes for this Post
Source code discussed in this post is found in my File Upload Download in Bootique Jersey Demo app on GitHub.