본문 바로가기

백엔드/Spring

Spring Security 설정.

- Spring-security-3.1.0.RC2로 작업.
- 일반적인 Spring 설정은 제외.

web.xml
	
	
		contextConfigLocation
		
			 classpath*:/applicationContext*.xml
		
	
...
...
	
		springSecurityFilterChain
		org.springframework.web.filter.DelegatingFilterProxy
	

	
		springSecurityFilterChain
		/*
	


applicationContext-security.xml



	
	

	
		
		
     	
		
        
		
		
		
		
		
		
		
		
		
		
        
		
		
	
	
		
	
	
	
	
	

	
	
	
	

	
		
        	
	

	
		
		
	

	
		
		
	

	
		
		
		
	
	


MemberManager.java
public interface MemberManager extends UserDetailsService{
	// 구현하고픈 메서드
}

MemberManagerImpl.java
@Service("memberMgr")
public class MemberManagerImpl extends AbstractGenericManager implements MemberManager{

	@Autowired
	// DB와 통신할 DAO
	MemberDao memberDao;
	
	@Override
	// 로그인 메서드
	public Member login(String memberId, String memberPw){
		Member member = (Member) loadUserByUsername(memberId);
		if(member != null){
			if(memberPw.equals(member.getPasswd())) {
				member.setName(member.getAuth().get(0).getAuthority());
				member.setAuthenticated(true);
				return member;
			}
		}
		return null;
	}
		
	@Override
	// UserDetailService 구현체
	public UserDetails loadUserByUsername(String adminId) throws UsernameNotFoundException {
		// Parameters는 커스텀 클래스임.
		Parameters params = new Parameters();
		params.put("p_id", adminId);
		List list = null;
		try{
			// DAO를 통해 쿼리를 날리고 결과를 받아오는 것.
			list = memberDao.list(params);
			// 유저가 없을경우.
			if(list.size() == 0 || list.size() > 1){
				return null;
			}
		}catch(Exception e){
			StringBuilder logMsg = (new StringBuilder("Username(")).append(adminId).append(") access exception!");
			logger.error(logMsg.toString(), e);
            throw new UsernameNotFoundException(logMsg.toString(), e);
		}
		return list.get(0);
	}
	
	
	public Collection getAuthorities(Member member) {
		List authList = new ArrayList();
		Role role = member.getRole();
		authList.add(new SimpleGrantedAuthority(role.getRoleName()));
        return authList;
	}

}

Member와 SecurityObject (인증을 저장하고 있을 JPA Entity)
인증 정보를 가지고 있을 객체는 몇가지 객체를 구현해야하는데 이에 필요한 filed가 존재해야만 한다.
JPA에서는 @Entity가 붙은 클래스는 DB와 동기화를 하기 때문에 DB에 없는 filed를 넣을시 에러가 난다.
때문에 SecurityObject를 만들어서 객체 구현에 필요한 filed를 가지게하고
인증 정보를 가지고 있을 객체가 SecurityObject를 상속하는 방식으로 처리 했다.

SecurityObject.java
public class SecurityObject implements Serializable{

	private static final long serialVersionUID = 8359426924640562032L;
	
	protected boolean accountNonExpired;
	protected boolean accountNonLocked;
	protected boolean credentialsNonExpired;
	protected boolean accepted;
	
	protected String name;
	protected Object credentials;
	protected Object details;
	protected Object principal;
	protected boolean authenticated;

}


인증 정보를 가지고 있을 Member 객체
/**
 * The persistent class for the members database table.
 * 
 */
@Entity
@Table(name="members")
public class Member extends com.score.www.common.domain.SecurityObject implements Serializable, UserDetails, Authentication {
	private static final long serialVersionUID = 1L;

	// 이런 저런 filed, ex) name, id, nickname 등

	//bi-directional many-to-one association to Role
	// ROLE과 Member 는 1:N의 관계로 설정했고 이를 JPA로 구현한 것.
	@ManyToOne
	@JoinColumn(name="ROLE_SEQ")
	private Role role;

	public Member() {
	}

	// 일반 filed의 getter/setter

	public Role getRole() {
		return this.role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
	
	@Override
	public Object getCredentials() {
		return credentials;
	}

	@Override
	public Object getDetails() {
		return details;
	}

	@Override
	public Object getPrincipal() {
		return principal;
	}
	
	public void setPrincipal(Object principal){
		this.principal = principal;
	}

	@Override
	public boolean isAuthenticated() {
		return authenticated;
	}

	@Override
	public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
		this.authenticated = isAuthenticated;
	}

	@SuppressWarnings("unchecked")
	public List getAuth(){
		return (List) this.getAuthorities();
	}
	
	@Override
	public Collection getAuthorities() {
		List list = new ArrayList();
		list.add(new SimpleGrantedAuthority(role.getRoleName()));
		return list;
	}

	@Override
	public String getPassword() {
		return this.passwd;
	}

	@Override
	public String getUsername() {
		return this.memberName;
	}

	@Override
	public boolean isAccountNonExpired() {
		return accountNonExpired;
	}

	@Override
	public boolean isAccountNonLocked() {
		return accountNonLocked;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return credentialsNonExpired;
	}

	@Override
	public boolean isEnabled() {
		return super.accepted;
	}

	@Override
	public String getName() {
		return this.name;
	}

	public void setName(String authority) {
		this.name = authority;
	}
	
}