자바 단일 로그 인(SSO)구현

단일 로그 인(SSO):SSO 는 여러 응용 시스템 에서 사용자 가 한 번 만 로그 인하 면 서로 신뢰 하 는 모든 응용 시스템 에 접근 할 수 있 는 것 을 말한다.이것 은 이번 주요 로그 인 을 다른 응용 프로그램 에 비 추어 같은 사용자 의 로그 인 에 사용 할 수 있 는 메커니즘 을 포함한다.
SSO 의 실현 과정:

상기 도형 을 통 해 우 리 는 SSO 의 대체 적 인 실현 절 차 는 주로 로그 인 정 보 를 저장 하고 로그 인 정 보 를 검사 하 는 두 단계 로 나 뉜 다.
SSO 에 대해 서도 우 리 는 이 를 두 가지 유형 으로 나 눌 수 있다.같은 도 메 인 SSO 와 크로스 도 메 인 SSO;그 중에서 같은 도 메 인 SSO 는 완전히 같은 도 메 인 SSO 와 같은 부모 도 메 인 SSO 로 나 눌 수 있다.
1.똑 같은 도 메 인 SSO:도 메 인 이름 이 똑 같은 여러 응용 시스템 에서 단일 로그 인 을 실현 하 는 것 을 말 합 니 다.
그 실현 절 차 는 주로 초기 준비 작업,통합 로그 인 인 터 페 이 스 를 작성 하고 로그 인 검사 인 터 페 이 스 를 작성 하 며 인증 페이지 를 작성 하여 SSO 를 실현 하 는 것 으로 나 뉜 다.
통합 로그 인 인터페이스 작성:
로그 인 페이지 의 작성 은 주로 사용자 의 로그 인 정 보 를 입력 하 는데 사용자 이름,비밀번호,그리고 로그 인 페이지 의 주 소 를 포함한다.여러 개의 응용 시스템 이 존재 하기 때문에 사용 자 는 통합 로그 인 페이지 로그 인 에 성공 한 후에 시스템 은 사용자 가 방문 하고 자 하 는 시스템 페이지 가 어떤 시스템 페이지 인지 알 아야 한다.이 럴 때 사용자 가 처음 방문 한 주 소 를 기록 하고 사용자 가 로그 인 에 성공 하면 바로 이 페이지 를 뛰 어 넘 을 수 있다.

<body>
    <center>
        <h1>   </h1>
        <form action="/sso/doLogin.action" method="POST">
            <span>   :</span><input type="text" name="username" />
            <span>  :</span><input type="text" name="password" />
            //         url  
            <input type="hidden" name="gotoUrl" value="${gotoUrl}" />
            <input type="submit" />
        </form>
    </center>
</body>
로그 인 방법의 작성:새 쿠키 가 필요 합 니 다.사용자 의 정 보 를 쿠키 에 저장 하고 쿠키 의 경 로 를 지정 합 니 다.완전히 같은 도 메 인 이기 때문에 쿠키 의 주 소 는("/")로 간략하게 쓸 수 있 습 니 다.여기 서 쿠키 의 경 로 를 설정 해 야 합 니 다.설정 하지 않 으 면 쿠키 의 경 로 는 현재 도 메 인 이름 의 맨 위 에 있 지 않 습 니 다.이 경 로 는 현재 도 메 인의 다른 경로 에서 이 쿠키 를 찾 을 수 없습니다.해결 방법 은 쿠키 를 현재 도 메 인의 맨 위 에 설정 하 는 것 입 니 다.이렇게 하면 현재 필드 의 모든 응용 프로그램 을 볼 수 있 습 니 다.

public String doLogin(){
        //  Cookie
        Cookie cookie = new Cookie("ssocookie","sso");
        //  Cookie  
        cookie.setPath("/");
        HttpServletResponse response = ServletActionContext.getResponse();
        response.addCookie(cookie);
        return "success";
 }

로그 인 검사 인터페이스의 작성:보통 SSO 로그 인 인터페이스 검 사 는 로그 인 차단기 에 놓 여 있 습 니 다.사용자 가 특정한 시스템 에 접근 하려 고 할 때 로그 인 차단 기 는 로그 인 페이지 를 통일 적 으로 바 꾸 고 사용자 가 로그 인 정 보 를 작성 하면 로그 인 검 사 를 합 니 다.

