gitlab4j-api
gitlab4j-api copied to clipboard
Cannot create Personal Access Token
The API offers to create a Personal Access Token through AccessTokenUtils::createPersonalAccessToken. However this method is not working for me. The method is not able to extract the authenticity token from the login response. Also the /profile/personal_access_tokens url seems to have changed.
What's working for me is a custom implementation of api Create a personal access token:
public class UserPersonalAccessTokensApi extends UserApi
{
public UserPersonalAccessTokensApi( GitLabApi gitLabApi )
{
super( gitLabApi );
}
public PersonalAccessToken createPersonalAccessToken(
Object userIdOrUsername, String name, Date expiresAt, Scope[] scopes )
throws GitLabApiException
{
// See https://docs.gitlab.com/ee/api/users.html#create-a-personal-access-token
if( scopes == null || scopes.length == 0 )
throw new RuntimeException( "scopes cannot be null or empty" );
GitLabApiForm formData = new GitLabApiForm()
.withParam( "name", name, true )
.withParam( "expires_at", expiresAt );
for( Scope scope : scopes )
formData.withParam( "scopes[]", scope.toString() );
Response response = post( Response.Status.CREATED, formData, "users",
getUserIdOrUsername( userIdOrUsername ), "personal_access_tokens" );
return (response.readEntity( PersonalAccessToken.class ));
}
}
where
public class PersonalAccessToken
{
public enum Scope {
API, READ_API, READ_USER, READ_REPOSITORY, WRITE_REPOSITORY, READ_REGISTRY, WRITE_REGISTRY, SUDO;
private static JacksonJsonEnumHelper<Scope> enumHelper = new JacksonJsonEnumHelper<>(Scope.class);
@JsonCreator
public static Scope forValue(String value) {
return enumHelper.forValue(value);
}
@JsonValue
public String toValue() {
return (enumHelper.toString(this));
}
@Override
public String toString() {
return (enumHelper.toString(this));
}
}
private Boolean active;
private String token;
private List<Scope> scopes;
private Boolean revoked;
private String name;
private Long id;
private Date createdAt;
private Date expiresAt;
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public List<Scope> getScopes() {
return scopes;
}
public void setScopes(List<Scope> scopes) {
this.scopes = scopes;
}
public Boolean getRevoked() {
return revoked;
}
public void setRevoked(Boolean revoked) {
this.revoked = revoked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
@Override
public String toString() {
return (JacksonJson.toJsonString(this));
}
}