Java Reference
In-Depth Information
The
PerDayAuthorizer
class is annotated with
@AllowedPerDay
. This completes the
@NameBinding
we started when we implemented the
@AllowedPerDay
annotation interface.
The class is also annotated with
@Priority
. This annotation affects the ordering of filters as
they are applied to a JAX-RS method. We want this filter to run after any authentication
code, but before any application code, as we are figuring out whether or not a user is allowed
to invoke the request. If we did not annotate the
OneTimePasswordAuthenticator
and
Per-
DayAuthorizer
classes with the
@Priority
annotation, it is possible that the
Per-
DayAuthorizer
would be invoked before the
OneTimePasswordAuthenticator
filter. The
PerDayAuthorizer
needs to know the authenticated user created in the
OneTimePass-
wordAuthenticator
filter; otherwise, it won't work.
@Context
ResourceInfo info
;
We inject a
ResourceInfo
instance into the filter instance using the
@Context
annotation.
We'll need this variable to know the current JAX-RS method that is being invoked.
public
public
void
void
filter
(
ContainerRequestContext requestContext
)
throws
throws
IOException
{
SecurityContext sc
=
requestContext
.
getSecurityContext
();
iif
(
sc
==
null
new
ForbiddenException
();
Principal principal
=
sc
.
getUserPrincipal
();
iif
(
principal
==
null
null
)
throw
throw new
new
ForbiddenException
();
String user
=
principal
.
getName
();
null
)
throw
throw new
The
filter()
method first obtains the
SecurityContext
from the
ContainerRequestCon-
text.getSecurityContext()
method. If the context is null or the user principal is null, it
returns a 403, “Forbidden,” response to the client by throwing a
ForbiddenException
.
iif
(!
authorized
(
user
))
{
throw
throw new
new
ForbiddenException
();
}
}
The username value is passed to the
authorized()
method to check the permission. If the
method returns false, a 401, “Forbidden,” response is sent back to the client via a
Forbid-
denException
.
protected
protected static
static class
class
UserMethodKey
UserMethodKey
{
String username
;
Method method
;