how to add facebook authentication to my Rest app in JAVA - java

I created a RESTful application with jersey and now I'm trying to add a facebook authentication interface to my app and i'm kinda stuck how to connect authentication to my rest method .
package service;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import metier.Cours;
#Path("rs")
public class Formation {
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/FraisAnnuelles/{code}")
public Double FraisInscription(#PathParam(value="code")int code) {
return (Double)(30000+(Math.random()*(30000-25000)));
}
#GET
#Path("/Cours/{code}")
#Produces(MediaType.APPLICATION_XML)
public Cours getCours(#PathParam(value="code")int code) {
return new Cours(code,"web semantique",30);
}
#GET
#Path("/ListeCours")
#Produces(MediaType.APPLICATION_XML)
public List<Cours> getAllCours(){
List<Cours> listeCours=new ArrayList<>();
listeCours.add(new Cours(1,"web semantique",30));
listeCours.add(new Cours(2,"web service",20));
listeCours.add(new Cours(3,"IAD",26));
return listeCours;
}
}

I am not sure if you will be able to do that. The protocol that is used for logging in with facebook/google/some_identity_provider is
OpenID connect. That itself is a big can of worms to dive into when starting from scratch, but the key element in why I have some doubts to the feasibility of what you are asking for is that for a login using openid connect to be successful, the identity provider has a database table with a list of allowed urls to log in from, and unless the url you try to log in from matches exactly 100% one of the values in that table, the login attempt will fail.
So in other words, in order to allow users to log in with facebook/google on https://myblog.example.com/blog you need to contact facebook/google and ask them "hey facebook/google, can you add https://myblog.example.com/blog to the list urls allowed to log in from pretty please?". I assume both companies require some (significant) minimum size of your web site before allowing logging in with them, and you will be absolutely at the whim of their terms and condition with zero negotiation possibilities. You might need to pay for the privileged to use them as identity providers.

Related

Spring boot #PostMapping for login

I need to send an email every time a user logs into an account, but since SpringBoot is used I don't have a #PostMapping method for /login. What should I do?
From what you wrote, I assume that you want to send email only when user performs a successful login. You could write your implementation of AuthenticationSuccessHandler to send an email when user logs in succesfully.
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
#Component
public class MyNotifyingAuthSuccessHandler implements AuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
//send email (do it asynchronously if you can)
//redirect to your homepage (page where user should land after login)
}
}
Sending an email sometimes takes a lot of time, so consider doing that async not to block the login operation for too long, if your business requirements allow you to do that.

Micronaut all routes forbidden

I created an app in Micronaut using JWT tokens for security
mn create-app --features=security-jwt,data-jdbc,reactor,graalvm example.micronaut.micronautguide --build=gradle --lang=java
And now all my routes are forbidden. How to exclude certain routes (ie. login) from JWT token checking. I tried both without annotation and with annotation IS_ANONYMOUS
package logfetcher;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;
import io.micronaut.http.annotation.Produces;
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.rules.SecurityRule;
#Controller("/log")
public class LogFethcerContoller
{
#Get
#Secured(
SecurityRule.IS_ANONYMOUS )
#Produces(MediaType.TEXT_PLAIN)
public String index() {
return "Hello World";
}
#Get("log")
public String index1() {
return "Hello World";
}
}
I get 401 on both routes.
How can I have routes that do not need the JWT token.
I get 401 on both routes.
From micronaut-projects.github.io/micronaut-security/3.2.0/guide/#gettingStarted...
By default Micronaut returns HTTP Status Unauthorized (401) for any
endpoint invocation. Routes must be explicitly allowed through the
provided mechanisms.
Question:
How can I have routes that do not need the JWT token.
There are a number of ways.
From micronaut-projects.github.io/micronaut-security/3.2.0/guide/#securityRule...
The decision to allow access to a particular endpoint to anonymous or
authenticated users is determined by a collection of Security Rules.
#PermitAll is one way to do it. Others are documented at the links above.

Java Micronaut - throws "javax.net.ssl.SSLHandshakeException" after I hit the endpoint more than once

