0
votes

Im building a web service app using jersey. For authorization/authentication im using apache shiro.

I found some tutorials showing how to use apache shiro in a web app. They show the login method using a .jsp page that have a username and password field and than this .jsp page is configured in shiro.ini like this:

[main]

shiro.loginUrl = /login.jsp

[urls]
/login.jsp = authc
/logout = logout

I Wanna know how to make this authentication without a any .jsp page, because my project have only web services. So i think that i need a login service, than i created one:

@POST
@Path("/login")
public Response login(@FormParam("username") final String username, @FormParam("password") final String password, @FormParam("remember") final boolean remember) {

    final Subject currentUser = SecurityUtils.getSubject();

    if (!currentUser.isAuthenticated()) {
        final UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            token.setRememberMe(remember);
            currentUser.login(token);
        } catch (final AuthenticationException e) {
            return Response.status(Status.BAD_REQUEST).entity("Usuário ou senha inválido").build();
        }
    }

And this is my shiro.ini conf:

[urls]
/security/login = anon
/security/isAuthenticated = anon
/** = authcBasic

Once that the user wont be authenticated to log in i include /security/login = anon.

Is this the correct way to authenticated a user with apache shiro in a webservice environment?

1

1 Answers

0
votes

You don't need a login service. Actually, authenticating and using the service should be two different things. What you need to do is:

  • Know what pages do you want to authenticate
  • Configure Shiro to authenticate those pages through your authentication method.

your shiro.ini will look to something like this:

[main]
myRealm = com.my.package.MyRealm
myAuthc = com.my.package.MyAuthenticationFilter

[urls]
/public/** = anon
/** = myAuthc

You will need to implement both the realm and the filter. You can implement the filter using AuthenticatingFilter or even one of the sub-classes, like BasicHttpAuthenticationFilter. The realm can be implemented using the AuthenticatingRealm class.

More on realms here and more on Shiro on web here. Notice that to make your filter available what you will need to do is basically set up the filter on the web.xml

After coding the realm and the filter, your code should work as expected. As defined on the shiro.ini any path that starts with public/ will not be authenticated and all the other paths will be authenticated through your com.my.package.MyAuthenticationFilter. Please notice that order matters: if you define the /** = myAuthc line first it will authenticate everything, including paths that start with /public/.