Securing URLs using Spring Security

Typically when securing a URL you are looking to do one of the following –

  • Allow access to everyone to a given URL
  • Secure URL based on roles
  • Secure URL based on multiple roles
  • Secure URL based on IP Address

This post shows how to do this using spring security

Specifying URL’s

The most common approach to specifying a URL is through antMatcher’s

So if we want to secure –

http://www.example.com/static Open to everyone – css, javascript
http://www.example.com/register Open to everyone
http://www.example.com/login Open to everyone
http://www.example.com/user/ ROLE_USER or ROLE_ADMIN – User Area
http://www.example.com/admin/ ROLE_ADMIN only and restrict on IPADDRESS – Admin Area

We would simply use –

.antMatchers("/register")

Or with multiple –

.antMatchers("/register","/login","/user","/admin")

We also specify individual pages or directories –

.antMatchers("register.html"); // Individual
.antMatchers("/admin/**"); // Directory

Depending on the complexity of pattern you are securing you can also consider –

Securing the URL’s

The methods to secure URL’s are defined in AuthorizedUrl

The most common methods are –

  • authenticated() – This is the URL you want to protect, and requires the user to login
  • permitAll() – This is used for URL’s with no security applied for example css, javascript
  • hasRole(String role) – Restrict to single role. Note that the role will have “ROLE_” appended. So role=”ADMIN” has a comparison against “ROLE_ADMIN”. An alternatve is hasAuthority(String authority)
  • hasAnyRole(String… roles) – Allows multiple roles. An alternative is hasAnyAuthority(String… authorities)

Other useful methods are –

  • access(String attribute) – This method takes SPEL, so you can create more complex restrictions. For those who are interested a lot of the methods in  ExpressionUrlAuthorizationConfigurer.AuthorizedUrl ultimately call access with the required SPEL
  • hasIpAddress(String ipaddressExpression) – Restrict on IP address or subnet

Putting it all together

We can put this altogher and create a method like –

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
        .authorizeRequests()
           .antMatchers("/static","/register").permitAll()
           .antMatchers("/user/**").hasRoles("USER", "ADMIN") // can pass multiple roles
           .antMatchers("/admin/**").access("hasRole('ADMIN') and hasIpAddress('123.123.123.123')") // pass SPEL using access method
           .anyRequest().authenticated()
           .and()
       .formLogin()
           .loginUrl("/login")
           .permitAll();
    }

The key points are –

  • permitAll gives everyone access to a file or directory
  • hasRoles passes multiple roles
  • access for more compicated access

As a side note I am currently working on a project to automatically generate this configuration with my spring-security-generator

 

 

Auto-generating Spring Security Tutorial – Custom JDBC Realms

This post builds on the set of spring-security posts I have done, and particularly my last post on Default JDBC Realms. The code is available on github, and spring-security-generator and the instructions to run the application are contained in the previous tutorial.

We also have a requirement to use a custom JDBC realm with the structure –

USER PASSWORD ROLES
customadmin customadmin ROLE_CUSTOM_ADMIN

Custom JDBC Tables

The tables Ive used in this example are renamed versions of the default tables -

create table custom_users (
  username varchar(256),
  password varchar(256),
  enabled boolean
);
create table custom_authorities (
  username varchar(256),
  authority varchar(256)
);
With inserts - 

insert into custom_users (username, password, enabled) values ('customadmin', 'customadmin', true);
insert into custom_authorities (username, authority) values ('customadmin', 'ROLE_CUSTOM_ADMIN');

Spring-Security-Generator

Using spring-security-generator we now select “JDBC Realm (Custom)” and supply the queries –

select username, password, enabled from custom_users where username = ?
select username, authority from custom_authorities where username = ?

The screen configuration is then –

screen-shot-2016-11-07-at-21-00-50

We then generate the code –

