Kronos Varmentos Kronos Varmentos - 1 month ago 7
Java Question

Can you use Java Annotations to evaluate something in a method?

I want to see if it is possible to use annotations to evaulate if a user is logged in or not.

Example

@AuthRequired
public String myProtectedArea() {
return View("view/protectedArea"); // If user is NOT authenticated, return "view/login"
}

Answer

As per your edit: Check this SO Post:

Scanning Java annotations at runtime

I'd still recommend using Spring Security for this, it's tested and secure:

@PreAuthorize("hasRole('ROLE_USER')")
public String myProtectedArea() {
  return View("view/protectedArea"); 
}

The annotation will check if the user is logged in and has the required credentials.

Another way with Spring Security is to intercept the URL pattern by setting this inside a spring.security-settings.xml:

    <intercept-url pattern="/view/protectedArea/*" access="hasRole('ROLE_USER')" />

I'd recommend using both to maximize security.

In the security settings file you can then tell spring security where to redirect the user to login. If the user is already logged in, you can redirect him to yet another page:

<form-login login-page="/view/login.xhtml" default-target-url="/view/protectedArea/home.xhtml"
            authentication-failure-url="/view/login.xhtml" />

It's a tested framework and thus secure and versatile. However it requires a bit of setting up if you want more than the standard behaviour.

Comments