Spring security 로그인 처리 (2)

북마크 추가


 

1.UserInfo.java

-> user의 정보를 담을 모델 구현

 

package com.demo.auth;

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

 

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;

 

 

public class UserInfo implements UserDetails

{

 

    private static final long serialVersionUID = 1L;

    private String username;

    private String name;

    private String password;

    private String memSq;

    private String img;

    private String role;

   

    public Collection<? extends GrantedAuthority> getAuthorities()

    {

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();    

        String str= getRole();        // Role이 ADMIN일 경우 ROLE_ADMIN 권한 부여 

       if(str!=""&&str!=null){

      if(str.equals("ADMIN")){

          

          authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

           }

      

       }else{

      authorities.add(new SimpleGrantedAuthority("ROLE_USER")); // 아닐경우 일반유저 권한 부여

       }

      

        return authorities;

    }

    

    public void setPassword(String password)

    {

        this.password = password;

    }

    

    public String getPassword()

    {

        return password;

    }

    

    public void setUsername(String username)

    {

        this.username = username;

    }

    

    public String getUsername() 

    {

        return username;

    }

    

    public boolean isAccountNonExpired() 

    {

        return true;

    }

    

    public boolean isAccountNonLocked() 

    { 

        return true;

    }

    

    public boolean isCredentialsNonExpired() 

    {

        return true;

    }

    

    public boolean isEnabled() 

    {

        return true;

    }

 

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

public String getMemSq() {

return memSq;

}

 

public void setMemSq(String memSq) {

this.memSq = memSq;

}

 

public String getImg() {

return img;

}

 

public void setImg(String img) {

this.img = img;

}

 

public String getRole() {

return role;

}

 

public void setRole(String role) {

this.role = role;

}

}

 


 

 

2. DAO 인터페이스, DAO 구현 


UserInfoDAO.java

 

package com.demo.auth;

 

public interface UserInfoDAO {

public UserInfo getUser(String id);

}

 

UserInfoDAOService.java

 

쿼리를 실행하여 유저정보 받아옴

 

package com.demo.auth;

 

import org.apache.ibatis.session.SqlSession;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

 

 

 

@Repository

public class UserInfoDAOService implements UserInfoDAO {

@Autowired

private SqlSession sqlSession;

@Override

public UserInfo getUser(String id) {

// TODO Auto-generated method stub

UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);

UserInfo userInfo = new UserInfo();

userInfo = userInfoMapper.getUser(id);

return userInfo;

}

 

}

 

3.UserService 구현 - UserService.java

- UserDetailsService를 구현한다

 

package com.demo.auth;

 

import org.springframework.beans.factory.annotation.Autowired;

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.Controller;

 

 

 

public class UserService implements UserDetailsService

{

@Autowired

UserInfoDAOService userInfoDAOService;

    

public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException

    {

       

        System.out.println(id);

        UserInfo userInfo = new UserInfo();

               

        userInfo = userInfoDAOService.getUser(id);

        UserInfo user = new UserInfo();

        

        user .setUsername(userInfo.getUsername());

        user .setPassword(userInfo.getPassword());

        user .setName(userInfo.getName());

        user .setMemSq(userInfo.getMemSq());

        user .setImg(userInfo.getImg());

        user .setRole(userInfo.getRole());

        return user ;

    }

} 

 

4. LoginSuccessHandler.java


package com.demo.auth;

 

import java.io.IOException;

import java.io.OutputStream;

import java.util.HashMap;

import java.util.Map;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

 

import org.codehaus.jackson.map.ObjectMapper;

import org.springframework.security.core.Authentication;

import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import org.springframework.security.web.savedrequest.HttpSessionRequestCache;

import org.springframework.security.web.savedrequest.RequestCache;

import org.springframework.security.web.savedrequest.SavedRequest;

 

import com.mysql.jdbc.interceptors.SessionAssociationInterceptor;

 

 

public class LoginSuccessHandler implements AuthenticationSuccessHandler

{

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException

    {

    ObjectMapper om = new ObjectMapper();

  Map<String, Object> map = new HashMap<String, Object>();

map.put("returnUrl", getReturnUrl(request, response));   // 로그인 요청하기전 페이지 주소

UserInfo user = (UserInfo)auth.getPrincipal();

map.put("user",user);

System.out.println("auth::"+auth.getAuthorities());

HttpSession session = request.getSession(true);

session.setAttribute("name", user.getName());

session.setAttribute("memSq", user.getMemSq()); // 세션에 담아서 원래 페이지로 보냄

String jsonString = om.writeValueAsString(map);

OutputStream out = response.getOutputStream();

out.write(jsonString.getBytes());

}

private String getReturnUrl(HttpServletRequest request, HttpServletResponse response) {

RequestCache requestCache = new HttpSessionRequestCache();

SavedRequest savedRequest = requestCache.getRequest(request, response);

if (savedRequest == null) {

return request.getSession().getServletContext().getContextPath();

}

return savedRequest.getRedirectUrl();

}

 

 

LoginFailureHandler.java


package com.demo.auth;

 

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.web.authentication.AuthenticationFailureHandler;

 

 

public class LoginFailureHandler implements AuthenticationFailureHandler

{

    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException auth) throws IOException, ServletException

    {

     response.sendRedirect("/login");      // 로그인 페이지로 리다이렉트

    }

}

 

 

 

 

[참조]http://preludeb.egloos.com/viewer/4738521​ - Spring Security를 이용한 인증 처리 

 

 

 

AD
통관알리미
2014-07-15 21:52
SHARE