@Test
  public void testPrompt() {
    AuthorizationRequest req = mRequestBuilder.setPrompt(AuthorizationRequest.Prompt.LOGIN).build();

    assertThat(req.prompt).isEqualTo(AuthorizationRequest.Prompt.LOGIN);
    assertThat(req.getPromptValues()).hasSize(1).contains(AuthorizationRequest.Prompt.LOGIN);
  }
 @Test
 public void testToUri_noCodeVerifier() throws Exception {
   AuthorizationRequest req = mRequestBuilder.setCodeVerifier(null).build();
   assertThat(req.toUri().getQueryParameterNames())
       .doesNotContain(AuthorizationRequest.PARAM_CODE_CHALLENGE)
       .doesNotContain(AuthorizationRequest.PARAM_CODE_CHALLENGE_METHOD);
 }
  @Test
  public void testToUri() throws Exception {
    AuthorizationRequest request = mRequestBuilder.build();
    Uri uri = request.toUri();
    assertThat(uri.getQueryParameterNames())
        .isEqualTo(
            new HashSet<>(
                Arrays.asList(
                    AuthorizationRequest.PARAM_CLIENT_ID,
                    AuthorizationRequest.PARAM_RESPONSE_TYPE,
                    AuthorizationRequest.PARAM_REDIRECT_URI,
                    AuthorizationRequest.PARAM_STATE,
                    AuthorizationRequest.PARAM_CODE_CHALLENGE,
                    AuthorizationRequest.PARAM_CODE_CHALLENGE_METHOD)));

    assertThat(uri.getQueryParameter(AuthorizationRequest.PARAM_CLIENT_ID))
        .isEqualTo(TEST_CLIENT_ID);
    assertThat(uri.getQueryParameter(AuthorizationRequest.PARAM_RESPONSE_TYPE))
        .isEqualTo(ResponseTypeValues.CODE);
    assertThat(uri.getQueryParameter(AuthorizationRequest.PARAM_REDIRECT_URI))
        .isEqualTo(TEST_APP_REDIRECT_URI.toString());
    assertThat(uri.getQueryParameter(AuthorizationRequest.PARAM_STATE)).isEqualTo(request.state);
    assertThat(uri.getQueryParameter(AuthorizationRequest.PARAM_CODE_CHALLENGE))
        .isEqualTo(request.codeVerifierChallenge);
    assertThat(uri.getQueryParameter(AuthorizationRequest.PARAM_CODE_CHALLENGE_METHOD))
        .isEqualTo(request.codeVerifierChallengeMethod);
  }
Ejemplo n.º 4
0
 public void test_btooth_proper_URL() throws Exception {
   String properBtooth = "B1:B1:0D:B3:10:30:00:00";
   AuthorizationRequest req =
       new AuthorizationRequest(
           "B1:B1:0D:B3:10:30:00:00/sqrl?972764a6021a2649e9bbecfd52c36f13b30a260dbc5c373a53e9d7ae502d0c3a");
   assertTrue("Is proper Bluetooth address", req.isValidBluetooth);
   assertEquals("B1:B1:0D:B3:10:30:00:00", req.getURL());
 }
Ejemplo n.º 5
0
  public void testAuth3_nonce() throws Exception {

    AuthorizationRequest req =
        new AuthorizationRequest(
            "sqrl://example.com/sqrl?4095c8adfa51dabe30fe9f9474d3f91def620300e489e6853baa67bed5d5e0d4");
    String testReuslt = req.getNonce();
    assertEquals("4095c8adfa51dabe30fe9f9474d3f91def620300e489e6853baa67bed5d5e0d4", testReuslt);
  }
Ejemplo n.º 6
0
 public void testAuth_malformed_url3() throws Exception {
   AuthorizationRequest req =
       new AuthorizationRequest(
           "10.0.0.2.5/sqrl?972764a6021a2649e9bbecfd52c36f13b30a260dbc5c373a53e9d7ae502d0c3a");
   // There is no need to be this forgiving. Noone would expect it and I see no benefit in leaving
   // it out
   assertEquals(false, req.IsValid());
 }
