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"
}

Answers


As per your edit: Check this SO Post:

Scanning Java annotations at runtime

I'd still recomend using Spring Secuity 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 sepring.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.


Need Your Help

Gmail IMAP : Any way to find all Labels (folders) a particular message is in?

gmail imap gmail-imap

So, Gmail's IMAP is a bit 'weird'. They use IMAP folders to represent Labels. I believe typically that an email in IMAP can only belong to one 'Folder', however with Gmail, an email message can b...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.