//cookie  (          )
    public static boolean checkCookie(HttpServletRequst request){
        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookies cookie:cookies){
                if(cookie.getName().equals("ssocookie")
                        &&cookie.getValue().equals("sso")){
                    return true;
                }
            }
        }
        return false;
  }
테스트 홈 페이지 작성

public String main(){
        HttpServletRequst request = ServletActionContext.getRequst();
        if(SSOCheck.checkCookie(request)){
            //    ,        ......
            return "success";
        }
        //    ,         ,     ,       
        gotoUrl="/demo1/main.action";
        return "login";
 }

마지막 으로 struts 2 프로필 도 있 습 니 다.

<struts>
    <package name="sso" namespace="/sso" extends="struts-default">
        <action name="doLogin" class="com.xm.controllerAction.SSOAction" method="doLogin">
       <!--        ,       ,               -->  
            <result name="success" type="redirect">${gotoUrl}</result>
        </action>
    </package>
    
    <package name="demo1" namespace="/demo1" extends="struts-default">
        <action name="main" class="com.xm.controllerAction.Demo1Action" method="main">
            <result name="success">/success1.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
    </package>
    <package name="demo2" namespace="/demo2" extends="struts-default">
        <action name="main" class="com.xm.controllerAction.Demo2Action" method="main">
            <result name="success">/success2.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
    </package>
</struts>
2.같은 부모 도 메 인 SSO:부모 도 메 인 이름 이 같은 응용 시스템 에서 SSO 를 실현 하 는 것 을 말한다.
그 실현 절 차 는 상기 와 완전히 같은 도 메 인 SSO 와 같다.
도 메 인 이름 검사 중:http://check.x.com
테스트 페이지 도 메 인 이름:http://demo1.x.com와http://demo2.x.com
통합 로그 인 인터페이스 작성:
코드 구현 은 도 메 인 SSO 와 거의 일치 하지만 제출 경 로 를 설정 할 때 2 급 도 메 인 이름 이 다 르 기 때문에 상대 경로 로 쓸 수 없고 절대 경로 주소 로 써 야 합 니 다.

<body>
    <center>
        <h1>   </h1>
     //             ,       
        <form action="http://check.x.com/sso/doLogin.action" method="POST">
            <span>   :</span><input type="text" name="username" />
            <span>  :</span><input type="text" name="password" />
            //         url  
            <input type="hidden" name="gotoUrl" value="${gotoUrl}" />
            <input type="submit" />
        </form>
    </center>
</body>
로그 인 방법:쿠키 경 로 를 설정 할 때 변화 가 있 습 니 다.마찬가지 로 현재 두 개의 부모 도 메 인 응용 시스템 이 이 쿠키 를 볼 수 있 도록 이 쿠키 를 부모 도 메 인 아래 에 설정 해 야 합 니 다.이 도 메 인 아래 에 설정 하지 말 아야 도 메 인 이 다 르 지만 부모 도 메 인 이 같은 응용 에서 볼 수 있 는 이 쿠키 를 실현 할 수 있 습 니 다.

   public String doLogin(){
     boolean ok = SSOCheck.checkLogin(userName,passWord);
     if(ok){
          //  Cookie
          Cookie cookie = new Cookie("ssocookie","sso");
          //  Cookie   
          cookie.setDomain(".x.com");
          //  Cookie  
          cookie.setPath("/");
          HttpServletResponse response = ServletActionContext.getResponse();
          response.addCookie(cookie);
          return "success";
     }
  }

로그 인 검사 인터페이스:서로 다른 도 메 인 이 있 기 때문에 우 리 는 로그 인 에서 얻 은 쿠키 를 전문 적 인 검사 도 메 인 에서 검사 하 는 방법 으로 보 내야 합 니 다.그렇지 않 으 면 우 리 는 서로 다른 로그 인 페이지 에서 검 사 를 해 야 합 니 다.그러면 코드 가 매우 지루 합 니 다.

    private String cookieName;
    private String cookieValue;
    public String getCookieName() {
      return cookieName;
    }
    public void setCookieName(String cookieName) {
      this.cookieName = cookieName;
    }
    public String getCookieValue() {
      return cookieValue;
    }
    public void setCookieValue(String cookieValue) {
      this.cookieValue = cookieValue;
    }


   //             
    public void checkCookie() throws IOException{
        boolean ok=SSOCheck.checkCookie(cookieName,cookieValue);
        String result="0";
        if(ok){
            result="1";
        }
        HttpServletResponse response = ServletActionContext.getResponse();
        response.getWriter().print(result);
        response.getWriter().close();
    }


