Search This Blog

Friday, January 28, 2011

JSF 2 with Spring 3 - protection with Spring Security (part 2 of 2)

Requirements:
  • a working example of JSF 2.0 application with Spring Framework integrated (can be found here)
You will learn:
  • how to use Spring Security Framework in order to protect web application
From the previous post we know what Spring Framework is, and what advantages it gives us when used in web application. Business logic managed by Spring is not the only one advantage coming from Spring - we can use Spring's embedded mechanisms to secure our web application. This post will show the basic usage of Spring Security for securing our sample JSF 2.0 webapp. 
What parts of our application will be protected? Consider those scenarios:
1. Only registered user (or page administrator) can see details of a selected bike.
2. Only page administrator can add a new bike to the shop offer.

We need two user roles which will determine the privilleges which user has: registered users role and admin users role. Moreover, for the scenario 2, we have to add a new function: adding new bike. For this function we will create a page addBike.xhtml and a JSF managed bean for that page, named addBike.java.

addBike.xhtml source code is shown below:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<ui:composition template="../shopTemplate.xhtml">

<ui:define name="content">
<h:form>
<h:outputText value="#{msg['bikes.list.name']}: "/><h:inputText value="#{addBike.name}" /><br/>
<h:outputText value="#{msg['bikes.list.price']}: "/><h:inputText value="#{addBike.price}" /><br/>
<h:outputText value="#{msg['bikes.list.discountprice']}: "/><h:inputText value="#{addBike.discountPrice}" /><br/>
<h:outputText value="#{msg['bikes.list.description']}: "/><h:inputText value="#{addBike.description}" /><br/>
<h:commandButton action="#{addBike.addNewBike}" value="#{msg['bikes.add.button']}" />
</h:form>
</ui:define>

</ui:composition>
</html>
Nothing special - standard form for entering the data.
addBike.java source code is also simple:
package com.jsfsample.managedbeans;
...
@ManagedBean(name="addBike")
@SessionScoped
public class AddBike implements Serializable {

private static final long serialVersionUID = -2155913853431899821L;


@ManagedProperty("#{bikeDataProvider}")
private BikeDataProvider bikeDataProvider; // injected Spring defined service for bikes

private String name;
private String description;
private String price;
private String discountPrice;
private Integer categoryId;

public String addNewBike(){

Bike newBike = new Bike();
newBike.setName(getName());
newBike.setDescription(getDescription());
newBike.setPrice(Integer.parseInt(getPrice()));
newBike.setDiscountPrice(Integer.parseInt(getDiscountPrice()));
newBike.setCategory(categoryId);

// save new bike and return to the shop
bikeDataProvider.add(newBike);
return "/bikesShop.xhtml";
};
...
}
Please note that we use here BikeDataProvider.java class, which is Spring managed service, the same we used for loading bikes list and loading a certain bike details in previous post.

Now it is time for protected parts of application. I will show two ways of protecting webapp: protecting resources (like access to certain page) and protecting business logic methods execution. Scenario 1 will be an example of protecting business logic and scenario 2 will be an example of protecting resources.
When user tries to access the protected area (resource or invoke protected method), application will check user roles and based on them will decide if let the user go further or force him to log in. Log in - that's right - a login page will be displayed where user will enter his credentials. Based on them Spring Security will decide what roles user has and depends on assigned roles further action will be continued or not. Let's modify our application to use Spring Security:

Step 1. Modify configuration files:
applicationContext.xml source:
...
<!--
resource security
-->
<sec:http auto-config="true" access-denied-page="/faces/accessDenied.xhtml">
<sec:form-login login-page="/faces/login.xhtml" />
<sec:intercept-url pattern="/faces/admin/**" access="ROLE_ADMIN" />
</sec:http>
<!--
business logic (method) security
-->
<sec:global-method-security
secured-annotations="enabled" jsr250-annotations="enabled" >
</sec:global-method-security>
<!--
manager responsible for loading user account with assigned roles
-->
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider
user-service-ref="userDetailsService" />
</sec:authentication-manager>
...
Access-denied-page is invoked when user is authenticated but is not authorized to access protected resources. When user is not authenticated, he is moved into form-login instead of access-denied-page.
web.xml source:
...
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
Step 2. Additional pages: login.xhtml and accessDenied.xhtml.
accessDenied.xhtml is simple page displaying only a message saying that the user is authenticated but still is not authorized to go further.
login.xhtml is a simple page with login form where user enters his credentials (login and password). The more interesting part is corresponding managed bean LoginBean.java which uses a Spring service for authenticating users:
package com.jsfsample.managedbeans;
...
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {
private static final long serialVersionUID = 1L;

private String login;
private String password;

@ManagedProperty(value = "#{authenticationService}")
private AuthenticationService authenticationService; // injected Spring defined service for bikes


public String login() {

boolean success = authenticationService.login(login, password);

if (success){
return "bikesShop.xhtml"; // return to application but being logged now
}
else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login or password incorrect."));
return "login.xhtml";
}
}
...
}
When login was successful and user is authenticated, he is moved to the shop. If not a proper message is displayed and user can re-enter his credentials or go back to the shop without login. Let's look inside AuthenticationService.java class which is a service deciding if user is authenticated or not.