Ejemplo n.º 7
0
  public void testAuth_malformed_url() throws Exception {

    AuthorizationRequest req =
        new AuthorizationRequest(
            "example.com/sqrl?4095c8adfa51dabe30fe9f9474d3f91def620300e489e6853baa67bed5d5e0d4");
    // There is no need to be this forgiving. Noone would expect it and I see no benefit in leaving
    // it out
    assertEquals(false, req.IsValid());
  }
    public AuthorizationRequest createAuthorizationRequest(Contact contact) {
      logger.trace("createAuthorizationRequest " + contact);

      AuthorizationRequest authReq = new AuthorizationRequest();
      authReq.setReason(authorizationRequestReason);

      isAuthorizationRequestSent = true;

      return authReq;
    }
Ejemplo n.º 9
0
 private AuthorizationRequest clientCredentialToken(AccessTokenRequest accessTokenRequest) {
   AuthorizationRequest request = new AuthorizationRequest();
   request.setClient(accessTokenRequest.getClient());
   // We have to construct a AuthenticatedPrincipal on-the-fly as there is only key-secret
   // authentication
   request.setPrincipal(new AuthenticatedPrincipal(request.getClient().getClientId()));
   // Get scopes (either from request or the client's default set)
   request.setGrantedScopes(accessTokenRequest.getScopeList());
   return request;
 }
Ejemplo n.º 10
0
  public void testAuth() throws Exception {

    AuthorizationRequest req =
        new AuthorizationRequest(
            "https://localhost/sqrl?4095c8adfa51dabe30fe9f9474d3f91def620300e489e6853baa67bed5d5e0d4");
    String testReuslt = req.getDomain();
    assertEquals("localhost", testReuslt);
    req.fullNut = false;
    assertEquals("https://localhost/sqrl", req.getReturnURL());
  }
Ejemplo n.º 11
0
  @Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
  @Test
  public void supportCodeResponseType(
      final String userId,
      final String userSecret,
      final String redirectUris,
      final String redirectUri,
      final String sectorIdentifierUri)
      throws Exception {
    showTitle("OC5:FeatureTest-Support code Response Type");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);

    // 1. Register client
    RegisterRequest registerRequest =
        new RegisterRequest(
            ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(
        registerResponse.getStatus(),
        200,
        "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String registrationAccessToken = registerResponse.getRegistrationAccessToken();

    // 2. Request authorization
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest =
        new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);

    AuthorizationResponse authorizationResponse =
        authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getCode());
    assertNotNull(authorizationResponse.getState());
  }
Ejemplo n.º 12
0
 private Response sendAuthorizationCodeResponse(AuthorizationRequest authReq) {
   String uri = authReq.getRedirectUri();
   String authorizationCode = getAuthorizationCodeValue();
   authReq.setAuthorizationCode(authorizationCode);
   authorizationRequestRepository.save(authReq);
   uri = uri + appendQueryMark(uri) + "code=" + authorizationCode + appendStateParameter(authReq);
   return Response.seeOther(UriBuilder.fromUri(uri).build())
       .cacheControl(cacheControlNoStore())
       .header("Pragma", "no-cache")
       .build();
 }
  @Test
  public void testToUri_additionalParams() throws Exception {
    Map<String, String> additionalParams = new HashMap<>();
    additionalParams.put("my_param", "1234");
    additionalParams.put("another_param", "5678");
    AuthorizationRequest req = mRequestBuilder.setAdditionalParameters(additionalParams).build();

    Uri uri = req.toUri();
    assertThat(uri.getQueryParameter("my_param")).isEqualTo("1234");
    assertThat(uri.getQueryParameter("another_param")).isEqualTo("5678");
  }
