com.networknt.body.BodyHandler Java Examples

The following examples show how to use com.networknt.body.BodyHandler. 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: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");

        HttpHandler handler = getPetStoreHandler();
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        SwaggerHandler swaggerHandler = new SwaggerHandler();
        swaggerHandler.setNext(handler);
        handler = swaggerHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }
}
 
Example #2
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the request against the given API operation
 * @param requestPath normalised path
 * @param exchange The HttpServerExchange to validate
 * @param openApiOperation OpenAPI operation
 * @return A validation report containing validation errors
 */
public Status validateRequest(final NormalisedPath requestPath, HttpServerExchange exchange, OpenApiOperation openApiOperation) {
    requireNonNull(requestPath, "A request path is required");
    requireNonNull(exchange, "An exchange is required");
    requireNonNull(openApiOperation, "An OpenAPI operation is required");

    Status status = validateRequestParameters(exchange, requestPath, openApiOperation);
    if(status != null) return status;
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (contentType==null || contentType.startsWith("application/json")) {
        Object body = exchange.getAttachment(BodyHandler.REQUEST_BODY);
        // skip the body validation if body parser is not in the request chain.
        if(body == null && ValidatorHandler.config.skipBodyValidation) return null;
        status = validateRequestBody(body, openApiOperation);
    }
    return status;
}
 
Example #3
Source File: ForwardRequestHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String responseBody = null;
    if(exchange.getAttachment(BodyHandler.REQUEST_BODY) != null) {
        responseBody = Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY));
    }

    List<HttpString> headerNames = exchange.getRequestHeaders().getHeaderNames().stream()
            .filter( s -> s.toString().startsWith("todo"))
            .collect(Collectors.toList());
    for(HttpString headerName : headerNames) {
        String headerValue = exchange.getRequestHeaders().get(headerName).getFirst();
        exchange.getResponseHeaders().put(headerName, headerValue);
    }
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ContentType.APPLICATION_JSON.value());
    exchange.getResponseSender().send(responseBody);
}
 
Example #4
Source File: ResponseValidatorTest.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");
        TestValidateResponseHandler testValidateResponseHandler = new TestValidateResponseHandler();
        HttpHandler handler = Handlers.routing()
                .add(Methods.GET, "/v1/todoItems", testValidateResponseHandler);
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        OpenApiHandler openApiHandler = new OpenApiHandler();
        openApiHandler.setNext(handler);
        handler = openApiHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }
}
 
Example #5
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the request against the given API operation
 * @param requestPath normalised path
 * @param exchange The HttpServerExchange to validate
 * @param swaggerOperation swagger operation
 * @return A validation report containing validation errors
 */
public Status validateRequest(final NormalisedPath requestPath, HttpServerExchange exchange, SwaggerOperation swaggerOperation) {
    requireNonNull(requestPath, "A request path is required");
    requireNonNull(exchange, "An exchange is required");
    requireNonNull(swaggerOperation, "An swagger operation is required");

    Status status = validatePathParameters(requestPath, swaggerOperation);
    if(status != null) return status;

    status = validateQueryParameters(exchange, swaggerOperation);
    if(status != null) return status;

    status = validateHeader(exchange, swaggerOperation);
    if(status != null) return status;

    Object body = exchange.getAttachment(BodyHandler.REQUEST_BODY);
    // skip the body validation if body parser is not in the request chain.
    if(body == null && ValidatorHandler.config.skipBodyValidation) return null;
    status = validateRequestBody(body, swaggerOperation);

    return status;
}
 
Example #6
Source File: BodyDumper.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * impl of dumping request body to result
 * @param result A map you want to put dump information to
 */
@Override
public void dumpRequest(Map<String, Object> result) {
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    //only dump json info
    if (contentType != null && contentType.startsWith("application/json")) {
        //if body info already grab by body handler, get it from attachment directly
        Object requestBodyAttachment = exchange.getAttachment(BodyHandler.REQUEST_BODY);
        if(requestBodyAttachment != null) {
            dumpBodyAttachment(requestBodyAttachment);
        } else {
            //otherwise get it from input stream directly
            dumpInputStream();
        }
    } else {
        logger.info("unsupported contentType: {}", contentType);
    }
    this.putDumpInfoTo(result);
}
 
