Java源码示例:org.gitlab.api.TokenType

示例1
@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);
    }
  }
}
 
示例2
/**
 * 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;
}
 
示例3
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());
		}
	}
}
 
示例4
@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);
        }
    });
}
 
示例5
/**
 * 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();
}
 
示例6
public GitLabConfig() {
  this("http://localhost/", TokenType.PRIVATE_TOKEN, "");
}
 
示例7
private GitLabConfig(@NotNull String url, @NotNull TokenType tokenType, @NotNull String token) {
  this.url = url;
  this.token = token;
  this.tokenType = tokenType;
}
 
示例8
public GitLabToken(@NotNull TokenType type, @NotNull String value) {
  this.type = type;
  this.value = value;
}
 
示例9
@NotNull
public TokenType getType() {
  return type;
}
 
示例10
/**
 * 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;
}