@Override public Identity identity() throws IOException { Identity identity = Identity.ANONYMOUS; if (this.resource.uriInfo().getQueryParameters() .containsKey(Github.FLAG)) { final List<String> code = this.resource.uriInfo() // @checkstyle MultipleStringLiterals (1 line) .getQueryParameters().get("code"); if (code == null || code.isEmpty()) { throw new WebApplicationException( new IllegalArgumentException( "HTTP query parameter 'code' is mandatory" ), HttpURLConnection.HTTP_BAD_REQUEST ); } identity = this.fetch(this.token(code.get(0))); } return identity; }
@Override public Link link() { return new Link( "rexsl:github", UriBuilder .fromUri("https://github.com/login/oauth/authorize") // @checkstyle MultipleStringLiterals (2 lines) .queryParam("client_id", "{client_id}") .queryParam("redirect_uri", "{redirect_uri}") .build(this.app, this.redirectUri()) ); }
/** * Get user name from Github, with the token provided. * @param token Github access token * @return The user found in Github * @throws IOException If fails */ private Identity fetch(final String token) throws IOException { final URI uri = UriBuilder .fromUri("https://api.github.com/user") .queryParam("access_token", "{token}") .build(token); return this.parse( new JdkRequest(uri) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON) .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class).json().readObject() ); }
/** * Authentication inset. * @return The inset */ @Inset.Runtime public final AuthInset auth() { return new AuthInset(this, Manifests.read("Stateful-SecurityKey")) .with(new Auth(this, this.base())) // @checkstyle LineLength (3 lines) .with(new Facebook(this, Manifests.read("Stateful-FbId"), Manifests.read("Stateful-FbSecret"))) .with(new Google(this, Manifests.read("Stateful-GoogleId"), Manifests.read("Stateful-GoogleSecret"))) .with(new Github(this, Manifests.read("Stateful-GithubId"), Manifests.read("Stateful-GithubSecret"))) .with(BaseRs.TESTER); }
/** * Retrieve Github access token. * @param code Github "authorization code" * @return The token * @throws IOException If failed */ private String token(final String code) throws IOException { final URI uri = UriBuilder .fromUri("https://github.com/login/oauth/access_token") .queryParam("client_id", "{id}") .queryParam("redirect_uri", "{uri}") .queryParam("client_secret", "{secret}") .queryParam("code", "{code}") .build( this.app, this.redirectUri(), this.key, code ); return new JdkRequest(uri) .method(Request.POST) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml().xpath("/OAuth/access_token/text()").get(0); }