下面列出了怎么用javax.annotation.security.DenyAll的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
Annotation mpJwtAnnotation = getMpJwtAnnotation(resourceInfo);
if (mpJwtAnnotation != null) {
if (mpJwtAnnotation instanceof DenyAll) {
configureDenyAll(context);
} else if (mpJwtAnnotation instanceof RolesAllowed) {
configureRolesAllowed((RolesAllowed) mpJwtAnnotation, context);
}
} else {
// the resource method is not annotated and the class is not annotated either
if (hasSecurityAnnotations(resourceInfo) && shouldNonannotatedMethodsBeDenied()) {
// some other method has a security annotation and this one doesn't, it should be @DenyAll by default
configureDenyAll(context);
}
}
}
private Annotation getAuthAnnotation( AnnotatedElement element )
{
Annotation ann = element.getAnnotation( DenyAll.class );
if ( ann == null )
{
ann = element.getAnnotation( RolesAllowed.class );
}
if ( ann == null )
{
ann = element.getAnnotation( PermitAll.class );
}
if ( ann == null )
{
ann = element.getAnnotation( RelationCredibility.class );
}
return ann;
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());
final Annotation[][] parameterAnnotations = am.getParameterAnnotations();
if (am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) ||
am.isAnnotationPresent(PermitAll.class)) {
context.register(authFilter);
} else {
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation instanceof Auth) {
context.register(authFilter);
return;
}
}
}
}
}
/**
* Check does <tt>method</tt> contains one on of security annotations PermitAll, DenyAll, RolesAllowed.
*
* @see PermitAll
* @see DenyAll
* @see RolesAllowed
*/
@Override
public void accept(GenericResourceMethod method, Object[] params) throws WebApplicationException {
for (Annotation annotation : method.getAnnotations()) {
Class<?> annotationType = annotation.annotationType();
if (annotationType == PermitAll.class) {
return;
} else if (annotationType == DenyAll.class) {
throw new WebApplicationException(Response.status(FORBIDDEN)
.entity("User not authorized to call this method").type(TEXT_PLAIN)
.build());
} else if (annotationType == RolesAllowed.class) {
SecurityContext security = ApplicationContext.getCurrent().getSecurityContext();
for (String role : ((RolesAllowed)annotation).value()) {
if (security.isUserInRole(role)) {
return;
}
}
throw new WebApplicationException(Response.status(FORBIDDEN)
.entity("User not authorized to call this method").type(TEXT_PLAIN)
.build());
}
}
}
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
resourceMethod = mock(GenericResourceMethod.class);
permitAll = mock(PermitAll.class);
when(permitAll.annotationType()).thenReturn((Class)PermitAll.class);
denyAll = mock(DenyAll.class);
when(denyAll.annotationType()).thenReturn((Class)DenyAll.class);
rolesAllowed = mock(RolesAllowed.class);
when(rolesAllowed.annotationType()).thenReturn((Class)RolesAllowed.class);
when(rolesAllowed.value()).thenReturn(new String[]{"user"});
ApplicationContext applicationContext = mock(ApplicationContext.class);
securityContext = mock(SecurityContext.class);
when(applicationContext.getSecurityContext()).thenReturn(securityContext);
ApplicationContext.setCurrent(applicationContext);
securityConstraint = new SecurityConstraint();
}
@GET()
@Path("deny-all")
@DenyAll
@Produces(MediaType.TEXT_PLAIN)
public String helloShouldDeny(@Context SecurityContext ctx) {
Principal caller = ctx.getUserPrincipal();
String name = caller == null ? "anonymous" : caller.getName();
return "hello + " + name;
}
@GET
@Path("locked")
@Produces("application/json")
@DenyAll
public Response getLockedData(int id) {
return null;
}
@DenyAll
@GET
@Path("denied")
public String getSubjectDenied(@Context SecurityContext sec) {
Principal user = sec.getUserPrincipal();
String name = user != null ? user.getName() : "anonymous";
return name;
}
@DenyAll
@GET
@Path("denied")
public String getSubjectDenied(@Context SecurityContext sec) {
Principal user = sec.getUserPrincipal();
String name = user != null ? user.getName() : "anonymous";
return name;
}
@DenyAll
@GET
@Path("denied")
public String getSubjectDenied(@Context SecurityContext sec) {
Principal user = sec.getUserPrincipal();
String name = user != null ? user.getName() : "anonymous";
return name;
}
@DenyAll
@GET
@Path("denied")
public String getSubjectDenied(@Context SecurityContext sec) {
Principal user = sec.getUserPrincipal();
String name = user != null ? user.getName() : "anonymous";
return name;
}
@GET
@Path("/nobody")
@Produces(MediaType.TEXT_PLAIN)
@DenyAll()
public String nobody() {
return "nobody";
}
/**
* Check if all relevant methods in use case implementations have permission checks i.e. {@link RolesAllowed},
* {@link DenyAll} or {@link PermitAll} annotation is applied. This is only checked for methods that are declared in
* the corresponding interface and thus have the {@link Override} annotations applied.
*/
@Test
@Ignore // Currently Access control has not been implemented in jumpthequeue so the test is ignored
public void permissionCheckAnnotationPresent() {
String packageName = "com.devonfw.application.jtqj";
Filter<String> filter = new Filter<String>() {
@Override
public boolean accept(String value) {
return value.contains(".logic.impl.usecase.Uc") && value.endsWith("Impl");
}
};
ReflectionUtil ru = ReflectionUtilImpl.getInstance();
Set<String> classNames = ru.findClassNames(packageName, true, filter);
Set<Class<?>> classes = ru.loadClasses(classNames);
SoftAssertions assertions = new SoftAssertions();
for (Class<?> clazz : classes) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Method parentMethod = ru.getParentMethod(method);
if (parentMethod != null) {
Class<?> declaringClass = parentMethod.getDeclaringClass();
if (declaringClass.isInterface() && declaringClass.getSimpleName().startsWith("Uc")) {
boolean hasAnnotation = false;
if (method.getAnnotation(RolesAllowed.class) != null || method.getAnnotation(DenyAll.class) != null
|| method.getAnnotation(PermitAll.class) != null) {
hasAnnotation = true;
}
assertions.assertThat(hasAnnotation)
.as("Method " + method.getName() + " in Class " + clazz.getSimpleName() + " is missing access control")
.isTrue();
}
}
}
}
assertions.assertAll();
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext configuration) {
final Method am = resourceInfo.getResourceMethod();
try {
// DenyAll on the method take precedence over RolesAllowed and PermitAll
if (am.isAnnotationPresent(DenyAll.class)) {
configuration.register(new RolesAllowedRequestFilter());
return;
}
// RolesAllowed on the method takes precedence over PermitAll
Optional<Annotation> ra = Arrays.stream(am.getAnnotations())
.filter(a -> a.annotationType().getName().equals(RolesAllowed.class.getName())).findFirst();
if (ra.isPresent()) {
configuration.register(new RolesAllowedRequestFilter(((RolesAllowed) ra.get()).value()));
return;
}
// PermitAll takes precedence over RolesAllowed on the class
if (am.isAnnotationPresent(PermitAll.class)) {
// Do nothing.
return;
}
// DenyAll can't be attached to classes
// RolesAllowed on the class takes precedence over PermitAll
ra = Arrays.stream(resourceInfo.getResourceClass().getAnnotations())
.filter(a -> a.annotationType().getName().equals(RolesAllowed.class.getName())).findFirst();
if (ra.isPresent()) {
configuration.register(new RolesAllowedRequestFilter(((RolesAllowed) ra.get()).value()));
}
} catch (Exception e) {
logger.error("Error while configuring the roles", e);
}
}
@Override
public boolean test(Scope scope) {
AnnotatedMethod am = new AnnotatedMethod(scope.getInvokedMethod());
// DenyAll on the method take precedence over RolesAllowed and PermitAll
if (am.isAnnotationPresent(DenyAll.class)) {
return false;
}
// RolesAllowed on the method takes precedence over PermitAll
RolesAllowed ra = am.getAnnotation(RolesAllowed.class);
if (ra != null) {
return checkRoles(ra.value());
}
// PermitAll takes precedence over RolesAllowed on the class
if (am.isAnnotationPresent(PermitAll.class)) {
// Do nothing.
return true;
}
// DenyAll can't be attached to classes
// RolesAllowed on the class takes precedence over PermitAll
ra = scope.getInvokedClass().getAnnotation(RolesAllowed.class);
if (ra != null) {
return checkRoles(ra.value());
}
return true;
}
private boolean isAccessForbidden(
ClassOrInterfaceDeclaration typeDeclaration,
MethodDeclaration methodDeclaration) {
return !methodDeclaration.isPublic()
|| (hasSecurityAnnotation(methodDeclaration)
? methodDeclaration.isAnnotationPresent(DenyAll.class)
: typeDeclaration.isAnnotationPresent(DenyAll.class));
}
private boolean entityForbidden(AnnotatedElement entity,
HttpServletRequest request) {
return entity.isAnnotationPresent(DenyAll.class) || (!entity
.isAnnotationPresent(AnonymousAllowed.class)
&& !roleAllowed(entity.getAnnotation(RolesAllowed.class),
request));
}
private void assertPaths(Paths actualPaths,
List<Class<?>> testEndpointClasses) {
int pathCount = 0;
for (Class<?> testEndpointClass : testEndpointClasses) {
for (Method expectedEndpointMethod : testEndpointClass
.getDeclaredMethods()) {
if (!Modifier.isPublic(expectedEndpointMethod.getModifiers())
|| accessChecker
.getSecurityTarget(expectedEndpointMethod)
.isAnnotationPresent(DenyAll.class)) {
continue;
}
pathCount++;
String expectedEndpointUrl = String.format("/%s/%s",
getEndpointName(testEndpointClass),
expectedEndpointMethod.getName());
PathItem actualPath = actualPaths.get(expectedEndpointUrl);
assertNotNull(String.format(
"Expected to find a path '%s' for the endpoint method '%s' in the class '%s'",
expectedEndpointUrl, expectedEndpointMethod,
testEndpointClass), actualPath);
assertPath(testEndpointClass, expectedEndpointMethod, actualPath);
}
}
assertEquals("Unexpected number of OpenAPI paths found", pathCount,
actualPaths.size());
}
@Test
public void should_Fail_When_DenyAllClass() throws Exception {
@DenyAll
class Test {
public void test() {
}
}
shouldFail(Test.class);
}
@Test()
public void should_Pass_When_DenyAllClass_ValidRoleMethod()
throws Exception {
@DenyAll
class Test {
@RolesAllowed(ROLE_USER)
public void test() {
}
}
shouldPass(Test.class);
}
@Test()
public void should_Pass_When_DenyAllClass_PermitAllMethod()
throws Exception {
@DenyAll
class Test {
@PermitAll
public void test() {
}
}
shouldPass(Test.class);
}
@Test
public void should_DisallowAnyAuthenticatedAccess_When_DenyAllAndAnonymousAllowed()
throws Exception {
class Test {
@DenyAll
@AnonymousAllowed
public void test() {
}
}
shouldFail(Test.class);
}
@Test
public void should_DisallowAnonymousAccess_When_DenyAllAndAnonymousAllowed()
throws Exception {
class Test {
@DenyAll
@AnonymousAllowed
public void test() {
}
}
createAnonymousContext();
shouldFail(Test.class);
}
@Test
public void should_DisallowAnonymousAccess_When_AnonymousAllowedIsOverriddenWithDenyAll()
throws Exception {
@AnonymousAllowed
class Test {
@DenyAll
public void test() {
}
}
createAnonymousContext();
shouldFail(Test.class);
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());
// DenyAll on the method take precedence over RolesAllowed and PermitAll
if (am.isAnnotationPresent(DenyAll.class)) {
context.register(new RolesAllowedRequestFilter());
return;
}
// RolesAllowed on the method takes precedence over PermitAll
RolesAllowed ra = am.getAnnotation(RolesAllowed.class);
if (ra != null) {
context.register(new RolesAllowedRequestFilter(ra.value()));
return;
}
// PermitAll takes precedence over RolesAllowed on the class
if (am.isAnnotationPresent(PermitAll.class)) {
// Do nothing.
return;
}
// DenyAll can't be attached to classes
// RolesAllowed on the class takes precedence over PermitAll
ra = resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
if (ra != null) {
context.register(new RolesAllowedRequestFilter(ra.value()));
}
}
private void checkLoggedIn(InvocationContext invocationContext) {
LoggedIn loggedIn = AnnotationUtil.getAnnotation(invocationContext, LoggedIn.class);
DenyAll denyAll = AnnotationUtil.getAnnotation(invocationContext, DenyAll.class);
if (loggedIn != null || denyAll != null) {
if(!identity.isLoggedIn()) {
throw new NotLoggedInException(identity+" Not logged in");
}
}
}
@DenyAll
public String denied() {
return "callingDenied";
}
@GET
@DenyAll
@Path("denied")
public String denied() {
return "denied";
}
@DenyAll
public String forbiddenOnMethod() {
return "forbiddenOnMethod";
}
@DenyAll
public String deniedInSubclass() {
return "deniedInSubclass";
}