I have a simple micronaut app.
I have two separate endpoints where the method that executes will call an API using a client (I've tried both the http client from "java.net.http.HttpClient" and "io.micronaut.http.client.RxHttpClient" but the same issue happens).
When you hit any of the endpoints after starting the app, the function will execute as expected, where the client calls an external API and retrieves the response as a string. If you try to hit that same endpoint again, it will throw:
"javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure."
I don't think this is an issue on the API's server side for the following reasons:
This issue happens when I hit two separate endpoints with two separate external APIs
The request goes through the first time no problem
I can hit the same APIs in postman without error - it's just when I call them with the client that there is an issue.
My controller:
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.HttpResponse;
import javax.inject.Inject;
import java.io.IOException;
import static io.micronaut.http.HttpRequest.GET;
#Controller("/api")
public class DeckController {
#Inject
private DeckService deckService;
#Get(value = "/drawRx")
public HttpResponse<Card> drawCardRx(){
deckService.drawCardRx("ijhhxvxwn63g",1);
return HttpResponse.ok();
}
}
One of my services where the client calls the API:
public void drawCardRx(String deckId, int amount){
final String newDeckUrl = "/deck/"+deckId+"/draw/?count="+amount;
Disposable result = this.httpClient
.retrieve( GET(newDeckUrl))
.subscribe(data -> System.out.println(data));
return;
}
Like I said, the first time I hit the endpoint, the response is returned from the server without a problem.
I've tried the below articles and followed those steps, but no improvement.
https://www.baeldung.com/java-ssl-handshake-failures
How to solve javax.net.ssl.SSLHandshakeException Error?
Is there something I am missing?

At what moment does JAX-RS receive information about the key storage address from microprofile-config.properties?

I have Java EE backend and I use Keycloak for auth.
I have Application extends class:
import org.eclipse.microprofile.auth.LoginConfig;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/")
#LoginConfig(authMethod = "MP-JWT", realmName = "private")
public class CargoServiceApplication extends Application {
}
And I have microprofile-config.properties too:
mp.jwt.verify.publickey.location=http://keycloak-test.local:8080/auth/realms/customer-service/protocol/openid-connect/certs
mp.jwt.verify.issuer=http://keycloak-test.local:8080/auth/realms/customer-service
Сan someone explain to me at what point in time JAX-RS gets the JWT config? And where does it store this configuration?
How can I reset stored config in runtime?
Thanks everyone!)

access web services from WSDL link java

I am trying to access web services that are defined in WSDL by giving the url of the WSDL. The specific case I am working on is the ebay "FindingService".
After parsing the WSDL, I search for the service I am looking for (for example "FindingService"). Next, I want to be able to use that service (send keywords and get results) through some sort of client. I looked around and found the following code that I tried to modify to use it for my example. Since I am still new to WSDL, I am not sure of how to adapt it and I keep getting the error: Undefined port type: {http://WSDL/}face
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class client{
public static void main(String[] args) throws Exception {
URL url = new URL("http://developer.ebay.com/webservices/finding/latest/findingservice.wsdl");
//1st argument service URI, refer to wsdl document above
//2nd argument is service name, refer to wsdl document above
QName qname = new QName("http://www.ebay.com/marketplace/search/v1/services", "FindingService");
Service service = Service.create(url, qname);
face hello = service.getPort(face.class);
System.out.println(hello.getHelloWorldAsString("test"));
}
}
the second class is:
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
//Service Endpoint Interface
#WebService
#SOAPBinding(style = Style.RPC)
public interface face{
#WebMethod String getHelloWorldAsString(String name);
}
the third class is:
import javax.jws.WebService;
//Service Implementation
#WebService(endpointInterface = "face")
public class endp implements face{
#Override
public String getHelloWorldAsString(String name) {
return "Hello World JAX-WS " + name;
}
}
I'd be thankful if I can get some guidance. Is it possible to access services like that or do I have to use the ebay API (with keys etc..) ?
WSDL is just a contract between the client and the server.
The best solution is not parse the WSDL in runtime and try to call the actions. You probably want to call these actions to do something useful. Ex: find all user Ebay orders.
Each of these actions can have complex inputs and outputs. The best solution to work with SOAP webservices in Java is usually generate code based in the WSDL, so you will have a full working client without too much work.
I can recommend these APIs:
JAX-WS:
http://www.mkyong.com/webservices/jax-ws/jax-ws-wsimport-tool-example/
Spring-WS:
https://spring.io/guides/gs/consuming-web-service/
Axis 2:
https://axis.apache.org/axis2/java/core/docs/userguide-creatingclients.html

Categories