Step 3. AuthenticationService implementation:
package com.jsfsample.application.impl;
...
@Service("authenticationService")
public class AuthenticationServiceImpl implements com.jsfsample.application.AuthenticationService {


@Resource(name = "authenticationManager")
private AuthenticationManager authenticationManager; // specific for Spring Security

@Override
public boolean login(String username, String password) {
try {
Authentication authenticate = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(
username, password));
if (authenticate.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(
authenticate);
return true;
}
} catch (AuthenticationException e) {
}
return false;
}
...
}
This Spring managed service uses internally a class AuthenticationManager, which comes from Spring Security and was defined as a manager in applicationContext.xml file:
...
<!--
manager responsible for loading user account with assigned roles
-->
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider
user-service-ref="userDetailsService" />
</sec:authentication-manager>
...
Note that we do not explicit define AuthenticationManager! It is a ready to use object. But AuthenticationManager has helper service named userDetailService defined in applicationContext.xml file - this service must be written by our own.

Step 4. Implementation of userDetailService
userDetailsService source code is shown below:
package com.jsfsample.application.impl;
...
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

private HashMap users = new HashMap();

@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException{

org.springframework.security.core.userdetails.User user = users.get(username);

if (user == null) {
throw new UsernameNotFoundException("UserAccount for name \""
+ username + "\" not found.");
}

return user;
}

@PostConstruct
public void init() {

// sample roles
Collection adminAuthorities = new ArrayList();
adminAuthorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

Collection userAuthorities = new ArrayList();
userAuthorities.add(new GrantedAuthorityImpl("ROLE_REGISTERED"));

boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;

// sample users with roles set
users.put("admin", new org.springframework.security.core.userdetails.User("admin", "admin", enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, adminAuthorities));

users.put("user", new org.springframework.security.core.userdetails.User("user", "user", enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, userAuthorities));
}
}
We have here a Spring Security specific objects representing users and roles. In the init() method I created some mocked data two roles representing page administrators and registered users - ROLE_ADMIN and ROLE_REGISTERED. For each role I created a single account: admin (password: admin) for the ROLE_ADMIN and user (password: user) for the ROLE_REGISTERED. That's all - it is time to protect applicartion.

Step 5. Protecting application.
5 a) Scenario 1: protecting business logic. We have to protect invoking a method which allows to see bike details. This method is placed inside BikeDataProvider.java service class. In order to protect the method we have to add an annotation defining roles allowed to execute this method:
package com.jsfsample.services;
...
public interface BikeDataProvider {
...

@RolesAllowed({"ROLE_ADMIN","ROLE_REGISTERED"})
public abstract Bike getBikeById(Integer id);

public abstract void add(Bike newBike);
}
This simply means that only registered users or admin users can see bike details. 
Why we do not protect the add(...) method? Because we protect the whole page access where this method is executed - of course in addition we can also protect this method by annotating it with @RolesAllowed({"ROLE_ADMIN"}).
5 b) Scenario 2: protecting resource. According to rules of protecting resources defined in applicationContext.xml, we protect all resources which are located inside /admin directory. So we have to create a directory /admin under /WebContent directory and move addBike.xhtml page there. It should look like this:

Note: there is a little trick in the protecting resources like pages in JSF. Spring Security tries to match exact URL address to apply the rule. But in JSF there is a "old URL" issue - after navigtation from page A to page B, URL address in browser still points to page A. In order to make the rule working we have to force the browser to show the current URL instead of old one. It is done by adding a special command into the navigation string returning a page for adding a bike:
public String showForm(){  
...
return "/admin/addBike.xhtml?faces-redirect=true";
}

That's all about Spring Security in our sample application. 
How to test it? After deploying application on the server and starting the server, we have to open a browser and type in URL:

http://localhost:8080/JSF2FeaturesSpring

Then try to display some bike details. When promped for login, enter credentials: user, user and try again. Then try to add a new bike - You should see access denied page. The close the application and clean the browser cache and try the same with the user admin, admin.

-------------------------------------------
Download source files:

Note: make sure that Java, Eclipse and Tomcat are properly installed and configured for running the project (additional configuration may be required if different directories are used).

Eclipse complete sample project is here (with all required libraries). The sample project is a ready to run application which contains all described Spring Security issues in this post. You can also download a war file located here (just copy it inside webapps folder in Your Tomcat and start Tomcat with the script startup.bat)

