Search in sources :

Example 6 with State

use of com.nimbusds.oauth2.sdk.id.State in project nifi by apache.

the class AccessResource method oidcRequest.

@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());
}
Also used : Cookie(javax.servlet.http.Cookie) State(com.nimbusds.oauth2.sdk.id.State) URI(java.net.URI) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 7 with State

use of com.nimbusds.oauth2.sdk.id.State in project nifi by apache.

the class OidcService method createState.

/**
 * 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;
}
Also used : State(com.nimbusds.oauth2.sdk.id.State) ExecutionException(java.util.concurrent.ExecutionException) CacheKey(org.apache.nifi.web.security.util.CacheKey)

Example 8 with State

use of com.nimbusds.oauth2.sdk.id.State in project nifi by apache.

the class OidcServiceTest method testValidateState.

@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));
}
Also used : State(com.nimbusds.oauth2.sdk.id.State) Test(org.junit.Test)

Example 9 with State

use of com.nimbusds.oauth2.sdk.id.State in project ORCID-Source by ORCID.

the class OpenIDConnectTest method testImplicitOauth.

@Test
public void testImplicitOauth() throws URISyntaxException, ParseException, JOSEException, JSONException, InvalidHashException {
    HashMap<String, String> requestParams = new HashMap<String, String>();
    requestParams.put("nonce", "yesMate");
    requestParams.put("state", "Boaty McBoatface");
    String response = getImplicitTokenResponse(Lists.newArrayList("openid"), requestParams, true);
    // check it's got a fragment
    assertTrue(response.contains("#"));
    // switch to query param for ease of parsing
    response = response.replace('#', '?');
    List<NameValuePair> params = URLEncodedUtils.parse(new URI(response), "UTF-8");
    Map<String, String> map = new HashMap<String, String>();
    for (NameValuePair pair : params) {
        map.put(pair.getName(), pair.getValue());
    }
    // guid length
    assertEquals(map.get("access_token").length(), 36);
    assertTrue(map.get("id_token") != null);
    assertEquals(map.get("token_type"), "bearer");
    assertEquals(map.get("name"), null);
    assertEquals(map.get("orcid"), null);
    assertEquals(map.get("state"), "Boaty McBoatface");
    // check expiry about 10 minutes
    assertTrue((Integer.parseInt(map.get("expires_in")) <= 600));
    assertTrue((Integer.parseInt(map.get("expires_in")) > 590));
    // check id_token
    SignedJWT signedJWT = checkJWT(map.get("id_token"));
    // check hash
    assertNotNull(signedJWT.getJWTClaimsSet().getClaim("at_hash"));
    AccessTokenValidator.validate(new BearerAccessToken(map.get("access_token")), JWSAlgorithm.RS256, new AccessTokenHash(signedJWT.getJWTClaimsSet().getClaim("at_hash").toString()));
    // check access token works
    Client client = Client.create();
    WebResource webResource = client.resource(baseUri + "/oauth/userinfo");
    ClientResponse userInfo = webResource.header("Authorization", "Bearer " + map.get("access_token")).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    String userInfoString = userInfo.getEntity(String.class);
    JSONObject user = new JSONObject(userInfoString);
    Assert.assertEquals("9999-0000-0000-0004", user.get("sub"));
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) NameValuePair(org.apache.http.NameValuePair) HashMap(java.util.HashMap) WebResource(com.sun.jersey.api.client.WebResource) SignedJWT(com.nimbusds.jwt.SignedJWT) URI(java.net.URI) AccessTokenHash(com.nimbusds.openid.connect.sdk.claims.AccessTokenHash) JSONObject(org.codehaus.jettison.json.JSONObject) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Client(com.sun.jersey.api.client.Client) Test(org.junit.Test)

Aggregations

State (com.nimbusds.oauth2.sdk.id.State)8 Test (org.junit.Test)4 URI (java.net.URI)3 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)2 ParseException (com.nimbusds.oauth2.sdk.ParseException)2 ApiOperation (io.swagger.annotations.ApiOperation)2 Consumes (javax.ws.rs.Consumes)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 JWT (com.nimbusds.jwt.JWT)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 AuthorizationCodeGrant (com.nimbusds.oauth2.sdk.AuthorizationCodeGrant)1 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)1 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)1 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)1 AuthenticationErrorResponse (com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse)1 AuthenticationSuccessResponse (com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse)1 Nonce (com.nimbusds.openid.connect.sdk.Nonce)1 AccessTokenHash (com.nimbusds.openid.connect.sdk.claims.AccessTokenHash)1