public static boolean checkCookie(String cookieName,String cookieValue){
        if(cookieName.equals("ssocookie")&&cookieValue.equals("sso")){
            return true;
        }
        return false;
    }
테스트 홈 페이지 작성

public String main(){
        HttpServletRequst request = ServletActionContext.getRequst();
     //  cookie
        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("ssocookie")){
            //         cookieName cookieValue
                    String result = Demo1Tool.doGet("http://check.x.com/so/checkCookie.action",
                            cookie.getName(),cookie.getValue());
                    if(result.equals("1")){
                        return "success";
                    }
                }
            }
        }
        //         ,     ,       
        gotoUrl="http://demo1.x.com/demo1/main.action";
        return "login";
}


public static String doGet(String url,String cookieName,String cookieValue){
        //     
        StringBuffer sb = new StringBuffer();
        HttpURLConnection httpURLConnection = null;
        try{
            //         
            URL urls = new URL(url+
                    "?cookieName="+cookieName+"&cookieValue="+cookieValue);
            //    
            httpURLConnection = (HttpURLConnection) urls.openConnection();
            //         
            httpURLConnection.setRequestMethod("GET");
            //    
            httpURLConnection.connect();
            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String temp = null;
            while((temp = br.readLine())!=null){
                sb.append(temp);
            }
            br.close();
            isr.close();
            in.close();
        } catch(IOException e){
            e.printStackTrace();
        } finally{
            if(httpURLConnection!=null){
                httpURLConnection.disconnect();
            }
        }
        return sb.toString();
}
struts 프로필

<struts>
    <package name="sso" namespace="/sso" extends="struts-default">
        <action name="doLogin" class="com.xm.controllerAction.SSOAction" method="doLogin">
            <result name="success" type="redirect">${gotoUrl}</result>
        </action>
        <action name="checkCookie" class="check.x.com.SSOAction" method="checkCookie">
        </action>
    </package>
    <package name="demo1" namespace="/demo1" extends="struts-default">
        <action name="main" class="demo1.x.com.Demo1Action" method="main">
            <result name="success">/success1.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
    </package>
    <package name="demo2" namespace="/demo2" extends="struts-default">
        <action name="main" class="demo2.x.com.Demo2Action" method="main">
            <result name="success">/success2.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
    </package>
</struts>
3.도 메 인 간 SSO:도 메 인 이름 이 완전히 다른 응용 프로그램 에서 SSO 를 실현 합 니 다.
그 실현 절 차 는 완전히 같은 도 메 인 SSO 와 같다.
도 메 인 이름 검사 중:http://www.x.com
테스트 페이지 도 메 인 이름:http://www.a.com화해시키다http://www.b.com
통합 로그 인 인터페이스 작성:

<body>
    <center>
        <h1>   </h1>
        //               ,            ,           cookie
        <form action="/${path}/doLogin.action" method="POST">
            <span>   :</span><input type="text" name="username" />
            <span>  :</span><input type="text" name="password" />
            //         url  
            <input type="hidden" name="gotoUrl" value="${gotoUrl}" />
            <input type="submit" />
        </form>
    </center>
</body>
로그 인 방법:

public String doLogin(){
        Map<String,String> map = new HashMap<String,String>();
        map.put("userName", userName);
        map.put("password", passWord);
        String result = Demo1Tool.doGet("http://www.x.com/sso/doLogin.action",map);
        if(result.equals("1")){
            return "success";
        }
        return "login";
}


public void doLogin() throw IOException{
        boolean ok=SSOCheck.checkCookie(cookieName,cookieValue);
        String result = "0";
        if(ok){
            result = "1";
        }
        HttpServletResponse response = ServletActionContext.getResponse();
        response.getWriter().print(result);
        response.getWriter().close();
}
로그 인 검사 인터페이스;부모 필드 SSO 의 로그 인 검사 와 거의 일치 하 며 변화 가 없습니다.

public void checkCookie() throws IOException{
        boolean ok=SSOCheck.checkCookie(cookieName,cookieValue);
        String result="0";
        if(ok){
            result="1";
        }
        HttpServletResponse response = ServletActionContext.getResponse();
        response.getWriter().print(result);
        response.getWriter().close();
}
테스트 홈 페이지 작성