package com.glenware.springboot;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
         auth
             .jdbcAuthentication()
                 .dataSource(dataSource)
                   .usersByUsernameQuery(
                   "select username, password, enabled from custom_users where username = ?")
                   .authoritiesByUsernameQuery(
                   "select username, authority from custom_authorities where username = ?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/webjars/**","/about.html","/rest/**").permitAll()
                .antMatchers("/admin/**").hasAnyRole("CUSTOM_ADMIN")
                .anyRequest().authenticated()
            .and()
                .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/admin/admin.html")
                    .failureUrl("/login")
                    .permitAll()
             .and()
                .logout()
                    .logoutSuccessUrl("/")
                    .permitAll()
                    ;
    }
    
}

The key difference between this tutorial and the previous is that we supply the SQL directly to the usersByUsernameQuery and authoritiesByUsernameQuery

We can now copy this code to the parkrunpb applicaiton, and login using customadmin/customadmin

Auto-generating Spring Security Tutorial – Default JDBC Realms

The previous tutorial showed how we can auto-generate of spring security using a memory realm. This tutorial expands on this to cover Default JDBC Realms using the source code from the parkrunPB application

Security Requirements

The site has the following links and security requirements –

http://localhost:8080/ Accessible to all
http://localhost:8080/webjars Static Resources – Accessible to all
http://localhost:8080/about.html Static page – Accessible to all
http://localhost:8080/login.html Accessible to all
http://localhost:8080/admin/ Admin User
http://localhost:8080/rest Accessible to all

We also have a requirement to use a users and roles with the structure –

USER PASSWORD ROLES
admin admin ADMIN

Getting Started

The first thing we need to do is uncomment spring security in the maven pom –

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

We can then compile and run the code –

mvn spring-boot:run

The whole application is now locked down

Luckily we can login using the default username (user), and the password from the logs. Im my case –

2016-11-06 21:16:56.877 INFO 8088 --- [main] b.a.s.AuthenticationManagerConfiguration :
 Using default security password: e1c87658-8b7e-4b1e-88da-902b5356ef66

Default JDBC Tables

We can now begin to create our SecurityConfiguration using Spring Security Generator

screen-shot-2016-11-06-at-21-33-53

We then get the generated source code –

