Securing Shell using Annotations

We are going to have a look at how to create our own annotation to secure some commands. When we annotate a command with our annotation, it will make sure that user needs to authenticated in order to use it. It is going to look like this.

@Secured
@ShellMethod(key = "logout", value = "Logout from GitHub. Usage: logout")
public void logout() {
    sessionHolder.removeCurrentSession();
}

First, create build.gradle with all needed dependencies.

group 'shell'
version '0.0.1'

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE'
    }
}

apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven {
        url 'https://repo.spring.io/libs-milestone'
    }
}

dependencies {
    compile 'org.springframework.shell:spring-shell-starter:2.0.0.M2'
    compile "org.springframework:spring-aop:4.3.13.RELEASE"
    compile "org.springframework:spring-web:4.3.13.RELEASE"
    compile "org.aspectj:aspectjrt:1.8.13"
    compile "org.aspectj:aspectjweaver:1.8.13"
}

Now we need to create the new annotation @Secured.

Then we create an aspect that will add required functionality to @Secure annotation. In the aspect, we want to make sure a session exists before the annotated method is invoked. If session does not exist, we throw an exception to indicate user needs to authenticate first.

In SecuredAspect class, there is usage of SessionHolder bean. sessionHolder bean is a singleton by default and it holds a session. Here is how such a class could look like.

Here is the implementation.

And here the session object.

When user login operation is successful, we set a value in the session holder. It could look like this.

You can have a look at the whole example in this github repositoryarrow-up-right.

Last updated