Sunday, January 23, 2011

Hot Busy Philipps from Cougar Town

Busy Philipps was born in 1979 in June. She was on the television show Dawson's Creek, and she even was in Freaks and Geeks. She is pretty hot, and she is most known now for her role in Cougar Town with Kourtney Kox. I believe thats how you spell her name. Anyways here are some hot pictures and wallpapers that I found for Busy Philipps...




Friday, January 21, 2011

Foto Seksi Julia Perez District Cafe Makassar | Sparkling with Jupe

Foto Seksi Julia Perez District Cafe Makassar - Jupe mantan calon bupati pacitan yang sering tersandung dengan kasus foto hot julia perez kembali tampil seronok dan berani dengan menggunakan busana yang seksi di D'District Cafe Makassar dalam acara Sparkling with Jupe.

Jupe yang tampil seksi membius clubber Makassar dalam acara bertajuk "Sparkling With Jupe". Jupe tampil total dengan busana

Sunday, January 16, 2011

Teresa Scanlan Miss USA 2011 Biography

Teresa Scanlan Miss USA 2011 Biography - Miss USA pageant in las Vegas Nevada USA on 15 january 2011 goes to Teresa Scanlan a 17 years old girls from Nebraska. teresa scanlan also made the records as the youngest winner of Miss USA pageant. so who is teresa scanlan? here's a little biography of Teresa Scanlan.


Teresa Scanlan was become the youngest winner of Miss USA. At 17, Scanlan is the

Monday, January 10, 2011

Pernikahan Irwansyah Zaskia Sungkar

Pernikahan Irwansyah Zaskia Sungkar - Pasangan Selebritis Irwansyah dan Zaskia Sungkar akan melangsungkan pernikahan mereka pada 15 januari 2011. Irwansyah akan menikahi putri Mark Sungkar dan Fanny Bauty di Masjid Albina, Gelora Bung Karno, Senayan, pada Sabtu, 15 Januari 2011.

Ketua KUA Tanah Abang, H Asyrof Syahroni, saat ditemui Okezone di kantornya di jalan Mutiara no.2, Karet Tengsin,

Saturday, January 8, 2011

Ashanty Siddik Profil Rekan Duet Anang

Ashanty Siddik Profil Rekan Duet Anang - Siapa itu Ashanty? Berikut adalah profil dari Ashanty calon rekan duet anang yang baru menggantikan Syahrini yang pernah menjadi hits di 2010 sehingga banyak muncul foto mesra anang syahrini. akankah duet anang ashanty akan sesukses ansani? Simak profil dan biografi singkat Ashanty Berikut kumpulan foto terbaru Ashanty dan foto Seksi Ashanty.

Ashanty

Friday, January 7, 2011

Koleksi SMS Valentine 2011 Kado Valentine Romantis

Koleksi SMS Valentine 2011 Kado Valentine Romantis, 14 Februari, Hari yang sangat kunanti, Murni cinta tlah bersemi. 1 Bulan lagi kita akan bertemu dengan hari kasih sayang alias hari valentine. sudahkah anda mempersiapkan Koleksi SMS Valentine 2011 yang romantis untuk kado valentine kepada pasangan anda? Sebenarnya ada banyak jenis kado valentine yang bisa anda berikan kepada kekasih saat hari

Tuesday, January 4, 2011

Foto Aida Saskia Mandi

Foto Aida Saskia Mandi, Beredar lagi foto hot aida saskia mandi di internet, diduga ini merupakan salah satu scene film yang dilakoni oleh aida saskia yang pernah bermasalah dengan KH Zainudin MZ. entah apakah foto aida saskia mandi ini benar adalah aida atau hanya mirip saja.

Foto Hot Aida Saskia Mandi Download, dengar dengar ada kasus foto hot lagi yang beredar, kali ini dari aida saskia yang

Monday, January 3, 2011

Christina Milian Shakes Her Ass at the Club

Christina Milan is an up and coming famous female actress. She has been recently spotted at a club shakin' what her mama gave her. I just thought I would share some of these hot pictures with some of my loyal subscribers...


El Triunfo del Amor Capitulo 50

El Triunfo del Amor Capitulo 50, Watch el triunfo del amor capitulo 50, well we don't have the full trailer of this capitulo, but you can read the recap of the 50th capitulo of El Triunfo del Amor below.

This 50 Capitulo of El Triunfo del Amor is told about Linda (Dorismar) who traveled to the beach with Osvaldo. Apart tells the story of Osvaldo and Linda, at Triunfo del Amor Capitulo 50 also

Chyntiara Alona Released her Hijab