package com.glenware.springboot;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private DataSource dataSource;

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)
			throws Exception {
         auth
             .jdbcAuthentication()
                 .dataSource(dataSource)
                     .withDefaultSchema()
				.withUser("admin").password("admin").roles("ADMIN");
	}

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/webjars/*","/about.html","/rest/**").permitAll()
                .antMatchers("/admin/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
            .and()
                .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/admin/admin.html")
                    .failureUrl("/login")
                    .permitAll()
             .and()
                .logout()
                    .logoutSuccessUrl("/")
                    .permitAll()
                    ;
	}

}

Key Points

  • Using JDBC Realm(Default) – The default realm means Spring Security will use its default users.ddl
  • Same configuration as before

We can now access the site the same as the memory realm, but with user details stored in the database. The next post will look at using a custom JDBC table

procrun – Java Programs as Windows Services

I recently needed to run a Java program as a Windows service, and opted for Commons-daemon procrun. This wrapper is used by both Tomcat and JBoss Wildfly to wrap their servers – but took a bit of figuring out how to get my application running.

This post sets out an example of using procrun to wrap a Java process.

Download

I downloaded procrun from download. The download contains 3 different version of the procrun.exe –

  • 32 bit – this is the default architecture
  • amd64 – 64-bit AMD architecture
  • ia64 – 64-bit Intel Itanium architecture

You need to use the right version for your JVM and chipset

Code

The code is based on the EchoServer and EchoClient examples from oracle.

EchoServer

import java.net.*;
import java.io.*;
 
public class EchoServer {
    public static void main(String[] args) throws IOException {
         
        if (args.length != 1) {
            System.err.println("Usage: java EchoServer <port number>");
            System.exit(1);
        }
         
        int portNumber = Integer.parseInt(args[0]);
         
        try (
            ServerSocket serverSocket =
                new ServerSocket(Integer.parseInt(args[0]));
            Socket clientSocket = serverSocket.accept();     
            PrintWriter out =
                new PrintWriter(clientSocket.getOutputStream(), true);                   
            BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
        ) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                out.println(inputLine);
            }
        } catch (IOException e) {
            System.out.println("Exception caught when trying to listen on port "
                + portNumber + " or listening for a connection");
            System.out.println(e.getMessage());
        }
    }
}

EchoClient

The client is changed to take a shutdown parameter –

import java.io.*;
import java.net.*;
 
public class EchoClient {
    public static void main(String[] args) throws IOException {
         
        if (args.length != 3) {
            System.err.println(
                "Usage: java EchoClient <host name> <port number>");
            System.exit(1);
        }
 
        String hostName = args[0];
        int portNumber = Integer.parseInt(args[1]);
        String shutdown = args[2];
 
        try (
            Socket echoSocket = new Socket(hostName, portNumber);
            PrintWriter out =
                new PrintWriter(echoSocket.getOutputStream(), true);
            BufferedReader in =
                new BufferedReader(
                    new InputStreamReader(echoSocket.getInputStream()));
            BufferedReader stdIn =
                new BufferedReader(
                    new InputStreamReader(System.in))
        ) {
            String userInput;
            if (shutdown != null && !"".equals(shutdown)) {
                userInput = shutdown;
            }
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                System.out.println("echo: " + in.readLine());
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        } 
    }
}

Prunssrv

Ive also created a simple class to stop and start the server –

import java.net.*;
import java.io.*;

public class Prunssrv {
    public static void prunsrvStartServer(String[] args) throws Exception {
        String[] newArgs = new String[1];
        newArgs[0] = System.getProperty("prunsrv.port"); // -Dprunsrv.port=8080

        EchoServer.main(newArgs); 
    }
    
    public static void prunsrvStopServer(String[] args) throws Exception {
        String[] newArgs = new String[2];
        newArgs[0] = System.getProperty("prunsrv.server"); // -Dprunsrv.server=localhost
        newArgs[1] = System.getProperty("prunsrv.port"); // -Dprunsrv.port=8080
        newArgs[1] = "shutdown";
        
        EchoClient.main(newArgs);
    }
}

Putting it all together –

  1. Add the above classes and procrun.exe to a directory – C:\procrun
  2. Compile – javac *.java
  3. Create Archive – jar cvf simpleechoserver.jar *.class *.jar

service.bat

You dont need to create a service.bat file – but its cleaner and simpler. Store this in your code directory.

@echo off
setlocal

set SERVICE_NAME=SimpleEchoServer

set PR_INSTALL=%~dp0%prunsrv.exe
set PR_DESCRIPTION="Simple Echo Server Service"

REM Service log configuration
set PR_LOGPREFIX=%SERVICE_NAME%
set PR_LOGPATH=%~dp0%\
set PR_STDOUTPUT=%~dp0%\stdout.txt
set PR_STDERROR=%~dp0%\stderr.txt
set PR_LOGLEVEL=Debug
 
REM Path to java installation
set PR_JVM=%JAVA_HOME%\jre\bin\server\jvm.dll
set PR_CLASSPATH=simpleechoserver.jar
 
REM Startup configuration
set PR_STARTUP=auto
set PR_STARTMODE=jvm
set PR_STARTCLASS=Prunssrv
set PR_STARTMETHOD=prunsrvStartServer
 
REM Shutdown configuration
set PR_STOPMODE=jvm
set PR_STOPCLASS=Prunssrv
set PR_STOPMETHOD=prunsrvStopServer
set PR_STOPTIMEOUT=120
 
REM JVM configuration
set PR_JVMMS=256
set PR_JVMMX=1024
set PR_JVMSS=4000

REM JVM options
set prunsrv_port=8080
set prunsrv_server=localhost

set PR_JVMOPTIONS=-Dprunsrv.port=%prunsrv_port%;-Dprunsrv.server=%prunsrv_server%

REM current file
set "SELF=%~dp0%service.bat"
REM current directory
set "CURRENT_DIR=%cd%"
 
REM start - This takes the input from installService and places it between x's
REM       - if there are none then you get xx as a null check
if "x%1x" == "xx" goto displayUsage
set SERVICE_CMD=%1
REM ahift moves to next field
shift
if "x%1x" == "xx" goto checkServiceCmd
:checkServiceCmd
if /i %SERVICE_CMD% == install goto doInstall
if /i %SERVICE_CMD% == remove goto doRemove
if /i %SERVICE_CMD% == uninstall goto doRemove
echo Unknown parameter "%SERVICE_CMD%"
:displayUsage
echo.
echo Usage: service.bat install/remove
goto end
:doRemove
echo Removing the service '%PR_INSTALL%' '%SERVICE_NAME%' ...
%PR_INSTALL% //DS//%SERVICE_NAME%
if not errorlevel 1 goto removed
echo Failed removing '%SERVICE_NAME%' service
goto end
:removed
echo The service '%SERVICE_NAME%' has been removed
goto end
:doInstall
echo Installing the service '%PR_INSTALL%' '%SERVICE_NAME%' ...
%PR_INSTALL% //IS//%SERVICE_NAME% 
goto end
:end
echo Exiting service.bat ...
cd "%CURRENT_DIR%"

Key Points

  • All the Procrun fields are marked with PR_ – you can also feed these fields directly to procrun.exe using the ++ or — notation in the procrun notes, but i think this way is cleaner and easier to maintain
  • The key ones are the start/stop fields
  • PR_JVMOPTIONS – allows us to pass system properties to the Windows Service
  • Installing and removing –
    %PR_INSTALL% //IS//%SERVICE_NAME%
    %PR_INSTALL% //DS//%SERVICE_NAME%
  • There are other “//” options defined in the notes

Running service.bat

You may need to run this as administrator –

C:\procrun>service.bat

Usage: service.bat install/remove
Exiting service.bat ...

To install –

service.bat install

And uninstall –

service.bat remove

You can then test –

java EchoClient localhost 8080
hello
echo: hello
...

If you go to your Windows Services you will now see SimpleEchoServer with stop/start/restart options

prunmgr.exe

The final trick is to use prunmgr. This the the procrun manager and allows you to see the procrun operating parameters. To get started go to your copy of prunmgr.exe and rename or copy it to the SERVICE_NAME in your batch file

set SERVICE_NAME=SimpleEchoServer

So –

C:\procrun>copy prunmgr.exe SimpleEchoServer.exe

You then run the SimpleEchoServer.exe as administrator –

simpleechoserver

Reference

https://commons.apache.org/proper/commons-daemon/procrun.html

Auto-generating Spring Security Tutorial – Memory Realms

I created a demo spring boot application under github.com/farrelmr/parkrunpbreboot

parkrunpbreboot1

The application is simple and allows your to predict your 5km running time based on previous parkrun performances. For those who dont know what a parkrun is its a free 5km timed run held weekly in an increasing number of places.

Security Requirements

The site has the following links and security requirements –

http://localhost:8080/ Accessible to all
http://localhost:8080/webjars Static Resources – Accessible to all
http://localhost:8080/about.html Static page – Accessible to all
http://localhost:8080/login.html Accessible to all
http://localhost:8080/admin/ Admin User
http://localhost:8080/rest Accessible to all

We also have a requirement to use a memory realm with the structure –

USER PASSWORD ROLES
admin admin admin

Getting Started

The first thing we need to do is uncomment spring security in the maven pom –

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

We can now begin to create our SecurityConfiguration using –

http://www.glenware.com/spring-security-generator

springsecuritygenerator

Memory Realm with Basic Authentication

The first step is to configure the memory realm. The other security options are Default JDBC, and LDAP, and will be covered in later tutorials

basicauthenticationspringsec

The code is available on gist

We can then copy the generated code to com.glenware.springboot.SecurityConfig, and test the application. The whole application is secured, with the password admin/admin.

We now get the default login page –

login

Fine Tuning

We can now fine tune the requirements –

screen-shot-2016-10-09-at-21-17-08

Again the code is available on gist

This allows free access to the site, except for the admin sections as required. We also now have a formatted login page.

Conclusions

The above tutorial shows how a menu driven application can automatically and simply provide your spring security. The next areas of work are to improve JDBC and REST functionality

Can Spring Security be auto-generated?

I’ve generally found Security requirements are easy to state, but hard to implement. So have been wondering if I can autogenerate my Spring Security configuration.

Security Requirements

Common security requirements are –

  • Access controls on files/directories based on roles, IP address
  • Validation of credentials from a authentication provider

 

Coding

The problem with coding yourself is –

  • Security is complex and you need to know what your doing – there is a lot of information in the Spring Security manual
  • Upgrades – Spring Security could upgrade and you could miss out on new features to improve your security
  • Bugs – you introduce a bug in your code

It would be easier if I could define my security requirements into a website and autogenerate my security configuration.

Prototype

I’ve created a prototype of this idea at spring-security-generator, with the code released on github

2016-10-02-21_51_07-spring-security-generator

Future

I see this idea evolving to include –

  • Tutorial – soon to be released
  • REST API security
  • Automate creation of unit tests, login pages
  • Best practice – what are the best practice for configurations of spring security?
  • Storing security configuration

Solving Spring NoClassDefFoundError, ClassNotFoundException and MethodNotFoundExceptions Errors

I see a lot of Spring questions on Stackoverflow about NoClassDefFoundError, ClassNotFoundException and MethodNotFoundExceptions, especially with Spring Boot. The cause is nearly always a change to a build dependency in gradle or maven has resulted in the mixing of dependencies. This post considers how approach these issues, providing a starting point and possibly resolving these issues.

Steps

  • Do a clean build – the conflict is being caused by out of date libraries in the maven repository
  • If problems still exist then check Spring’s bill-of-materials to see what versions are recommended, and if they are in conflict with your own pom file versions. The purpose of the bom is discussed in my previous post(https://www.javabullets.com/2016/09/07/maven-bill-of-materialsbom/)
  • Check which spring-framework-bom you are using – the import will be of the form –
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.3.2.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

In this case we are using 4.3.2.RELEASE. You can then check what versions of other packages spring is using using mvnrepository(https://mvnrepository.com/artifact/org.springframework/spring-framework-bom/4.3.2.RELEASE).

  • For spring boot you can further check dependencies using the spring-boot-dependencies pom –

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-dependencies

Conflicts

If the above highlights a conflict then your options are –

  • Use the Spring Dependencies – Can you use the dependency version from the spring-bom or dependencies?
  • Dependency Management – can you manage the issue through dependency management?
  • Code Change – It may be that you are upgrading your spring boot or spring version to the latest version. It might be the API’s have changed, so you have to change your code. Time to get the manuals out

Maven bill of materials (bom)

The purpose of a bill of materials(bom) is to centrally manage Maven dependencies and reduce the chances of version mismatches. The concept is orignally from supply chain management where it is used to track parts.

The key points of boms are –

  • Special maven project to centrally manage dependencies
  • Managed in dependencyManagement section of type – <type>pom</type>
  • Allow dependencies to cascade down through projects using <dependencyManagement>
  • The bill of materials pom.xml will only list supported versions
  • Simplify dependency import in child projects because you do not need to specify dependency versions

Example

One advantage of bill-of-materials is that you can set out the recommended version dependencies, and use these through your application framework-

[sourcecode lang=”xml”] <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
[/sourcecode]

You can then import dependencies in sub-project pom’s without version numbers –

[sourcecode lang=”xml”] <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
[/sourcecode]

Reference

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/overview.html

RESTful and HATEOAS Services – Revisited

I get a lot of traffic for my original article on RESTful and HATEOAS services, so I’ve decided to update and revise the article.

What are RESTful Services?

REST stands for Representational State Transfer. The main selling point of RESTful Services is that they are designed to be used on the internet using HTTP. It has the following constraints –

  • Resources – Easily understood directory structure URI
  • Uniform Interface – Create, Retrieve, Update, Delete are accessed over HTTP via POST, GET, PUT, and DELETE methods
  • Messages – Most commonly these are JSON, but can be any format – HTML, XML, plain text, …
  • Stateless – Interactions not stored, and state is handled in the request

RESTful Examples

GET Select GET /customerservice/customers/1
POST Create POST /customerservice/customers
PUT Update or Create – Idempotent PUT /customerservice/customers
PATCH Update only – Idempotent PATCH /customerservice/customers/1
DELETE Remove record DELETE /customerservice/customers/1

The HTTP return codes are used for success/failure –

1xx Informational
2xx Success
3xx Redirection
4xx Client Error
5xx Server Error

HATEOAS – Hypermedia as the Engine of Application State

HATEOAS is an additional constraint on RESTful services. It requires the response to return the location of the data, and you can also return a list of other operations at that point. The advantage of this approach is that you can navigate the RESTful service model.

HATEOAS Examples

GET customerservice/customers/1 HTTP/1.1 HTTP/1.1 200 OK

<?xml version=”1.0″?>
<customer>
<id>1</id>
</customer>

Would have an additional link paramater to show its source –

<?xml version=”1.0″?>
<customer>
<id>1</id>
<link rel=”self” href=”http://localhost:8080/customerservice/customers/1″ />
</customer>

References

  • http://www.restapitutorial.com/httpstatuscodes.html
  • http://en.wikipedia.org/wiki/Representational_state_transfer
  • http://en.wikipedia.org/wiki/HATEOAS
  • http://docs.oracle.com/javaee/6/tutorial/doc/gijqy.html
  • https://www.javabullets.com/2015/01/15/apache-cxf-jax-rs/
  • https://github.com/spring-projects/spring-hateoas

@Named vs @ManagedBean

I was looking through some JSF controllers and it was a mix of @Named and @ManagedBean annotations. These annotations provide similar dependency injection, but there are important differences.

Containers

  • @ManagedBean – javax.faces.bean.ManagedBean – managed by JSF container
  • @Named – javax.faces.bean – CDI bean managed by application server

This means @Named beans are visible to the whole JEE container, while @ManagedBean are visible only to the JSF container. The visibility issue is covered in this table

Inject @Named @ManagedBean
@Named Y Y(*)
@ManagedBean N Y(*)

* – only if scope of injected bean is broader

One problem is that @Named requires that you use a JEE enabled container – so you have to use TomEE instead of Tomcat.

Scope

A further problem in earlier CDI versions was that there was no CDI equivalent of @ViewScoped. This has now been resolve with @javax.faces.view.ViewScope.

You also need to be very careful with mixing JSF and CDI as they use different packages – javax.faces.bean vs javax.enterprise.context.

So what approach to use?

This is a non-question as from JSF2.3 onwards @ManagedBean is being phased out and the recommended approach is @Named. It is also important not to mix CDI with JSP scopes

However there are circumstances when I would still use @ManagedBean at present –

  • Existing Code is using @ManagedBean – I would stick with @ManagedBean until a migration path is determined
  • Web Container – You just want to use a web container – then sticking with JSF ManagedBeans would be easier

Reference

http://germanescobar.net/2010/04/4-areas-of-possible-confusion-in-jee6.html