Search in sources :

Example 1 with TokenContext

use of de.ids_mannheim.korap.security.context.TokenContext in project Kustvakt by KorAP.

the class SearchController method serializeQuery.

// EM: This web service is DISABLED until there is a need for it.
// ND: In case rewrite is supported, it could be used to check the authorization
// scope without searching etc. In case not, it helps to compare queries in
// different query languages.
// MH: ref query parameter removed!
// @GET
// @Path("{version}/query")
// @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response serializeQuery(@Context Locale locale, @Context SecurityContext securityContext, @QueryParam("q") String q, @QueryParam("ql") String ql, @QueryParam("v") String v, @QueryParam("context") String context, @QueryParam("cutoff") Boolean cutoff, @QueryParam("count") Integer pageLength, @QueryParam("offset") Integer pageIndex, @QueryParam("page") Integer startPage, @QueryParam("access-rewrite-disabled") boolean accessRewriteDisabled, @QueryParam("cq") String cq) {
    TokenContext ctx = (TokenContext) securityContext.getUserPrincipal();
    try {
        scopeService.verifyScope(ctx, OAuth2Scope.SERIALIZE_QUERY);
        String result = searchService.serializeQuery(q, ql, v, cq, pageIndex, startPage, pageLength, context, cutoff, accessRewriteDisabled);
        if (DEBUG) {
            jlog.debug("Query: " + result);
        }
        return Response.ok(result).build();
    } catch (KustvaktException e) {
        throw kustvaktResponseHandler.throwit(e);
    }
}
Also used : TokenContext(de.ids_mannheim.korap.security.context.TokenContext) KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException)

Example 2 with TokenContext

use of de.ids_mannheim.korap.security.context.TokenContext in project Kustvakt by KorAP.

the class SearchController method retrieveMatchInfo.

@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Path("{version}/corpus/{corpusId}/{docId}/{textId}/{matchId}")
public Response retrieveMatchInfo(@Context SecurityContext ctx, @Context HttpHeaders headers, @Context Locale locale, @PathParam("corpusId") String corpusId, @PathParam("docId") String docId, @PathParam("textId") String textId, @PathParam("matchId") String matchId, @QueryParam("foundry") Set<String> foundries, @QueryParam("layer") Set<String> layers, @QueryParam("spans") Boolean spans, @QueryParam("expand") String expansion, // Highlights may also be a list of valid highlight classes
@QueryParam("hls") Boolean highlights) throws KustvaktException {
    Boolean expandToSentence = true;
    if (expansion != null && (expansion.equals("false") || expansion.equals("null"))) {
        expandToSentence = false;
    }
    TokenContext tokenContext = (TokenContext) ctx.getUserPrincipal();
    scopeService.verifyScope(tokenContext, OAuth2Scope.MATCH_INFO);
    spans = spans != null ? spans : false;
    highlights = highlights != null ? highlights : false;
    if (layers == null || layers.isEmpty())
        layers = new HashSet<>();
    try {
        String results = searchService.retrieveMatchInfo(corpusId, docId, textId, matchId, foundries, tokenContext.getUsername(), headers, layers, spans, expandToSentence, highlights);
        return Response.ok(results).build();
    } catch (KustvaktException e) {
        throw kustvaktResponseHandler.throwit(e);
    }
}
Also used : TokenContext(de.ids_mannheim.korap.security.context.TokenContext) KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 3 with TokenContext

use of de.ids_mannheim.korap.security.context.TokenContext in project Kustvakt by KorAP.

the class AuthenticationController method requestAPIToken.