Example #7
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");

        HttpHandler handler = getPetStoreHandler();
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        OpenApiHandler openApiHandler = new OpenApiHandler();
        openApiHandler.setNext(handler);
        handler = openApiHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
        clearLogFile();
    }
}
 
Example #8
Source File: ServerBuilder.java    From light-4j with Apache License 2.0 6 votes vote down vote up
public Undertow build() {
    HttpHandler handler = HandlerBuilder.build();

    SanitizerHandler sanitizerHandler = new SanitizerHandler(configName);
    sanitizerHandler.setNext(handler);
    handler = sanitizerHandler;

    BodyHandler bodyHandler = new BodyHandler();
    bodyHandler.setNext(handler);
    handler = bodyHandler;

    instance = null;

    return Undertow.builder()
            .addHttpListener(8080, "localhost")
            .setHandler(handler)
            .build();
}
 
Example #9
Source File: Oauth2ServiceServiceIdEndpointPostHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    List<Map<String, Object>> body = (List)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
    if(logger.isDebugEnabled()) logger.debug("post serviceEndpoints for serviceId " + serviceId);

    // ensure that the serviceId exists
    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    if(services.get(serviceId) == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
        processAudit(exchange);
        return;
    }

    IMap<String, List<ServiceEndpoint>> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints");
    List<ServiceEndpoint> list = new ArrayList<>();
    for(Map<String, Object> m: body) {
        list.add(Config.getInstance().getMapper().convertValue(m, ServiceEndpoint.class));
    }
    serviceEndpoints.set(serviceId, list);
    processAudit(exchange);
}
 
Example #10
Source File: Oauth2ClientPutHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    Client client = Config.getInstance().getMapper().convertValue(body, Client.class);
    if(client.getDerefClientId() != null && Client.ClientTypeEnum.EXTERNAL != client.getClientType()) {
        // only external client may have deref client id
        setExchangeStatus(exchange, DEREF_NOT_EXTERNAL);
        return;
    }

    String clientId = client.getClientId();

    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client originalClient = clients.get(clientId);
    if(originalClient == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
    } else {
        // set client secret as it is not returned by query.
        client.setClientSecret(originalClient.getClientSecret());
        clients.set(clientId, client);
    }
    processAudit(exchange);
}
 
Example #11
Source File: Oauth2UserPutHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    User user = Config.getInstance().getMapper().convertValue(body, User.class);
    String userId = user.getUserId();
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    User u = users.get(userId);
    if(u == null) {
        setExchangeStatus(exchange, USER_NOT_FOUND, userId);
    } else {
        // as password is not in the return value, chances are password is not in the user object
        user.setPassword(u.getPassword());
        users.set(userId, user);
    }
    processAudit(exchange);
}
 
Example #12
Source File: Oauth2ProviderPutHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    Provider provider = Config.getInstance().getMapper().convertValue(body, Provider.class);

    String provider_id = provider.getProviderId() ;

    IMap<String, Provider> providers = CacheStartupHookProvider.hz.getMap("providers");
    if(providers.get(provider_id) == null) {
        setExchangeStatus(exchange, PROVIDER_ID_INVALID);
    } else {
        providers.set(provider_id, provider);
        exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(provider));
    }
    processAudit(exchange);
    
}
 
Example #13
Source File: Oauth2ProviderPostHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    Provider provider = Config.getInstance().getMapper().convertValue(body, Provider.class);

    String provider_id = provider.getProviderId() ;

    IMap<String, Provider> providers = CacheStartupHookProvider.hz.getMap("providers");
    if(providers.get(provider_id) == null) {
        providers.set(provider_id, provider);
        exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(provider));
    } else {
        setExchangeStatus(exchange, PROVIDER_ID_EXISTS, provider_id);
    }
    processAudit(exchange);
}
 