Ejemplo n.º 14
0
 public void testQRlAddress() {
   // qrl://10.0.0.27/login/sqrlauth.php?nut=5f7d471e26450c1539fe73b7867a789abb0c7de6f4246f1e719d7b2830e73de2
   String qrlAddress =
       "qrl://10.0.0.27/login/sqrlauth.php?nut=5f7d471e26450c1539fe73b7867a789abb0c7de6f4246f1e719d7b2830e73de2";
   AuthorizationRequest req = new AuthorizationRequest(qrlAddress);
   assertEquals(true, req.isValid);
   assertEquals("10.0.0.27", req.domain);
   assertEquals(
       "5f7d471e26450c1539fe73b7867a789abb0c7de6f4246f1e719d7b2830e73de2", req.getNonce());
   assertTrue(req.getReturnURL().startsWith("http"));
 }
Ejemplo n.º 15
0
 private AuthorizationRequest authorizationCodeToken(AccessTokenRequest accessTokenRequest) {
   AuthorizationRequest authReq =
       authorizationRequestRepository.findByAuthorizationCode(accessTokenRequest.getCode());
   if (authReq == null) {
     throw new ValidationResponseException(ValidationResponse.INVALID_GRANT_AUTHORIZATION_CODE);
   }
   String uri = accessTokenRequest.getRedirectUri();
   if (!authReq.getRedirectUri().equalsIgnoreCase(uri)) {
     throw new ValidationResponseException(ValidationResponse.REDIRECT_URI_DIFFERENT);
   }
   authorizationRequestRepository.delete(authReq);
   return authReq;
 }
Ejemplo n.º 16
0
 private AuthorizationRequest refreshTokenToken(AccessTokenRequest accessTokenRequest) {
   AccessToken accessToken =
       accessTokenRepository.findByRefreshToken(accessTokenRequest.getRefreshToken());
   if (accessToken == null) {
     throw new ValidationResponseException(ValidationResponse.INVALID_GRANT_REFRESH_TOKEN);
   }
   AuthorizationRequest request = new AuthorizationRequest();
   request.setClient(accessToken.getClient());
   request.setPrincipal(accessToken.getPrincipal());
   request.setGrantedScopes(accessToken.getScopes());
   accessTokenRepository.delete(accessToken);
   return request;
 }
Ejemplo n.º 17
0
 private Response doProcess(HttpServletRequest request) {
   AuthorizationRequest authReq = findAuthorizationRequest(request);
   if (authReq == null) {
     return serverError("Not a valid AbstractAuthenticator.AUTH_STATE on the Request");
   }
   processScopes(authReq, request);
   if (authReq.getResponseType().equals(OAuth2Validator.IMPLICIT_GRANT_RESPONSE_TYPE)) {
     AccessToken token = createAccessToken(authReq, true);
     return sendImplicitGrantResponse(authReq, token);
   } else {
     return sendAuthorizationCodeResponse(authReq);
   }
 }
Ejemplo n.º 18
0
  public void testAuth3_wqithsqrl_picky() throws Exception {

    AuthorizationRequest req =
        new AuthorizationRequest(
            "sqrl://example.com/sqrl?4095c8adfa51dabe30fe9f9474d3f91def620300e489e6853baa67bed5d5e0d4");
    String testReuslt = req.getDomain();
    assertEquals("example.com", testReuslt);
    // if we understand how to construct a sqrl then we should expect to understand how to handle
    // the protocol
    req.isConnectionPicky = true;
    req.fullNut = false;
    assertEquals("https://example.com/sqrl", req.getReturnURL());
  }
Ejemplo n.º 19
0
 public void testQRlAddressSignatureSend() {
   // qrl://10.0.0.27/login/sqrlauth.php?nut=5f7d471e26450c1539fe73b7867a789abb0c7de6f4246f1e719d7b2830e73de2
   String qrlAddress =
       "qrl://10.0.0.27/login/sqrlauth.php?nut=393cbc323070c8281e05bd8554f8d8d409cd9c64267f358cac41c121b1720299";
   AuthorizationRequest req = new AuthorizationRequest(qrlAddress);
   assertEquals(true, req.isValid);
   assertEquals("10.0.0.27", req.domain);
   assertEquals(
       "393cbc323070c8281e05bd8554f8d8d409cd9c64267f358cac41c121b1720299", req.getNonce());
   assertTrue(req.getReturnURL().startsWith("http"));
   assertTrue(
       req.getReturnURL()
           .endsWith("nut=393cbc323070c8281e05bd8554f8d8d409cd9c64267f358cac41c121b1720299"));
 }
  @Test
  public void testPrompt_withVarargs() {
    AuthorizationRequest req =
        mRequestBuilder
            .setPromptValues(AuthorizationRequest.Prompt.LOGIN, AuthorizationRequest.Prompt.CONSENT)
            .build();

    assertThat(req.prompt)
        .isEqualTo(AuthorizationRequest.Prompt.LOGIN + " " + AuthorizationRequest.Prompt.CONSENT);
    assertThat(req.getPromptValues())
        .hasSize(2)
        .contains(AuthorizationRequest.Prompt.LOGIN)
        .contains(AuthorizationRequest.Prompt.CONSENT);
  }
