Application Platform 10.3 | Application Platform API | Adding Single Sign-On Authentication to Application Platform Projects | OSGi Service Layer Security | Dynamic Runtime Security
 
Dynamic Runtime Security
Application Platform enables you to implement dynamic runtime authentication and authorization, in which the roles allowed for a user are not known in advance. To add dynamic runtime security, you can use the SecurityContext class. If the SecurityContext field type is specified in the class and gets injected at runtime, you must add the @Secure annotation to the corresponding Application Platform POJO service class.
The following sample code shows an implementation of dynamic runtime security in an OSGi service, where:
*A POJO class, named GreeterImpl, implements the IGreeter interface. The IGreeter interface is marked as secure with the @Secure annotation.
*The @DenyAll annotation at the class level denies access to all methods at runtime.
*The @RolesAllowed annotation overrides the @DenyAll annotation for the greetMe method for users that have Administrators or Developers role.
*The logCurrentSubject method uses the secContext field to retrieve the Java Authentication and Authorization Service (JAAS) Subject representation of the currently logged in user. The secContext field is of type SecurityContext and it is injected at runtime before the logCurrentSubject method is invoked with a valid instance.
*After the logCurrentSubject method retrieves the JAAS Subject, it prints the instance details of the associated Principal.
@Service
@Secure
@DenyAll
public class GreeterImpl implements IGreeter {
 
    public static final String KEY_HELLO = "hello";
    private String key = KEY_HELLO;
 
    @ServiceReference(id = "resourceUtilRef", interfaces =
    { "com.example.osgi.greet.impl.ResourceUtil" })
    ResourceUtil resUtil;
 
//injected at method invocation time
    private SecurityContext secContext;
 
    @Override
    @RolesAllowed({ "Administrators", "Developers" })
    public String greetMe(String name) {
       logCurrentSubject();
       return greetMe(name, Locale.getDefault());
    }
private void logCurrentSubject() {
    Subject subj = secContext.currentSubject();
    if (subj != null) {
       Set<SagUserPrincipal> users = subj.getPrincipals(SagUserPrincipal.class);
       if (users != null) {
            for (SagUserPrincipal sup : users) {
            System.out.println("Current logged in user is " + sup.getName());
            }
       }
       } else {
            System.err.println("No authenticated subject found!");
       }
    }
}