Restful Web service Authentication and Authorization with Apache Shiro

Prem Singh Bist picture Prem Singh Bist · May 28, 2014 · Viewed 12.2k times · Source

I am able to authenticate web based application using apache shiro through databases using JDBC relam. Further more, I am successively able to make the use of Shiro-Filters to grant access for particular web-resource or http urls using Shiro filter configuation in web.xml and configuration into shiro.ini.

Now, I want to implement the same functionality for the webservices too. In Particular, I want user to hit the login-url for getting the token, if the credentials are valid. And after that, all the successive requests for the webservices has to be validated based on that particular token for the user. I have no any clue to implement this. Any suggestions, procedures, or suggestive links could help me alot !!

Answer

jeorfevre picture jeorfevre · May 31, 2014

I suggest you to use jersey web framwork since it's very simple, in java and annotated!

You specify your uri's, roles, permission in shiro.ini as you know and after that make a web project on jersey.

After that the use in a java code is clear and simple! See how to retrieve

Code in jersey :

/**
     * login to app
     * @param username
     * @param password
     * @return
     * since v0.6.4 
     */
    @PUT
    @Path("login")
    @Produces({"application/json"})
    public Response loginv3(
            @FormParam("username") String username,
            @FormParam("password") String password){

        return login(username, password);
    }

In this case we will retrieve the books only if are a user connected and that we have "reader" role :

  @GET
    @Path("/books")
    @Produces({"application/json"})
    @RequiresUser
    @RequiresRoles("reader")

It's realy easy! See the shiro documentation : shiro annotation reference