2013-03-25 1 views
6

리소스 집합을 둘러싼 서블릿을 작성하여 기본 HTTP 인증을 사용하여이를 보호해야합니다. 제출 된 사용자 이름/패스는 파일을 제공하기 전에 백엔드 데이터베이스와 비교하여 검사됩니다.서블릿에서 HTTP 기본 인증 구현

아무도이 작업 예제가 있습니까? http://www.coderanch.com/t/352345/Servlets/java/HTTP-basic-authentication-Web-Applications에서 샘플을 시도했지만 sendError 호출에서 IllegalStateException을 계속 반환했습니다.

+0

포스트 서블릿 –

+0

난 그냥 링크에서 샘플을 사용 : 여기

는 jMock을 사용하여 클래스의 기본 단위 테스트입니다. –

+1

@Roy, 게시물의 예제가 제대로 작동했습니다. 나는 왜 당신에게 그 잘못을주는 지 모르겠습니다. 스택 추적으로 게시물을 업데이트 해 주시겠습니까? –

답변

17

다음은 Credential 객체 (로그인 및 비밀번호가있는 bean 객체)를 반환하는 일부 코드입니다. ? & =/E $ £ :

public Credentials credentialsWithBasicAuthentication(HttpServletRequest req) { 
    String authHeader = req.getHeader("Authorization"); 
    if (authHeader != null) { 
     StringTokenizer st = new StringTokenizer(authHeader); 
     if (st.hasMoreTokens()) { 
      String basic = st.nextToken(); 

      if (basic.equalsIgnoreCase("Basic")) { 
       try { 
        String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8"); 
        LOG.debug("Credentials: " + credentials); 
        int p = credentials.indexOf(":"); 
        if (p != -1) { 
         String login = credentials.substring(0, p).trim(); 
         String password = credentials.substring(p + 1).trim(); 

         return new Credentials(login, password); 
        } else { 
         LOG.error("Invalid authentication token"); 
        } 
       } catch (UnsupportedEncodingException e) { 
        LOG.warn("Couldn't retrieve authentication", e); 
       } 
      } 
     } 
    } 

    return null; 
} 

심지어 펑키와 같은 암호를 사용하여, 잘 작동합니다.

public void testCredentialsWithBasicAuthentication() { 
    // Setup 
    final HttpServletRequest request = context.mock(HttpServletRequest.class); 

    AuthentificationHelper helper = new AuthentificationHelper(); 
    String login = "mickael"; 
    String password = ":&=/?é$£"; 
    String base64Hash = Base64.encodeString(login + ":" + password); 
    final String authHeader = "Basic " + base64Hash; 

    // Expectations 
    context.checking(new Expectations() { 
     { 
      oneOf (request).getHeader("Authorization"); 
      will(returnValue(authHeader)); 
     } 
    }); 

    // Execute 
    Credentials credentials = helper.credentialsWithBasicAuthentication(request); 

    // Verify 
    assertNotNull(credentials); 
    assertEquals(login, credentials.getLogin()); 
    assertEquals(password, credentials.getPassword()); 

    context.assertIsSatisfied(); 
} 
+1

공식 Java 문서에서 가져온'StringTokenizer' 클래스에 대한 약간의주의 사항 : "'StringTokenizer'는 새로운 코드에서 그 사용이 권장되지는 않지만 호환성의 이유로 보존되는 레거시 클래스입니다. 'String' 메소드 나 java.util.regex 패키지의'split' 메소드를 대신 사용하십시오. " – xonya

+0

Base64 클래스의 출처는 어디입니까? –

+0

잠시 동안 Java로 코딩하지 않았지만 J2SE의 Base64 부분이 아닙니까? https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html에서와 같이 –