// EM: testing using spring security authentication manager
// @Deprecated
// @GET
// @Path("ldap/token")
// public Response requestToken (@Context HttpHeaders headers,
// @Context Locale locale,
// @HeaderParam(ContainerRequest.USER_AGENT) String agent,
// @HeaderParam(ContainerRequest.HOST) String host,
// @HeaderParam("referer-url") String referer,
// @QueryParam("scope") String scopes,
// //   @Context WebServiceContext wsContext, // FB
// @Context SecurityContext securityContext) {
// 
// Map<String, Object> attr = new HashMap<>();
// if (scopes != null && !scopes.isEmpty())
// attr.put(Attributes.SCOPES, scopes);
// attr.put(Attributes.HOST, host);
// attr.put(Attributes.USER_AGENT, agent);
// 
// User user = new KorAPUser();
// user.setUsername(securityContext.getUserPrincipal().getName());
// controller.setAccessAndLocation(user, headers);
// if (DEBUG_LOG == true) System.out.printf(
// "Debug: /token/: location=%s, access='%s'.\n",
// user.locationtoString(), user.accesstoString());
// attr.put(Attributes.LOCATION, user.getLocation());
// attr.put(Attributes.CORPUS_ACCESS, user.getCorpusAccess());
// 
// try {
// TokenContext context = controller.createTokenContext(user, attr,
// TokenType.API);
// return Response.ok(context.toJson()).build();
// }
// catch (KustvaktException e) {
// throw kustvaktResponseHandler.throwit(e);
// }
// }
@GET
@Path("apiToken")
public // @ResourceFilters({HeaderFilter.class})
Response requestAPIToken(@Context HttpHeaders headers, @Context Locale locale, @HeaderParam(ContainerRequest.USER_AGENT) String agent, @HeaderParam(ContainerRequest.HOST) String host, @HeaderParam("referer-url") String referer, @QueryParam("scope") String scopes, // @Context WebServiceContext wsContext, // FB
@Context SecurityContext secCtx) {
    List<String> auth = headers.getRequestHeader(ContainerRequest.AUTHORIZATION);
    if (auth == null || auth.isEmpty()) {
        throw kustvaktResponseHandler.throwit(new KustvaktException(StatusCodes.MISSING_PARAMETER, "Authorization header is missing.", "Authorization header"));
    }
    AuthorizationData authorizationData;
    try {
        authorizationData = authorizationHandler.parseAuthorizationHeaderValue(auth.get(0));
        if (authorizationData.getAuthenticationScheme().equals(AuthenticationScheme.BASIC)) {
            authorizationData = authorizationHandler.parseBasicToken(authorizationData);
        } else {
        // EM: throw exception that auth scheme is not supported?
        }
    } catch (KustvaktException e) {
        throw kustvaktResponseHandler.throwit(e);
    }
    if (DEBUG_LOG == true) {
        System.out.printf("Debug: AuthService.requestAPIToken...:\n");
        System.out.printf("Debug: auth.size=%d\n", auth.size());
        System.out.printf("auth.get(0)='%s'\n", auth.get(0));
        /* hide password etc. - FB
             if( auth.size() > 0 )
            	{
            	Iterator it = auth.iterator();
            	while( it.hasNext() )
            		System.out.printf(" header '%s'\n",  it.next());
            	}
            if( values.length > 0 )
            	{
            	for(int i=0; i< values.length; i++)
            		{
            		System.out.printf(" values[%d]='%s'\n",  i, values[i]);
            		}
            	}
             */
        MultivaluedMap<String, String> headerMap = headers.getRequestHeaders();
        if (headerMap != null && headerMap.size() > 0) {
            Iterator<String> it = headerMap.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                List<String> vals = headerMap.get(key);
            // System.out.printf("Debug: requestAPIToken: '%s' = '%s'\n",
            // key, vals);
            }
        }
    // System.out.printf("Debug: requestAPIToken: isSecure = %s.\n",
    // secCtx.isSecure() ? "yes" : "no");
    }
    if (authorizationData.getUsername() == null || authorizationData.getUsername().isEmpty() || authorizationData.getPassword() == null || authorizationData.getPassword().isEmpty())
        // is actual an invalid request
        throw kustvaktResponseHandler.throwit(StatusCodes.REQUEST_INVALID);
    Map<String, Object> attr = new HashMap<>();
    if (scopes != null && !scopes.isEmpty())
        attr.put(Attributes.SCOPE, scopes);
    attr.put(Attributes.HOST, host);
    attr.put(Attributes.USER_AGENT, agent);
    TokenContext context;
    try {
        // User user = controller.authenticate(0, values[0], values[1], attr); Implementation by Hanl
        User user = controller.authenticate(AuthenticationMethod.LDAP, authorizationData.getUsername(), authorizationData.getPassword(), // Implementation with IdM/LDAP
        attr);
        // Userdata data = this.controller.getUserData(user, UserDetails.class); // Implem. by Hanl
        // todo: is this necessary?
        // attr.putAll(data.fields());
        // EM: add authentication time
        Date authenticationTime = TimeUtils.getNow().toDate();
        attr.put(Attributes.AUTHENTICATION_TIME, authenticationTime);
        // -- EM
        controller.setAccessAndLocation(user, headers);
        if (DEBUG_LOG == true)
            System.out.printf("Debug: /apiToken/: location=%s, access='%s'.\n", user.locationtoString(), user.accesstoString());
        attr.put(Attributes.LOCATION, user.getLocation());
        attr.put(Attributes.CORPUS_ACCESS, user.getCorpusAccess());
        context = controller.createTokenContext(user, attr, TokenType.API);
    // context = controller.createTokenContext(user, attr,
    // Attributes.API_AUTHENTICATION);
    } catch (KustvaktException e) {
        throw kustvaktResponseHandler.throwit(e);
    }
    try {
        return Response.ok(context.toJson()).build();
    } catch (KustvaktException e) {
        throw kustvaktResponseHandler.throwit(e);
    }
}
Also used : TokenContext(de.ids_mannheim.korap.security.context.TokenContext) KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) User(de.ids_mannheim.korap.user.User) AuthorizationData(de.ids_mannheim.korap.authentication.http.AuthorizationData) HashMap(java.util.HashMap) Date(java.util.Date) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 4 with TokenContext

