com.nimbusds.oauth2.sdk.id.State Java Examples

The following examples show how to use com.nimbusds.oauth2.sdk.id.State. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenIdConnector.java    From onedev with MIT License 6 votes vote down vote up
@Override
public void initiateLogin() {
	try {
		ClientID clientID = new ClientID(clientId);
		
		State state = new State(UUID.randomUUID().toString());
		Session.get().setAttribute(SESSION_ATTR_STATE, state.getValue());
		Session.get().setAttribute(SESSION_ATTR_PROVIDER_METADATA, discoverProviderMetadata());
		
		String scopes = "openid email profile";
		if (groupsClaim != null)
			scopes = scopes + " " + groupsClaim;
		
		AuthenticationRequest request = new AuthenticationRequest(
				new URI(getCachedProviderMetadata().getAuthorizationEndpoint()),
			    new ResponseType("code"), Scope.parse(scopes), clientID, getCallbackUri(),
			    state, new Nonce());
		throw new RedirectToUrlException(request.toURI().toString());
	} catch (URISyntaxException|SerializeException e) {
		throw new RuntimeException(e);
	}		
}
 
Example #2
Source File: OidcService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Initiates an OpenId Connection authorization code flow using the specified request identifier to maintain state.
 *
 * @param oidcRequestIdentifier request identifier
 * @return state
 */
public State createState(final String oidcRequestIdentifier) {
    if (!isOidcEnabled()) {
        throw new IllegalStateException(OPEN_ID_CONNECT_SUPPORT_IS_NOT_CONFIGURED);
    }

    final CacheKey oidcRequestIdentifierKey = new CacheKey(oidcRequestIdentifier);
    final State state = new State(generateStateValue());

    try {
        synchronized (stateLookupForPendingRequests) {
            final State cachedState = stateLookupForPendingRequests.get(oidcRequestIdentifierKey, () -> state);
            if (!timeConstantEqualityCheck(state.getValue(), cachedState.getValue())) {
                throw new IllegalStateException("An existing login request is already in progress.");
            }
        }
    } catch (ExecutionException e) {
        throw new IllegalStateException("Unable to store the login request state.");
    }

    return state;
}
 
Example #3
Source File: OidcService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validates the proposed state with the given request identifier. Will return false if the
 * state does not match or if entry for this request identifier has expired.
 *
 * @param oidcRequestIdentifier request identifier
 * @param proposedState proposed state
 * @return whether the state is valid or not
 */
public boolean isStateValid(final String oidcRequestIdentifier, final State proposedState) {
    if (!isOidcEnabled()) {
        throw new IllegalStateException(OPEN_ID_CONNECT_SUPPORT_IS_NOT_CONFIGURED);
    }

    if (proposedState == null) {
        throw new IllegalArgumentException("Proposed state must be specified.");
    }

    final CacheKey oidcRequestIdentifierKey = new CacheKey(oidcRequestIdentifier);

    synchronized (stateLookupForPendingRequests) {
        final State state = stateLookupForPendingRequests.getIfPresent(oidcRequestIdentifierKey);
        if (state != null) {
            stateLookupForPendingRequests.invalidate(oidcRequestIdentifierKey);
        }

        return state != null && timeConstantEqualityCheck(state.getValue(), proposedState.getValue());
    }
}
 
Example #4
Source File: OidcClient.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
public AuthenticationRequest getAuthenticationRequest(String callbackUrl, String state) {
  AuthenticationRequest request;
  try {
    Builder builder = new AuthenticationRequest.Builder(RESPONSE_TYPE, getScope(), getClientId(),
        new URI(callbackUrl));
    request = builder.endpointURI(getProviderMetadata().getAuthorizationEndpointURI()).state(State.parse(state))
        .build();
  } catch (URISyntaxException e) {
    throw new IllegalStateException("Creating new authentication request failed", e);
  }
  LOGGER.debug("Authentication request URI: {}", request.toURI());
  return request;
}
 
Example #5
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void getAuthenticationRequest() throws URISyntaxException {
  OidcClient underTest = newSpyOidcClient();
  AuthenticationRequest request = underTest.getAuthenticationRequest(CALLBACK_URL, STATE);
  assertEquals("invalid scope", Scope.parse("openid profile email"), request.getScope());
  assertEquals("invalid client id", new ClientID("id"), request.getClientID());
  assertEquals("invalid state", new State(STATE), request.getState());
  assertEquals("invalid response type", ResponseType.getDefault(), request.getResponseType());
  assertEquals("invalid redirect uri", new URI(CALLBACK_URL), request.getRedirectionURI());
  assertEquals("invalid endpoint uri", new URI(ISSUER_URI).resolve("/protocol/openid-connect/auth"),
      request.getEndpointURI());
}
 
Example #6
Source File: OidcServiceTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateStateExpiration() throws Exception {
    final OidcService service = getServiceWithOidcSupportAndCustomExpiration(1, TimeUnit.SECONDS);
    final State state = service.createState(TEST_REQUEST_IDENTIFIER);

    Thread.sleep(3 * 1000);

    assertFalse(service.isStateValid(TEST_REQUEST_IDENTIFIER, state));
}
 
Example #7
Source File: OidcServiceTest.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testOidcNotEnabledValidateState() throws Exception {
    final OidcService service = getServiceWithNoOidcSupport();
    service.isStateValid(TEST_REQUEST_IDENTIFIER, new State(TEST_STATE));
}
 
Example #8
Source File: OidcServiceTest.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testOidcUnknownState() throws Exception {
    final OidcService service = getServiceWithOidcSupport();
    assertFalse(service.isStateValid(TEST_REQUEST_IDENTIFIER, new State(TEST_STATE)));
}
 
Example #9
Source File: OidcServiceTest.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testValidateState() throws Exception {
    final OidcService service = getServiceWithOidcSupport();
    final State state = service.createState(TEST_REQUEST_IDENTIFIER);
    assertTrue(service.isStateValid(TEST_REQUEST_IDENTIFIER, state));
}
 
Example #10
Source File: AccessResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
@Path("oidc/request")
@ApiOperation(
        value = "Initiates a request to authenticate through the configured OpenId Connect provider.",
        notes = NON_GUARANTEED_ENDPOINT
)
public void oidcRequest(@Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) throws Exception {
    // only consider user specific access over https
    if (!httpServletRequest.isSecure()) {
        forwardToMessagePage(httpServletRequest, httpServletResponse, "User authentication/authorization is only supported when running over HTTPS.");
        return;
    }

    // ensure oidc is enabled
    if (!oidcService.isOidcEnabled()) {
        forwardToMessagePage(httpServletRequest, httpServletResponse, "OpenId Connect is not configured.");
        return;
    }

    final String oidcRequestIdentifier = UUID.randomUUID().toString();

    // generate a cookie to associate this login sequence
    final Cookie cookie = new Cookie(OIDC_REQUEST_IDENTIFIER, oidcRequestIdentifier);
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    cookie.setMaxAge(60);
    cookie.setSecure(true);
    httpServletResponse.addCookie(cookie);

    // get the state for this request
    final State state = oidcService.createState(oidcRequestIdentifier);

    // build the authorization uri
    final URI authorizationUri = UriBuilder.fromUri(oidcService.getAuthorizationEndpoint())
            .queryParam("client_id", oidcService.getClientId())
            .queryParam("response_type", "code")
            .queryParam("scope", oidcService.getScope().toString())
            .queryParam("state", state.getValue())
            .queryParam("redirect_uri", getOidcCallback())
            .build();

    // generate the response
    httpServletResponse.sendRedirect(authorizationUri.toString());
}