Basi c аутентификация с JAXRS и Джерси - PullRequest
0 голосов
/ 15 апреля 2020

Когда я добавил Jaxrs с jersey, это выдает внутреннюю ошибку 500. Я хочу выполнить базовую аутентификацию c, класс java также предоставляется после porm. xml Пожалуйста, обратитесь.

Также я включаю сервисы, которые я реализую

пакет com;

import java .util.List;

import javax.ws.rs. *; import javax.ws.rs.core.MediaType;

import model.Payments;

// для JSON import com.google.gson. *;

import controller.PaymentsDBHandler;

@ Path ("/ paymentService") publi c Класс paymentService реализует PaymentServiceInterface {

PaymentsDBHandler dbHandler = new PaymentsDBHandler();

@GET
@Path("/Admin/getAll/")
@Produces(MediaType.TEXT_HTML)
public String getPaymentAll() {
    return dbHandler.readAll();
}

@GET
@Path("/Admin/getAllJSON/")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Payments> getPaymentAllJSON() {
    return dbHandler.readAllJSON();
}

@Override
@GET
@Path("/getPayment/{ID}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Payments> getPaymentJSON(@PathParam("ID") int id) {
    return dbHandler.readJSON(String.valueOf(id));
}

@POST
@Path("/getPayment/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_HTML)
public String getPayment(String paymentID) {

    // Convert input string to json object
    JsonObject itemObject = new JsonParser().parse(paymentID).getAsJsonObject();

    String paymentID1 = itemObject.get("paymentID").getAsString();

    return dbHandler.read(paymentID1);
}

@PUT
@Path("/Admin/updatePayment/")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public String updatePayment(@FormParam("paymentID") String id, @FormParam("paymentType") String type,
        @FormParam("appointmentID") String App_id, @FormParam("paymentAmount") String amount) {

    Payments payments = new Payments();

    payments.setPaymentID(Integer.parseInt(id));
    payments.setPaymentType(type);
    payments.setPaymentAmount(Double.parseDouble(App_id));
    payments.setAppointmentID(Integer.parseInt(amount));

    return dbHandler.update(payments);

}

@PUT
@Path("/Admin/updatePaymentJSON/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_HTML)
public String updatePayment(String data) {

    Payments payments = new Payments();

    // Convert input string to json object
    JsonObject itemObject = new JsonParser().parse(data).getAsJsonObject();

    payments.setPaymentID(itemObject.get("paymentID").getAsInt());
    payments.setPaymentType(itemObject.get("paymentType").getAsString());
    payments.setPaymentAmount(itemObject.get("paymentAmount").getAsDouble());
    payments.setAppointmentID(itemObject.get("appointmentID").getAsInt());

    return dbHandler.update(payments);
}

@POST
@Path("/insertPayment/")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public String addPayment(@FormParam("paymentAmount") String amount, @FormParam("paymentType") String type,
        @FormParam("appointmentID") String App_id) {

    Payments payments = new Payments();

    payments.setPaymentType(type);
    payments.setPaymentAmount(Double.parseDouble(App_id));
    payments.setAppointmentID(Integer.parseInt(amount));

    return dbHandler.insert(payments);

}

@POST
@Path("/insertPaymentJSON/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_HTML)
public String addPayment(String data) {

    Payments payments = new Payments();

    // Convert input string to json object
    JsonObject itemObject = new JsonParser().parse(data).getAsJsonObject();

    payments.setPaymentType(itemObject.get("paymentType").getAsString());
    payments.setPaymentAmount(itemObject.get("paymentAmount").getAsDouble());
    payments.setAppointmentID(itemObject.get("appointmentID").getAsInt());

    return dbHandler.insert(payments);
}

@DELETE
@Path("/Admin/deletePaymentJSON/")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String deletePayment(String id) {

    // Convert input string to json object
    JsonObject itemObject = new JsonParser().parse(id).getAsJsonObject();

    String ID = itemObject.get("paymentID").getAsString();
    return dbHandler.delete(ID);

}

@GET
@Path("/getAppointment/")
@Produces(MediaType.TEXT_HTML)
public String getAppointmentID() {
    return dbHandler.readAll();
}

}

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.HealthCareSystem</groupId>
    <artifactId>HealthCareSystem</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
    <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.1</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>


        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-bundle</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.19.4</version>
        </dependency>
     Gives Error when I add this one without cannot do authentication
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0.1</version>
        </dependency>



    </dependencies>
</project>

Почему я использую аутентификацию

    package com;

    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.ws.rs.container.ContainerRequestContext; 

выдает ошибку, если удалена зависимость jaxrs

    import javax.ws.rs.core.Response;
    import javax.ws.rs.ext.Provider;

    import java.util.Base64;
    import java.util.List;

    import java.util.StringTokenizer;

    @Provider
    public class SecurityFilter implements javax.ws.rs.container.ContainerRequestFilter {

        private static final String AUTHORIZATION_HEADER = "Authorization";
        private static final String AUTHORIZATION_PREFIX = "Basic ";
        private static final String URL_PREFIX = "Admin";

        // Create DB connection
        private Connection connect() {
            Connection con = null;

            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                // Con details
                con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/users", "root", "Pa$$w0rd");
            } catch (Exception e) {
                // e.printStackTrace();
            }

            return con;
        }

        @Override
        public void filter(ContainerRequestContext requestcontext) throws IOException {

            if (requestcontext.getUriInfo().getPath().contains(URL_PREFIX)) {
                List<String> authHeader = requestcontext.getHeaders().get(AUTHORIZATION_HEADER);

                if (authHeader.size() > 0) {
                    String authToken = authHeader.get(0);
                    authToken = authToken.replaceFirst(AUTHORIZATION_PREFIX, "");

                    String decodeString = new String(Base64.getDecoder().decode(authToken));

                    StringTokenizer tokenizer = new StringTokenizer(decodeString, ":");

                    String userName = tokenizer.nextToken();
                    String password = tokenizer.nextToken();

                    // find whether user in the DB
                    Connection con = connect();

                    try {
                        String query = "select * from users where Password = " + password;
                        Statement statement = con.createStatement();
                        ResultSet resultSet = statement.executeQuery(query);

                        if (password == Integer.toString(resultSet.getInt(1))) {
                            return;
                        }

                        con.close();

                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                // if authentication fails
                Response unauthorizedStatus = Response.status(Response.Status.UNAUTHORIZED)
                        .entity("User cannot access the responce.").build();

                requestcontext.abortWith(unauthorizedStatus);
            }
        }
    }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...