REST API update

This commit is contained in:
Martin Stockhammer 2020-07-14 22:26:10 +02:00
parent 25f4760b1d
commit fa2b8ca7d4
13 changed files with 114 additions and 65 deletions

View File

@ -19,6 +19,7 @@
*/
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@ -26,8 +27,9 @@
* @author Martin Stockhammer <martin_s@apache.org>
*/
@XmlRootElement(name="group")
public class Group
public class Group implements Serializable
{
private static final long serialVersionUID = -1842878251787304632L;
String name;
String uniqueName;
String description;

View File

@ -22,15 +22,17 @@
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
/**
* @author Martin Stockhammer <martin_s@apache.org>
*/
@XmlRootElement(name="refreshToken")
@Schema(name="Request Token Data", description = "Schema used for requesting a Bearer token.")
public class RequestTokenRequest
public class RequestTokenRequest implements Serializable
{
String grantType = "";
private static final long serialVersionUID = -4803869713444270526L;
GrantType grantType = null;
String clientId;
String clientSecret;
String code;
@ -57,19 +59,19 @@ public RequestTokenRequest( String userId, String password, String scope )
this.scope = scope;
}
@XmlElement(name = "grant_type", required = true, nillable = false)
@Schema(description = "The grant type. Normally 'authorization_code'.")
public String getGrantType( )
@XmlElement(name = "grant_type", required = true )
@Schema(description = "The grant type. Currently only 'authorization_code' is supported.")
public GrantType getGrantType( )
{
return grantType;
}
public void setGrantType( String grantType )
public void setGrantType( GrantType grantType )
{
this.grantType = grantType;
}
@XmlElement(name="client_id", required = false, nillable = true)
@XmlElement(name="client_id", nillable = true)
public String getClientId( )
{
return clientId;
@ -80,7 +82,7 @@ public void setClientId( String clientId )
this.clientId = clientId;
}
@XmlElement(name="client_secret", required = false, nillable = true)
@XmlElement(name="client_secret", nillable = true)
public String getClientSecret( )
{
return clientSecret;
@ -91,7 +93,7 @@ public void setClientSecret( String clientSecret )
this.clientSecret = clientSecret;
}
@XmlElement(name="scope", required = false, nillable = true)
@XmlElement(name="scope", nillable = true)
public String getScope( )
{
return scope;
@ -102,7 +104,7 @@ public void setScope( String scope )
this.scope = scope;
}
@XmlElement(name="user_id", required = true, nillable = false)
@XmlElement(name="user_id", required = true )
@Schema(description = "The user identifier.")
public String getUserId( )
{
@ -114,20 +116,20 @@ public void setUserId( String userId )
this.userId = userId;
}
@XmlElement(name="password", required = true, nillable = false)
@XmlElement(name="password", required = true )
@Schema(description = "The user password")
public String getPassword( )
{
return password;
}
@XmlElement(name="password", required = true, nillable = false)
@XmlElement(name="password", required = true )
public void setPassword( String password )
{
this.password = password;
}
@XmlElement(name="code", required = false, nillable = false)
@XmlElement(name="code" )
public String getCode( )
{
return code;
@ -138,7 +140,7 @@ public void setCode( String code )
this.code = code;
}
@XmlElement(name="redirect_uri", required = false, nillable = false)
@XmlElement(name="redirect_uri" )
public String getRedirectUri( )
{
return redirectUri;
@ -149,7 +151,7 @@ public void setRedirectUri( String redirectUri )
this.redirectUri = redirectUri;
}
@XmlElement(name="state", required = false, nillable = false)
@XmlElement(name="state" )
public String getState( )
{
return state;

View File

@ -22,14 +22,16 @@
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
/**
* @author Martin Stockhammer <martin_s@apache.org>
*/
@XmlRootElement( name = "refreshToken" )
@Schema( name = "TokenRequest", description = "Information for requesting tokens" )
public class TokenRequest
public class TokenRequest implements Serializable
{
private static final long serialVersionUID = -7888325843736616091L;
GrantType grantType;
String refreshToken;
String scope;
@ -57,7 +59,7 @@ public void setGrantType( GrantType grantType )
this.grantType = grantType;
}
@XmlElement( name = "refresh_token", required = true)
@XmlElement( name = "refresh_token" )
@Schema(description = "The refresh token that is validated before generating the new access token")
public String getRefreshToken( )
{

View File

@ -18,10 +18,12 @@
* under the License.
*/
import io.swagger.v3.oas.annotations.media.Schema;
import org.apache.archiva.redback.authentication.Token;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;
@ -29,8 +31,11 @@
* @author Martin Stockhammer <martin_s@apache.org>
*/
@XmlRootElement(name="token")
public class TokenResponse
@Schema(name="TokenData", description = "The token response data")
public class TokenResponse implements Serializable
{
private static final long serialVersionUID = 2063260311211245209L;
String accessToken;
String tokenType = "Bearer";
long expiresIn;
@ -77,6 +82,7 @@ public TokenResponse( Token accessToken, Token refreshToken , String scope, Stri
}
@XmlElement(name="access_token")
@Schema(description = "The access token that may be used as Bearer token in the Authorization header")
public String getAccessToken( )
{
return accessToken;
@ -88,6 +94,7 @@ public void setAccessToken( String accessToken )
}
@XmlElement(name="token_type")
@Schema(description = "The type of the token. Currently only Bearer Tokens are supported.")
public String getTokenType( )
{
return tokenType;
@ -99,6 +106,7 @@ public void setTokenType( String tokenType )
}
@XmlElement(name="expires_in")
@Schema(description = "The time in seconds. After this time the token will expire and is not valid for authentication.")
public long getExpiresIn( )
{
return expiresIn;
@ -110,6 +118,7 @@ public void setExpiresIn( long expiresIn )
}
@XmlElement(name="refresh_token")
@Schema(description = "The refresh token, that can be used for getting a new access token.")
public String getRefreshToken( )
{
return refreshToken;
@ -120,6 +129,7 @@ public void setRefreshToken( String refreshToken )
this.refreshToken = refreshToken;
}
@Schema(description = "Scope of the token. Currently there are no scopes defined.")
public String getScope( )
{
return scope;
@ -130,6 +140,7 @@ public void setScope( String scope )
this.scope = scope;
}
@Schema(description = "The state value will be returned, if a state is provided in the request.")
public String getState( )
{
return state;

View File

@ -22,6 +22,8 @@
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.archiva.redback.authorization.RedbackAuthorization;
@ -40,14 +42,20 @@
/**
* Version 2 of authentication service
*
* @since 3.0
*/
@Path( "/auth" )
@SecurityScheme( scheme = "BearerAuth", type = SecuritySchemeType.HTTP )
@Tag(name = "v2")
@Tag(name = "v2/Authentication")
public interface AuthenticationService
{
/**
* Just a ping request / response for checking availability of the server
* @return the ping result
* @throws RedbackServiceException
*/
@Path( "ping" )
@GET
@Produces( { MediaType.APPLICATION_JSON } )
@ -56,11 +64,17 @@ PingResult ping()
throws RedbackServiceException;
/**
* This ping request is only successful, if the provided Bearer token is valid and authenticates a existing user
* @return the ping result or a failure message
* @throws RedbackServiceException
*/
@Path( "ping/authenticated" )
@GET
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noRestriction = false, noPermission = true )
@Operation( summary = "Ping request to restricted service. You have to provide a valid authentication token." )
@SecurityRequirement( name="BearerAuth" )
PingResult pingWithAutz()
throws RedbackServiceException;
@ -83,30 +97,33 @@ TokenResponse logIn( RequestTokenRequest loginRequest )
throws RedbackServiceException;
/**
* Renew the bearer token. The request must send a bearer token in the HTTP header
*
* Request a new token.
*/
@Path( "token" )
@POST
@RedbackAuthorization( noRestriction = false, noPermission = true )
@RedbackAuthorization( noPermission = true )
@Produces( { MediaType.APPLICATION_JSON } )
@Operation( summary = "Creates a new access token based on the given payload.",
@Operation( summary = "Creates a new access token based on the given payload. Currently only grant_type=refresh_token is "+
"supported. You have to provide the refresh token in the payload. And you have to provide a valid Bearer access token in "+
"the Authorization header.",
responses = {
@ApiResponse( description = "The new bearer token," )
@ApiResponse( description = "The new access token," )
}
)
@SecurityRequirement( name="BearerAuth" )
TokenResponse token( TokenRequest tokenRequest )
throws RedbackServiceException;
/**
* simply check if current user has an http session opened with authz passed and return user data
* @since 1.4
* Check, if the current request is authenticated and if so return the current user data
*/
@Path( "authenticated" )
@GET
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noRestriction = true )
@Operation(summary = "Checks the request for a valid access token, and returns the user object that corresponds to the " +
"provided token.")
User getAuthenticatedUser()
throws RedbackServiceException;

View File

@ -48,7 +48,11 @@
public abstract class AbstractInterceptor
{
private final Logger log = LoggerFactory.getLogger( getClass() );
private static final Logger log = LoggerFactory.getLogger( AbstractInterceptor.class );
private static final String API_DOCS = "api-docs";
private static final String OPENAPI_JSON = "openapi.json";
private static final String API_DOCS1 = "api-docs/";
private Map<Method, RedbackAuthorization> authorizationCache = new HashMap<>( );
@ -80,6 +84,12 @@ protected void setHttpServletResponse(HttpServletResponse response) {
}
public static final boolean ignoreAuth(final String requestPath) {
final int len = requestPath.length( );
return len >= 8 && ( ( len == 12 && OPENAPI_JSON.equals( requestPath ) ) ||
( requestPath.startsWith( API_DOCS ) && ( len == 8 || requestPath.startsWith( API_DOCS1 ) ) ) );
}
public RedbackAuthorization getRedbackAuthorization( ResourceInfo resourceInfo ) {
Method method = resourceInfo.getResourceMethod( );
RedbackAuthorization redbackAuthorization = getAuthorizationForMethod( method );

View File

@ -105,10 +105,10 @@ public void filter( ContainerRequestContext requestContext ) throws IOException
log.debug( "Intercepting request for bearer token" );
log.debug( "Request {}", requestContext.getUriInfo( ).getPath( ) );
final String requestPath = requestContext.getUriInfo( ).getPath( );
if ("api-docs".equals(requestPath) || requestPath.startsWith( "api-docs/" )
|| "openapi.json".equals(requestPath)) {
if (ignoreAuth( requestPath )) {
return;
}
// If no redback resource info, we deny the request
RedbackAuthorization redbackAuthorization = getRedbackAuthorization( resourceInfo );
if ( redbackAuthorization == null )

View File

@ -49,6 +49,7 @@ public JacksonJsonConfigurator( @Named("redbackJacksonJsonMapper") ObjectMapper
{
log.info( "configure jackson ObjectMapper" );
objectMapper.disable( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES );
objectMapper.enable( DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL );
objectMapper.setAnnotationIntrospector( new JaxbAnnotationIntrospector( objectMapper.getTypeFactory() ) );
objectMapper.findAndRegisterModules( );
objectMapper.registerModule( new JavaTimeModule( ) );

View File

@ -71,12 +71,12 @@ public class PermissionsInterceptor
private static final Logger log = LoggerFactory.getLogger( PermissionsInterceptor.class );
@Override
public void filter( ContainerRequestContext containerRequestContext )
{
log.debug( "Filtering request" );
final String requestPath = containerRequestContext.getUriInfo( ).getPath( );
if ("api-docs".equals(requestPath) || requestPath.startsWith( "api-docs/" )
|| "openapi.json".equals(requestPath)) {
if (ignoreAuth( requestPath )) {
return;
}

View File

@ -381,8 +381,7 @@ public void filter( ContainerRequestContext containerRequestContext )
{
final String requestPath = containerRequestContext.getUriInfo( ).getPath( );
if ("api-docs".equals(requestPath) || requestPath.startsWith( "api-docs/" )
|| "openapi.json".equals(requestPath)) {
if (ignoreAuth( requestPath )) {
return;
}

View File

@ -31,6 +31,7 @@
import org.apache.archiva.redback.policy.AccountLockedException;
import org.apache.archiva.redback.policy.MustChangePasswordException;
import org.apache.archiva.redback.rest.api.model.ErrorMessage;
import org.apache.archiva.redback.rest.api.model.GrantType;
import org.apache.archiva.redback.rest.api.model.PingResult;
import org.apache.archiva.redback.rest.api.model.TokenRequest;
import org.apache.archiva.redback.rest.api.model.RequestTokenRequest;
@ -113,7 +114,7 @@ public PingResult pingWithAutz()
public TokenResponse logIn( RequestTokenRequest loginRequest )
throws RedbackServiceException
{
if (!"authorization_code".equals(loginRequest.getGrantType())) {
if (!GrantType.AUTHORIZATION_CODE.equals(loginRequest.getGrantType())) {
throw new RedbackServiceException( "redback:bad_authorization_code", Response.Status.FORBIDDEN.getStatusCode( ) );
}
String userName = loginRequest.getUserId(), password = loginRequest.getPassword();
@ -195,7 +196,7 @@ public TokenResponse logIn( RequestTokenRequest loginRequest )
@Override
public TokenResponse token( TokenRequest request ) throws RedbackServiceException
{
if (!"refresh_token".equals(request.getGrantType().getLabel())) {
if (!GrantType.REFRESH_TOKEN.equals(request.getGrantType())) {
log.debug( "Bad grant type {}, expected: refresh_token", request.getGrantType( ).name( ).toLowerCase( ) );
throw new RedbackServiceException( "redback:bad_grant", Response.Status.FORBIDDEN.getStatusCode( ) );
}

View File

@ -56,10 +56,12 @@
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -168,6 +170,29 @@ protected void deleteUser(User user) {
}
}
protected User addUser( String userId, String password, String fullName, String email ) throws UserManagerException
{
return addUser( userId, password, fullName, email, null );
}
protected User addUser( String userId, String password, String fullName, String email, Consumer<User> updateFunction ) throws UserManagerException
{
UserManager um = getUserManager( );
User user = um.createUser( userId, fullName, email );
user.setPassword( password );
user.setPermanent( false );
user.setPasswordChangeRequired( false );
user.setLocked( false );
user.setValidated( true );
user = um.addUser( user );
// We need this additional round, because new users have the password change flag set to true
user.setPasswordChangeRequired( false );
if (updateFunction!=null) {
updateFunction.accept( user );
}
um.updateUser( user );
return user;
}
protected void deleteUser(String userName) {
if (userName!=null)
{

View File

@ -19,18 +19,15 @@
*/
import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
import org.apache.archiva.redback.rest.api.model.LoginRequest;
import org.apache.archiva.redback.rest.api.model.GrantType;
import org.apache.archiva.redback.rest.api.model.RequestTokenRequest;
import org.apache.archiva.redback.rest.api.model.Token;
import org.apache.archiva.redback.rest.api.model.TokenResponse;
import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
import org.apache.archiva.redback.rest.api.services.UserService;
import org.apache.archiva.redback.rest.services.BaseSetup;
import org.apache.archiva.redback.rest.services.FakeCreateAdminService;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.memory.SimpleUser;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -69,7 +66,7 @@ public void loginAdmin()
{
RequestTokenRequest request = new RequestTokenRequest( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME,
BaseSetup.getAdminPwd() );
request.setGrantType( "authorization_code" );
request.setGrantType( GrantType.AUTHORIZATION_CODE );
assertNotNull( getLoginServiceV2( null ).logIn( request ) );
@ -83,15 +80,7 @@ public void createUserThenLog()
{
// START SNIPPET: create-user
UserManager um = getUserManager( );
User user = um.createUser( "toto", "toto the king", "toto@toto.fr" );
user.setValidated( true );
user.setLocked( false );
user.setPassword( "foo123" );
user.setPermanent( false );
user.setPasswordChangeRequired( false );
user.setLocked( false );
user = um.addUser( user );
User user = addUser( "toto", "foo123", "toto the king", "toto@toto.fr" );
// END SNIPPET: create-user
assertNotNull( user );
assertEquals( "toto the king", user.getFullName() );
@ -112,23 +101,13 @@ public void simpleLogin() throws RedbackServiceException, UserManagerException
{
// START SNIPPET: create-user
UserManager um = getUserManager( );
User user = um.createUser( "toto", "toto the king", "toto@toto.fr" );
user.setPassword( "foo123" );
user.setPermanent( false );
user.setPasswordChangeRequired( false );
user.setLocked( false );
user.setValidated( true );
user = um.addUser( user );
// We need this additional round, because new users have the password change flag set to true
user.setPasswordChangeRequired( false );
um.updateUser( user );
User user = addUser( "toto", "foo123", "toto the king", "toto@toto.fr" );
// END SNIPPET: create-user
RequestTokenRequest request = new RequestTokenRequest( "toto", "foo123" );
request.setGrantType( "authorization_code" );
request.setGrantType( GrantType.AUTHORIZATION_CODE );
TokenResponse result = getLoginServiceV2( "" ).logIn( request );
// assertNotNull( result );
// assertEquals( "toto", result.getUsername( ) );
assertNotNull( result );
assertTrue( StringUtils.isNotEmpty( result.getAccessToken( ) ) );
}
finally