public String main(){
        HttpServletRequst request = ServletActionContext.getRequst();
        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("ssocookie")){
                    Map<String,String> map = new HashMap<String,String>();
                    map.put("userName", cookie.getName());
                    map.put("password", cookie.getValue());
                    String result = Demo1Tool.doGet("http://www.x.com/so/checkCookie.action",
                            cookie.getName(),cookie.getValue());
                    if(result.equals("1")){
                        return "success";
                    }
                }
            }
        }
        //         ,     ,       
        path = "demo1";
        gotoUrl="http://www.a.com/demo1/main.action";
        return "login";
    }


public static String doGet(String url,Map<String,String> map){
        //     
        StringBuffer sb = new StringBuffer();
        HttpURLConnection httpURLConnection = null;
        try{
            StringBuffer t_s = new StringBuffer(url).append("?");
            for(Map.Entry<String, String> entry:map.entrySet()){
                t_s.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                
            }
            url = t_s.substring(0,t_s.length()-1);
            //         
            URL urls = new URL(url);
            //    
            httpURLConnection = (HttpURLConnection) urls.openConnection();
            //         
            httpURLConnection.setRequestMethod("GET");
            //    
            httpURLConnection.connect();
            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String temp = null;
            while((temp = br.readLine())!=null){
                sb.append(temp);
            }
            br.close();
            isr.close();
            in.close();
        } catch(IOException e){
            e.printStackTrace();
        } finally{
            if(httpURLConnection!=null){
                httpURLConnection.disconnect();
            }
        }
        return sb.toString();
    }

이로써 준비 작업 이 완료 되 었 습 니 다.그 다음은 크로스 도 메 인 SSO 실현 에서 가장 중요 한 부분 입 니 다.즉,쿠키 의 설정 입 니 다.예전 에 똑 같은 도 메 인과 같은 부모 도 메 인 상황 에서 SSO 를 실현 하기 위해 저 희 는 doLogin 을 진행 할 때 쿠키 를 설 치 했 습 니 다.도 메 인 이름 이 같 기 때문에 매우 간단 하지만 크로스 도 메 인 SSO 에서 서로 다른 도 메 인 간 의 쿠키 는 보이 지 않 습 니 다.따라서 저 희 는 하나의 쿠키 만 설정 한 다음 에 모든 도 메 인 이름 의 응용 프로그램 을 볼 수 없 기 때문에 저 희 는 모든 도 메 인 아래 에 본 도 메 인 에 쿠키 를 설정 하 는 방법 이 있어 야 합 니 다.쿠키 를 직접 검사 도 메 인 에 전달 해 서 는 안 됩 니 다.

//     cookie   
    public void addCookie(){
        Cookie cookie = new Cookie("ssocookie","sso");
        cookie.setPath("/");
        HttpServletResponse response = ServletActionContext.getResponse();
        response.addCookie(cookie);
    }

설정 파일 에서 설정 해 야 합 니 다:

<action name="addCookie" class="www.a.com.Demo1Action" method="addCookie"></action>
좋 은 방법 을 쓰 려 면 호출 이 필요 합 니 다.그래서 우 리 는 두 사람 이 교 회 를 할 수 있 는 곳 을 찾 아야 합 니 다.여기 서 저 는 로그 인 에 성공 하 는 순간 을 선 택 했 습 니 다.숨겨 진 Iframe 을 통 해 두 사람 을 교 회 를 하 게 했 습 니 다.

public String doLogin(){
        Map<String,String> map = new HashMap<String,String>();
        map.put("userName", userName);
        map.put("password", passWord);
        String result = Demo1Tool.doGet("http://www.x.com/sso/doLogin.action",map);
        if(result.equals("1")){
            return "success";
        }
        List hidderUrl = new ArrayList<String>();
        hidderUrl.add("http://www.a.com/demo1/addCookie.action");
        hidderUrl.add("http://www.b.com/demo2/addCookie.action");
        return "login";
    }

<c:forEach var="url" item="${hiddenUrl}">
    <iframe src="${url}" width="0px" heigth="0px" style="display:none"></iframe>
</c:forEach>
자바 단일 로그 인(SSO)의 실현 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 자바 단일 로그 인 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기