Chyntiara Alona Released her Hijab, Chyntiara alona the famous models and actress admits that she released her hijab, Chyntiara claims began closing off one of her private parts this year. However, I'm a model and movie player, it does not mean she again appeared bold as before wearing hijab

"I want to be myself and a career. So, still not used to wearing the hijab is, "said the owner's full

Sunday, January 2, 2011

Tracing the regal existence of ‘Miss Universe’






‘Miss Universe’ has been one of the most esteemed beauty contests in the world for past the 50 years. The renowned pageant, as an annual international competition, has been showcasing culture, talent and beauty with entries from more than 80 countries on the map. Organised by the ‘Miss Universe Organization’, the contest stands a rival to ‘Miss World’ and ‘Miss Earth’ crowns.

Emergence of the pageant

The prestigious contest evolved in 1951 by a California clothing company ‘Pacific Mills’. The pageant became part of ‘Kayser-Roth’ and the ‘Gulf and Western Industries’, before being taken over by ‘Donald Trump’ in 1996. The ‘Miss Universe Pageant’ amended its title from what it was previously known as - ‘Miss America Pageant’, when Yolande Betbeze, the winner of ‘Miss America 1951’ refused to pose in a swimsuit from its major sponsor, Catalina swimwear. Retaliating to this, the brand manufacturer ‘Pacific Mills’ withdrew itself from ‘Miss America’, and established the ‘Miss Universe’ and ‘Miss USA’ contests.

From 1952 to 1971, the main pageant ‘Miss Universe’ was successfully held consecutively, in the continental US. In the present scenario, MUP is held over a two-week period in every May and July, as compared to 1970s to 1990s, when the contest used to be stretched over a month long period.

Variations in the Contest Format

In the few initial years of the pageant, the semi-finalists used to be announced instantly after the preliminary competition. The arrangement was such that the runners-up and winners were announced from the short listed 15 semi-finalists, after the preliminary round. But in 1964, the top 15 was reduced to top 10, and the format incorporated a round of interview, whereby the winner and runners-up were selected from the 10 finalists.

But a year later, in 1965, the pageant adapted ‘cut to 5 finalists’ concept, in accordance to which, the semi-finalists had to compete once again in ‘evening gown and swimsuit’, post the preliminary round, to make it to the final 5.

In 1969, the format introduced ‘a final question’ concept, whereby one last question was posed to the top 5 selected contestants. But earlier this was an on-and-off feature of the pageant. While in 1990, the concept became a norm, and it was mandatory for the final contestants to answer ‘a final question’ put up to them.

The year 1990 brought a lot many variations in the competition format. Now, instead of the count reducing from 10 semi-finalists to 5, it got down to 6. Each contestant was then made to randomly select a judge to ask her a question in the finale of the contest.

Later that year, the contest underwent frequent changes, when the finalist count was reduced to 3, and after that in 1998, it increased to 5.

Surprisingly, in 2000, the interview round of the semi-finals was dropped and the contestants once again, as in the early days of the pageant, began to compete only in swimsuit and gowns.

Two years back, in 2006, Miss Universe contest settled on the announcement of 20 short-listed semi-finalists, to further compete in the swimsuit. After this round, the selected contestants were brought down to 10, those for competing in the evening gown. This round allowed the final 5 to be declared and initiated the ladies towards the final fight in the ‘final question’ or ‘interview’ round. At the end of this final stroke, the runners-up were announced and the winner was crowned by the outgoing queen.

But in 2007, the format again underwent some changes with the top 15 in the swimsuit round; thereafter the 10 selected ones moved on to the evening gown round, where 5 faced elimination. The final 5 answered the final question, allowing the judging panel to decide on the ultimate winner of the crown. Since then, till date, the trend has been on the similar lines – graceful and exciting, leaving no room for foul play.

A majestic crown to take you places

The crowned beauty is awarded a one-year contract with the Miss Universe Organization, with opportunity for going across borders to spread social awareness about the control of diseases, peace. Since the time Donald Trump took over the pageant, the winner is even awarded a Trump Tower apartment in NYC for use during her reign. Along with the main crown, special awards are also awarded to the winners in the category of the Best National Costume, Miss Photogenic, and Miss Congeniality.

Miss Universe has now turned out to be the biggest glam show, where the most beautiful women from across the world compete with each other to earn pride and honour not just for themselves, but also for their countries.


- Bhavna Khullar

Watch Secret Garden Ep 14 Eng Sub Online

Watch Secret Garden Ep 14 Eng Sub Online, Do you love a korean drama? well Secret garden was one of the favorite korean drama today, so what's the main plot of this secret garden drama? The drama tells the story of Kim Joo Won (Hyun Bin), a seemingly perfect man yet with certain arrogance and childishness in him, and Gil Ra Im (Ha Ji Won), a stuntwoman whose beauty and body are the object of envy