Ejemplo n.º 21
0
 /*
  * In the user consent filter the scopes are (possible) set on the Request
  */
 private void processScopes(AuthorizationRequest authReq, HttpServletRequest request) {
   if (authReq.getClient().isSkipConsent()) {
     // return the scopes in the authentication request since the requested scopes are stored in
     // the
     // authorizationRequest.
     authReq.setGrantedScopes(authReq.getRequestedScopes());
   } else {
     String[] scopes = (String[]) request.getAttribute(AbstractUserConsentHandler.GRANTED_SCOPES);
     if (!ArrayUtils.isEmpty(scopes)) {
       authReq.setGrantedScopes(Arrays.asList(scopes));
     } else {
       authReq.setGrantedScopes(null);
     }
   }
 }
Ejemplo n.º 22
0
  private AuthorizationRequest passwordToken(AccessTokenRequest accessTokenRequest) {
    // Authenticate the resource owner
    AuthenticatedPrincipal principal =
        resourceOwnerAuthenticator.authenticate(
            accessTokenRequest.getUsername(), accessTokenRequest.getPassword());
    if (principal == null) {
      throw new ValidationResponseException(ValidationResponse.INVALID_GRANT_PASSWORD);
    }

    AuthorizationRequest request = new AuthorizationRequest();
    request.setClient(accessTokenRequest.getClient());
    request.setPrincipal(principal);
    request.setGrantedScopes(accessTokenRequest.getScopeList());
    return request;
  }