Example #14
Source File: Oauth2ServicePutHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    Service service = Config.getInstance().getMapper().convertValue(body, Service.class);

    String serviceId = service.getServiceId();

    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    if(services.get(serviceId) == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
    } else {
        services.set(serviceId, service);
    }
    processAudit(exchange);
}
 
Example #15
Source File: ClientAuditHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
protected void processAudit(HttpServerExchange exchange) throws Exception{
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.CLIENT);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #16
Source File: LoggerPostHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    Map<String, Deque<String>> parameters = exchange.getQueryParameters();
    String loggerName = parameters.get(LOGGER_NAME).getFirst();

    Map<String, Object> requestBody = (Map<String, Object>) exchange.getAttachment(BodyHandler.REQUEST_BODY);
    LoggerConfig config = (LoggerConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, LoggerConfig.class);

    if (config.isEnabled()) {
        ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(loggerName);
        if(requestBody!=null) {
            String firstKey = requestBody.keySet().stream().findFirst().get();
            logger.setLevel(Level.valueOf(requestBody.get(firstKey).toString()));
        }else{
            logger.error("Logging level is not provided");
            setExchangeStatus(exchange, LOGGER_LEVEL_EMPTY);
        }
        LoggerInfo loggerInfo = new LoggerInfo();
        loggerInfo.setName(logger.getName());
        loggerInfo.setLevel(logger.getLevel().toString());

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ContentType.APPLICATION_JSON.value());
        exchange.getResponseSender().send(mapper.writeValueAsString(loggerInfo));
        exchange.getResponseSender().send(loggerInfo.toString());

    } else {
        logger.error("Logging is disabled in logging.yml");
        setExchangeStatus(exchange, STATUS_LOGGER_INFO_DISABLED);
    }
}
 
Example #17
Source File: Oauth2AuthorizeGetHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
private void processAudit(HttpServerExchange exchange) throws Exception {
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.AUTHORIZE);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #18
Source File: Oauth2AuthorizePostHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
public void processAudit(HttpServerExchange exchange) throws Exception {
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.AUTHORIZE);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #19
Source File: ProviderAuditHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
protected void processAudit(HttpServerExchange exchange) throws Exception{
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.CLIENT);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #20
Source File: Oauth2KeyKeyIdGetHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
private void processAudit(HttpServerExchange exchange) throws Exception {
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.KEY);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #21
Source File: SanitizerHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    String method = exchange.getRequestMethod().toString();
    if (config.isSanitizeHeader()) {
        HeaderMap headerMap = exchange.getRequestHeaders();
        if (headerMap != null) {
            for (HeaderValues values : headerMap) {
                if (values != null) {
                    ListIterator<String> itValues = values.listIterator();
                    while (itValues.hasNext()) {
                        itValues.set(encoding.applyEncoding(itValues.next()));
                    }
                }
            }
        }
    }

    if (config.isSanitizeBody() && ("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method) || "PATCH".equalsIgnoreCase(method))) {
        // assume that body parser is installed before this middleware and body is parsed as a map.
        // we are talking about JSON api now.
        Object body = exchange.getAttachment(BodyHandler.REQUEST_BODY);
        if (body != null) {
            if(body instanceof List) {
                encoding.encodeList((List<Map<String, Object>>)body);
            } else {
                // assume it is a map here.
                encoding.encodeNode((Map<String, Object>)body);
            }
        }
    }
    Handler.next(exchange, next);
}
 
Example #22
Source File: Oauth2ClientPostHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    Client client = Config.getInstance().getMapper().convertValue(body, Client.class);
    if(client.getDerefClientId() != null && Client.ClientTypeEnum.EXTERNAL != client.getClientType()) {
        // only external client may have deref client id
        setExchangeStatus(exchange, DEREF_NOT_EXTERNAL);
        return;
    }
    // generate client_id and client_secret here.
    String clientId = UUID.randomUUID().toString();
    client.setClientId(clientId);
    String clientSecret = Util.getUUID();
    client.setClientSecret(HashUtil.generateStrongPasswordHash(clientSecret));

    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    if(clients.get(clientId) == null) {
        clients.set(clientId, client);
        // send the client back with client_id and client_secret
        Client c = Client.copyClient(client);
        c.setClientSecret(clientSecret);
        exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(c));
    } else {
        setExchangeStatus(exchange, CLIENT_ID_EXISTS, clientId);
    }
    processAudit(exchange);
}
 
