org.gitlab.api.TokenType Java Examples

The following examples show how to use org.gitlab.api.TokenType. 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: GitLabContext.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
public static GitLabToken obtainAccessToken(@NotNull String gitlabUrl, @NotNull String username, @NotNull String password, boolean sudoScope) throws IOException {
  try {
    final OAuthGetAccessToken tokenServerUrl = new OAuthGetAccessToken(gitlabUrl + "/oauth/token?scope=api" + (sudoScope ? "%20sudo" : ""));
    final TokenResponse oauthResponse = new PasswordTokenRequest(transport, JacksonFactory.getDefaultInstance(), tokenServerUrl, username, password).execute();
    return new GitLabToken(TokenType.ACCESS_TOKEN, oauthResponse.getAccessToken());
  } catch (TokenResponseException e) {
    if (sudoScope && e.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
      // Fallback for pre-10.2 gitlab versions
      final GitlabSession session = GitlabAPI.connect(gitlabUrl, username, password);
      return new GitLabToken(TokenType.PRIVATE_TOKEN, session.getPrivateToken());
    } else {
      throw new GitlabAPIException(e.getMessage(), e.getStatusCode(), e);
    }
  }
}
 
Example #2
Source File: GitlabService.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to GitLab as the current logged in user.
 */
private GitlabAPI getConnection(User user) throws Exception {
    log.debug("Authenticating user `{}` on GitLab", user.getLogin());
    if (user.getGitlabOAuthToken() == null) {
        log.info("No GitLab token configured");
        throw new Exception("GitLab is not configured.");
    }
    GitlabAPI gitlab = GitlabAPI.connect(applicationProperties.getGitlab().getHost(), user.getGitlabOAuthToken(),
        TokenType.ACCESS_TOKEN);

    log.debug("User `{}` authenticated as `{}` on GitLab", user.getLogin(), gitlab.getUser().getUsername());
    return gitlab;
}
 
Example #3
Source File: GitLabAuthenticationToken.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
public GitLabAuthenticationToken(String accessToken, String gitlabServer, TokenType tokenType) throws IOException {
	super(new GrantedAuthority[] {});

	this.accessToken = accessToken;
	this.gitLabAPI = GitlabAPI.connect(gitlabServer, accessToken, tokenType);

	this.me = gitLabAPI.getUser();
	assert this.me != null;

	setAuthenticated(true);

	this.userName = this.me.getUsername();
	authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
	Jenkins jenkins = Jenkins.getInstance();
	if (jenkins != null && jenkins.getSecurityRealm() instanceof GitLabSecurityRealm) {
		if (myRealm == null) {
			myRealm = (GitLabSecurityRealm) jenkins.getSecurityRealm();
		}
		// Search for scopes that allow fetching team membership. This is
		// documented online.
		// https://developer.gitlab.com/v3/orgs/#list-your-organizations
		// https://developer.gitlab.com/v3/orgs/teams/#list-user-teams
		List<GitlabGroup> myTeams = gitLabAPI.getGroups();
		for (GitlabGroup group : myTeams) {
			LOGGER.log(Level.FINE, "Fetch teams for user " + userName + " in organization " + group.getName());

			GitLabOAuthGroupDetails gitLabOAuthGroupDetails = new GitLabOAuthGroupDetails(group);

			authorities.add(gitLabOAuthGroupDetails.getAuth());
		}
	}
}
 
Example #4
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents(new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            if (authentication instanceof GitLabAuthenticationToken) {
                return authentication;
            }
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                try {
                    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
                    GitLabAuthenticationToken gitlab = new GitLabAuthenticationToken(token.getCredentials().toString(), getGitlabApiUri(), TokenType.PRIVATE_TOKEN);
                    SecurityContextHolder.getContext().setAuthentication(gitlab);
                    return gitlab;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            throw new BadCredentialsException("Unexpected authentication type: " + authentication);
        }
    }, new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
            return GitLabSecurityRealm.this.loadUserByUsername(username);
        }
    });
}
 
Example #5
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 4 votes vote down vote up
/**
 * This is where the user comes back to at the end of the OpenID redirect
 * ping-pong.
 */
public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {
    String code = request.getParameter("code");

    if (StringUtils.isBlank(code)) {
        Log.info("doFinishLogin: missing code or private_token.");
        return HttpResponses.redirectToContextRoot();
    }

    String state = request.getParameter("state");

    HttpPost httpPost = new HttpPost(gitlabWebUri + "/oauth/token");
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("client_id", clientID));
    parameters.add(new BasicNameValuePair("client_secret", clientSecret));
    parameters.add(new BasicNameValuePair("code", code));
    parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
    parameters.add(new BasicNameValuePair("redirect_uri", buildRedirectUrl(request, state)));
    httpPost.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost proxy = getProxy(httpPost);
    if (proxy != null) {
        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        httpPost.setConfig(config);
    }

    org.apache.http.HttpResponse response = httpclient.execute(httpPost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.close();

    String accessToken = extractToken(content);

    if (StringUtils.isNotBlank(accessToken)) {
        // only set the access token if it exists.
        GitLabAuthenticationToken auth = new GitLabAuthenticationToken(accessToken, getGitlabApiUri(), TokenType.ACCESS_TOKEN);

        HttpSession session = request.getSession(false);
        if (session != null) {
            // avoid session fixation
            session.invalidate();
        }
        request.getSession(true);

        SecurityContextHolder.getContext().setAuthentication(auth);

        GitlabUser self = auth.getMyself();
        User user = User.current();
        if (user != null) {
            user.setFullName(self.getName());
            // Set email from gitlab only if empty
            if (!user.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) {
                user.addProperty(new Mailer.UserProperty(auth.getMyself().getEmail()));
            }
        }
        SecurityListener.fireAuthenticated(new GitLabOAuthUserDetails(self, auth.getAuthorities()));
    } else {
        Log.info("Gitlab did not return an access token.");
    }

    if (StringUtils.isNotBlank(state)) {
        return HttpResponses.redirectTo(state);
    }
    return HttpResponses.redirectToContextRoot();
}
 
Example #6
Source File: GitLabConfig.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
public GitLabConfig() {
  this("http://localhost/", TokenType.PRIVATE_TOKEN, "");
}
 
Example #7
Source File: GitLabConfig.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
private GitLabConfig(@NotNull String url, @NotNull TokenType tokenType, @NotNull String token) {
  this.url = url;
  this.token = token;
  this.tokenType = tokenType;
}
 
Example #8
Source File: GitLabToken.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
public GitLabToken(@NotNull TokenType type, @NotNull String value) {
  this.type = type;
  this.value = value;
}
 
Example #9
Source File: GitLabToken.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@NotNull
public TokenType getType() {
  return type;
}
 
Example #10
Source File: GitlabHTTPRequestor.java    From java-gitlab-api with Apache License 2.0 3 votes vote down vote up
/**
 * Sets authentication data for the request.
 * Has a fluent api for method chaining.
 *
 * @param token  The token value
 * @param type   The type of the token
 * @param method The authentication method
 * @return this
 */
public GitlabHTTPRequestor authenticate(String token, TokenType type, AuthMethod method) {
    this.apiToken = token;
    this.tokenType = type;
    this.authMethod = method;
    return this;
}