Download Spring Security
Spring Security 3.1.0.RELEASE – http://www.springsource.org/spring-security
Maven Artifacts
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
Database
CREATE TABLE `springsec`.`user` (
`username` varchar(255) NOT NULL,
`active` bit(1) NOT NULL,
`familyName` varchar(255) DEFAULT NULL,
`firstName` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into user (username, password, firstName, familyName, active) VALUES(‘user’, ‘password’,'Administrator’,'Family Name’,true);
CREATE TABLE `springsec`.`role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
insert into role (id, name) VALUES(1,’ROLE_ADMIN’);
CREATE TABLE `springsec`.`user_role` (
`user_username` varchar(255) NOT NULL,
`roles_id` bigint(20) NOT NULL,
KEY `FK143BF46A4903B745` (`user_username`),
KEY `FK143BF46A45FF7703` (`roles_id`),
CONSTRAINT `FK143BF46A45FF7703` FOREIGN KEY (`roles_id`) REFERENCES `role` (`id`),
CONSTRAINT `FK143BF46A4903B745` FOREIGN KEY (`user_username`) REFERENCES `user` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO user_role (user_username, roles_id) VALUES(‘user’,1);
User.java
A entidade User implementa a interface UserDetails
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
@Entity
@Table(name="user")
public class User implements Serializable, UserDetails {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
private String username;
private String password;
private String firstName;
private String familyName;
private boolean active;
@ManyToMany(fetch=FetchType.EAGER)
private List<Role> roles;
@Transient
public Collection<GrantedAuthority> getAuthorities() {
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
for (Role role : roles) {
result.add(new GrantedAuthorityImpl(role.getName()));
}
return result;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Transient
public boolean isAccountNonExpired() {
return true;
}
@Transient
public boolean isAccountNonLocked() {
return true;
}
@Transient
public boolean isCredentialsNonExpired() {
return true;
}
@Transient
public boolean isEnabled() {
return active;
}
public String getFirstName() {
return firstName;
}
// métodos getters e setters omitidos
// métodos hashcode e equals omitidos
}
ManagedBean:
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import demo.service.AuthenticationService;
@ManagedBean(name="loginMB")
@RequestScoped
public class LoginBean {
@ManagedProperty(value = "#{authenticationService}")
private AuthenticationService authenticationService;
private String userName;
private String password;
public String login() {
boolean success = authenticationService.login(userName, password);
if (!success) {
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Login ou senha inválidos");
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
return "falhaLogin";
}
return "sucessoLogin";
}
public String logout() {
authenticationService.logout();
return "login";
}
public String getUsuarioLogado(){
return authenticationService.getUsuarioLogado().getUsername();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setAuthenticationService(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
}
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import demo.model.User;
@Component("authenticationService")
public class AuthenticationService {
@Autowired
@Qualifier("authenticationManager")
private AuthenticationManager authenticationManager;
public boolean login(String username, String password) {
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Authentication authenticate = authenticationManager.authenticate(token);
if (authenticate.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authenticate);
return true;
}
}
catch (AuthenticationException e) {}
return false;
}
public void logout() {
SecurityContextHolder.getContext().setAuthentication(null);
invalidateSession();
}
public User getUsuarioLogado() {
return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
private void invalidateSession() {
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
session.invalidate();
}
}
A autenticação é feita pela interface UserDetailsService.
Criamos uma implementação de UserDetailsService e sobrescrevemos o método loadUserByUsername()
import javax.annotation.Resource;
import javax.persistence.NoResultException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import demo.dao.UserDao;
import demo.model.User;
@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Resource
private UserDao userDao;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails userReturn = findByUsername(username);
return userReturn;
}
private User findByUsername(String username) {
try{
User userRecuperado = userDao.pesquisarPorId(username);
if (userRecuperado == null) {
throw new NoResultException();
}
return userRecuperado;
}catch (NoResultException e) {
throw new UsernameNotFoundException("User not found");
}
}
}
<authentication-manager alias="authenticationManager" >
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>
And DAO…
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
@Entity
@Table(name=”user”)
public class User implements Serializable, UserDetails {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
private String username;
private String password;
private String firstName;
private String familyName;
private boolean active;
@ManyToMany(fetch=FetchType.EAGER)
private List<Role> roles;
@Transient
public Collection<GrantedAuthority> getAuthorities() {
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
for (Role role : roles) {
result.add(new GrantedAuthorityImpl(role.getName()));
}
return result;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Transient
public boolean isAccountNonExpired() {
return true;
}
@Transient
public boolean isAccountNonLocked() {
return true;
}
@Transient
public boolean isCredentialsNonExpired() {
return true;
}
@Transient
public boolean isEnabled() {
return active;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (active ? 1231 : 1237);
result = prime * result
+ ((familyName == null) ? 0 : familyName.hashCode());
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((password == null) ? 0 : password.hashCode());
result = prime * result + ((roles == null) ? 0 : roles.hashCode());
result = prime * result
+ ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (active != other.active)
return false;
if (familyName == null) {
if (other.familyName != null)
return false;
} else if (!familyName.equals(other.familyName))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (roles == null) {
if (other.roles != null)
return false;
} else if (!roles.equals(other.roles))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}