Example #23
Source File: ServiceAuditHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
protected void processAudit(HttpServerExchange exchange) throws Exception{
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.SERVICE);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #24
Source File: Oauth2ServicePostHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    Service service = Config.getInstance().getMapper().convertValue(body, Service.class);

    String serviceId = service.getServiceId();
    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    if(services.get(serviceId) == null) {
        services.set(serviceId, service);
    } else {
        setExchangeStatus(exchange, SERVICE_ID_EXISTS, serviceId);
    }
    processAudit(exchange);
}
 
Example #25
Source File: Oauth2PasswordUserIdPostHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    String userId = exchange.getQueryParameters().get("userId").getFirst();
    char[] password = null;
    if(body.get("password") != null) {
        password = ((String)body.get("password")).toCharArray();
    }
    String newPassword = (String)body.get("newPassword");
    String newPasswordConfirm = (String)body.get("newPasswordConfirm");

    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    User user = users.get(userId);
    if(user == null) {
        setExchangeStatus(exchange, USER_NOT_FOUND, userId);
        processAudit(exchange);
    } else {
        if(!HashUtil.validatePassword(password, user.getPassword())) {
            setExchangeStatus(exchange, INCORRECT_PASSWORD);
            processAudit(exchange);
            return;
        }
        if(newPassword.equals(newPasswordConfirm)) {
            String hashedPass = HashUtil.generateStrongPasswordHash(newPassword);
            user.setPassword(hashedPass);
            users.set(userId, user);
        } else {
            setExchangeStatus(exchange, PASSWORD_PASSWORDCONFIRM_NOT_MATCH, newPassword, newPasswordConfirm);
        }
        processAudit(exchange);
    }
}
 
Example #26
Source File: UserAuditHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
protected void processAudit(HttpServerExchange exchange) throws Exception{
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.USER);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #27
Source File: CodeAuditHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
protected void processAudit(HttpServerExchange exchange) throws Exception{
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.CODE);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #28
Source File: TokenAuditHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
protected void processAudit(HttpServerExchange exchange) throws Exception{
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.TOKEN);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}
 
Example #29
Source File: Oauth2SigningPostHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    ObjectMapper mapper = Config.getInstance().getMapper();
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
    // check authorization header for basic authentication
    Client client = authenticateClient(exchange);
    if(client != null) {
        String jwt;
        Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY);
        SignRequest sr = Config.getInstance().getMapper().convertValue(body, SignRequest.class);
        int expires = sr.getExpires();
        try {
            // assume that the custom_claim is in format of json map string.
            Map<String, Object>  customClaim = sr.getPayload();
            jwt = JwtIssuer.getJwt(mockCcClaims(client.getClientId(), expires, customClaim));
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage()));
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("access_token", jwt);
        resMap.put("token_type", "bearer");
        resMap.put("expires_in", expires);
        exchange.getResponseSender().send(mapper.writeValueAsString(resMap));
    }
    processAudit(exchange);
}
 
Example #30
Source File: RefreshTokenAuditHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
protected void processAudit(HttpServerExchange exchange) throws Exception{
    if (oauth_config.isEnableAudit() ) {
        AuditInfo auditInfo = new AuditInfo();
        auditInfo.setServiceId(Oauth2Service.REFRESHTOKEN);
        auditInfo.setEndpoint(exchange.getHostName() + exchange.getRelativePath());
        auditInfo.setRequestHeader(exchange.getRequestHeaders().toString());
        auditInfo.setRequestBody(Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY)));
        auditInfo.setResponseCode(exchange.getStatusCode());
        auditInfo.setResponseHeader(exchange.getResponseHeaders().toString());
        auditInfo.setResponseBody(Config.getInstance().getMapper().writeValueAsString(exchange.getResponseCookies()));
        saveAudit(auditInfo);
    }
}