Ejemplo n.º 23
0
 private String appendStateParameter(AuthorizationRequest authReq) {
   String state = authReq.getState();
   try {
     return StringUtils.isBlank(state) ? "" : "&state=".concat(URLEncoder.encode(state, "UTF-8"));
   } catch (UnsupportedEncodingException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 24
0
 private AccessToken createAccessToken(AuthorizationRequest request, boolean isImplicitGrant) {
   Client client = request.getClient();
   long expireDuration = client.getExpireDuration();
   long expires =
       (expireDuration == 0L ? 0L : (System.currentTimeMillis() + (1000 * expireDuration)));
   String refreshToken =
       (client.isUseRefreshTokens() && !isImplicitGrant) ? getTokenValue(true) : null;
   AuthenticatedPrincipal principal = request.getPrincipal();
   AccessToken token =
       new AccessToken(
           getTokenValue(false),
           principal,
           client,
           expires,
           request.getGrantedScopes(),
           refreshToken);
   return accessTokenRepository.save(token);
 }
Ejemplo n.º 25
0
 private Response sendImplicitGrantResponse(
     AuthorizationRequest authReq, AccessToken accessToken) {
   String uri = authReq.getRedirectUri();
   String fragment =
       String.format(
               "access_token=%s&token_type=bearer&expires_in=%s&scope=%s",
               accessToken.getToken(),
               accessToken.getExpiresIn(),
               StringUtils.join(authReq.getGrantedScopes(), ','))
           + appendStateParameter(authReq);
   if (authReq.getClient().isIncludePrincipal()) {
     fragment += String.format("&principal=%s", authReq.getPrincipal().getDisplayName());
   }
   return Response.seeOther(UriBuilder.fromUri(uri).fragment(fragment).build())
       .cacheControl(cacheControlNoStore())
       .header("Pragma", "no-cache")
       .build();
 }
  @Test
  public void testPrompt_withIterable() {
    AuthorizationRequest req =
        mRequestBuilder
            .setPromptValues(
                Arrays.asList(
                    AuthorizationRequest.Prompt.SELECT_ACCOUNT,
                    AuthorizationRequest.Prompt.CONSENT))
            .build();

    assertThat(req.prompt)
        .isEqualTo(
            AuthorizationRequest.Prompt.SELECT_ACCOUNT + " " + AuthorizationRequest.Prompt.CONSENT);

    assertThat(req.getPromptValues())
        .hasSize(2)
        .contains(AuthorizationRequest.Prompt.SELECT_ACCOUNT)
        .contains(AuthorizationRequest.Prompt.CONSENT);
  }
Ejemplo n.º 27
0
 public void testQRLAddressNewNut() {
   // qrl://10.0.0.27/login/sqrlauth.php?nut=5f7d471e26450c1539fe73b7867a789abb0c7de6f4246f1e719d7b2830e73de2
   String qrlAddress =
       "qrl://10.0.0.27/login/sqrlauth.php?nut=393cbc323070c8281e05bd8554f8d8d409cd9c64267f358cac41c121b1720299";
   AuthorizationRequest req = new AuthorizationRequest(qrlAddress);
   assertEquals(true, req.isValid);
   assertEquals("10.0.0.27", req.domain);
   assertEquals(
       "393cbc323070c8281e05bd8554f8d8d409cd9c64267f358cac41c121b1720299", req.getNonce());
   assertTrue(req.getReturnURL().startsWith("http"));
   assertTrue(
       req.getReturnURL()
           .endsWith("nut=393cbc323070c8281e05bd8554f8d8d409cd9c64267f358cac41c121b1720299"));
   String newNut = Helper.urlEncode(Helper.CreateRandom(32));
   AuthorizationRequest newnutaddress = req.getNewNut(newNut);
   assertTrue(newnutaddress.getReturnURL().startsWith("http"));
   assertTrue(newnutaddress.getReturnURL().endsWith(newNut));
   assertEquals(
       String.format("http://10.0.0.27/login/sqrlauth.php?nut=%s", newNut),
       newnutaddress.getReturnURL());
 }
    public AuthorizationResponse processAuthorisationRequest(
        AuthorizationRequest req, Contact sourceContact) {
      logger.debug("Processing in " + this);
      synchronized (this) {
        logger.trace("processAuthorisationRequest " + req + " " + sourceContact);

        isAuthorizationRequestReceived = true;
        authorizationRequestReason = req.getReason();

        notifyAll();

        // will wait as a normal user
        Object lock = new Object();
        synchronized (lock) {
          try {
            lock.wait(2000);
          } catch (Exception ex) {
          }
        }

        return responseToRequest;
      }
    }
  @Parameters({"redirectUris", "sectorIdentifierUri", "redirectUri", "userId", "userSecret"})
  @Test // This test requires a place to publish a sector identifier JSON array of redirect URIs via
        // HTTPS
  public void requestAuthorizationCodeWithSectorIdentifier(
      final String redirectUris,
      final String sectorIdentifierUri,
      final String redirectUri,
      final String userId,
      final String userSecret)
      throws Exception {
    showTitle("requestAuthorizationCodeWithSectorIdentifier");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);

    // 1. Register client with Sector Identifier URL
    RegisterRequest registerRequest =
        new RegisterRequest(
            ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setSubjectType(SubjectType.PAIRWISE);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(
        registerResponse.getStatus(),
        200,
        "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    // 2. Request authorization and receive the authorization code.
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String state = UUID.randomUUID().toString();
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest =
        new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);
    authorizationRequest.getPrompts().add(Prompt.NONE);

    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(authorizationRequest);
    AuthorizationResponse authorizationResponse = authorizeClient.exec();

    showClient(authorizeClient);
    assertEquals(
        authorizationResponse.getStatus(),
        302,
        "Unexpected response code: " + authorizationResponse.getStatus());
    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");
    assertNotNull(authorizationResponse.getScope(), "The scope is null");
    assertEquals(authorizationResponse.getState(), state);

    String authorizationCode = authorizationResponse.getCode();
    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));

    RSAPublicKey publicKey =
        JwkClient.getRSAPublicKey(jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);

    assertTrue(rsaSigner.validate(jwt));

    // 4. Request access token using the authorization code.
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(
        tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");

    String accessToken = tokenResponse.getAccessToken();

    // 5. Request user info
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);

    showClient(userInfoClient);
    assertEquals(
        userInfoResponse.getStatus(),
        200,
        "Unexpected response code: " + userInfoResponse.getStatus());
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.NAME));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.GIVEN_NAME));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.FAMILY_NAME));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.EMAIL));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.ZONEINFO));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.LOCALE));
  }