use of de.ids_mannheim.korap.security.context.TokenContext in project Kustvakt by KorAP.

the class AuthenticationController method loginshib.

// fixme: security issues: setup shibboleth compatible authentication system
// todo: will be purged with token authentication --> shib is client side
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/json")
@Path("shibboleth")
public Response loginshib(@Context HttpHeaders headers, @Context Locale locale, @HeaderParam(ContainerRequest.USER_AGENT) String agent, @HeaderParam(ContainerRequest.HOST) String host, @QueryParam("client_id") String client_id) {
    // the shibfilter decrypted the values
    // define default provider for returned access token strategy?!
    Map<String, Object> attr = new HashMap<>();
    attr.put(Attributes.HOST, host);
    attr.put(Attributes.USER_AGENT, agent);
    TokenContext context;
    try {
        // todo: distinguish type KorAP/Shibusers
        User user = controller.authenticate(AuthenticationMethod.SHIBBOLETH, null, null, attr);
        context = controller.createTokenContext(user, attr, null);
    } catch (KustvaktException e) {
        throw kustvaktResponseHandler.throwit(e);
    }
    try {
        return Response.ok().entity(context.toJson()).build();
    } catch (KustvaktException e) {
        throw kustvaktResponseHandler.throwit(e);
    }
}
Also used : TokenContext(de.ids_mannheim.korap.security.context.TokenContext) User(de.ids_mannheim.korap.user.User) KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 5 with TokenContext

use of de.ids_mannheim.korap.security.context.TokenContext in project Kustvakt by KorAP.

the class OAuth2Controller method requestAuthorizationCode.

/**
 * Requests an authorization code.
 *
 * Kustvakt supports authorization only with Kalamar as the
 * authorization web-frontend or user interface. Thus
 * authorization code request requires user authentication
 * using authorization header.
 *
 * <br /><br />
 * RFC 6749:
 * If the client omits the scope parameter when requesting
 * authorization, the authorization server MUST either process the
 * request using a pre-defined default value or fail the request
 * indicating an invalid scope.
 *
 * @param request
 *            HttpServletRequest
 * @param form
 *            form parameters
 * @return a redirect URL
 */
@POST
@Path("authorize")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response requestAuthorizationCode(@Context HttpServletRequest request, @Context SecurityContext context, @FormParam("state") String state, MultivaluedMap<String, String> form) {
    TokenContext tokenContext = (TokenContext) context.getUserPrincipal();
    String username = tokenContext.getUsername();
    ZonedDateTime authTime = tokenContext.getAuthenticationTime();
    try {
        scopeService.verifyScope(tokenContext, OAuth2Scope.AUTHORIZE);
        HttpServletRequest requestWithForm = new FormRequestWrapper(request, form);
        OAuth2AuthorizationRequest authzRequest = new OAuth2AuthorizationRequest(requestWithForm);
        String uri = authorizationService.requestAuthorizationCode(requestWithForm, authzRequest, username, authTime);
        return responseHandler.sendRedirect(uri);
    } catch (OAuthSystemException e) {
        throw responseHandler.throwit(e, state);
    } catch (OAuthProblemException e) {
        throw responseHandler.throwit(e, state);
    } catch (KustvaktException e) {
        throw responseHandler.throwit(e, state);
    }
}
Also used : TokenContext(de.ids_mannheim.korap.security.context.TokenContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) FormRequestWrapper(de.ids_mannheim.korap.web.utils.FormRequestWrapper) KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) ZonedDateTime(java.time.ZonedDateTime) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2AuthorizationRequest(de.ids_mannheim.korap.oauth2.oltu.OAuth2AuthorizationRequest) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Aggregations

TokenContext (de.ids_mannheim.korap.security.context.TokenContext)62 KustvaktException (de.ids_mannheim.korap.exceptions.KustvaktException)54 Path (javax.ws.rs.Path)40 Consumes (javax.ws.rs.Consumes)21 POST (javax.ws.rs.POST)19 User (de.ids_mannheim.korap.user.User)16 ResourceFilters (com.sun.jersey.spi.container.ResourceFilters)15 GET (javax.ws.rs.GET)11 KorAPUser (de.ids_mannheim.korap.user.KorAPUser)10 DELETE (javax.ws.rs.DELETE)10 Produces (javax.ws.rs.Produces)9 Userdata (de.ids_mannheim.korap.user.Userdata)5 ZonedDateTime (java.time.ZonedDateTime)5 HashMap (java.util.HashMap)4 PUT (javax.ws.rs.PUT)4 AuthorizationData (de.ids_mannheim.korap.authentication.http.AuthorizationData)3 FormRequestWrapper (de.ids_mannheim.korap.web.utils.FormRequestWrapper)3 HashSet (java.util.HashSet)3 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)3 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)3