Ejemplo n.º 30
0
  @Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
  @Test
  public void requestAuthorizationPromptNone(
      final String userId,
      final String userSecret,
      final String redirectUris,
      final String redirectUri,
      final String sectorIdentifierUri)
      throws Exception {
    showTitle("OC5:FeatureTest-Support prompt value none");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);

    // 1. Register client
    RegisterRequest registerRequest =
        new RegisterRequest(
            ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(
        registerResponse.getStatus(),
        200,
        "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    String sessionState = null;
    {
      // 2. Request authorization
      List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
      String nonce = UUID.randomUUID().toString();
      String state = UUID.randomUUID().toString();

      AuthorizationRequest authorizationRequest =
          new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
      authorizationRequest.setState(state);

      AuthorizationResponse authorizationResponse =
          authenticateResourceOwnerAndGrantAccess(
              authorizationEndpoint, authorizationRequest, userId, userSecret);

      assertNotNull(authorizationResponse.getLocation());
      assertNotNull(authorizationResponse.getCode());
      assertNotNull(authorizationResponse.getState());
      assertNotNull(authorizationResponse.getScope());

      String authorizationCode = authorizationResponse.getCode();
      sessionState = authorizationResponse.getSessionState();

      // 3. Get Access Token
      TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
      tokenRequest.setCode(authorizationCode);
      tokenRequest.setRedirectUri(redirectUri);
      tokenRequest.setAuthUsername(clientId);
      tokenRequest.setAuthPassword(clientSecret);
      tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

      TokenClient tokenClient = new TokenClient(tokenEndpoint);
      tokenClient.setRequest(tokenRequest);
      TokenResponse tokenResponse = tokenClient.exec();

      showClient(tokenClient);
      assertEquals(
          tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
      assertNotNull(tokenResponse.getEntity(), "The entity is null");
      assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
      assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null");
      assertNotNull(tokenResponse.getTokenType(), "The token type is null");
      assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
    }

    {
      // 4. Request authorization
      List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
      String nonce = UUID.randomUUID().toString();
      String state = UUID.randomUUID().toString();

      AuthorizationRequest authorizationRequest =
          new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
      authorizationRequest.setState(state);
      authorizationRequest.getPrompts().add(Prompt.NONE);
      authorizationRequest.setSessionState(sessionState);

      AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
      authorizeClient.setRequest(authorizationRequest);

      AuthorizationResponse authorizationResponse = authorizeClient.exec();

      assertNotNull(authorizationResponse.getLocation());
      assertNotNull(authorizationResponse.getCode());
      assertNotNull(authorizationResponse.getState());
      assertNotNull(authorizationResponse.getScope());

      String authorizationCode = authorizationResponse.getCode();

      // 5. Get Access Token
      TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
      tokenRequest.setCode(authorizationCode);
      tokenRequest.setRedirectUri(redirectUri);
      tokenRequest.setAuthUsername(clientId);
      tokenRequest.setAuthPassword(clientSecret);
      tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

      TokenClient tokenClient = new TokenClient(tokenEndpoint);
      tokenClient.setRequest(tokenRequest);
      TokenResponse tokenResponse = tokenClient.exec();

      showClient(tokenClient);
      assertEquals(
          tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
      assertNotNull(tokenResponse.getEntity(), "The entity is null");
      assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
      assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null");
      assertNotNull(tokenResponse.getTokenType(), "The token type is null");
      assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
    }
  }