Does anyone can help me to get a solution for authenticate with a backend server ? I am logging in in my platform with a google account and I post the id_token (using ajax).
var msg = $.ajax({type: "POST", url: "controller/action", data: token, async: false}).responseText;
if (msg=="ok"){
window.location = "controller/action";
}
else {
window.location = "controller/action";
}
Now, I want to authenticate the token in order to save user information (name, image,email) in database.
I see this https://developers.google.com/identity/sign-in/web/backend-auth. Is there a way to use it?
Send get Request in any RestClient and replace xyz with your token:-
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=xyz
Once you get Response in restclient then simply assemble this get request in your convenient language. Get request in grails see this
hope it helps you
Related
I am building login application using OAuth2 and spring boot microservice. The challenge I facing is implementing two factor authentiation. Once the user enters credentials when gets successful then before sending
access token to frontend it should call another microservice to send sms to phone number which is present in access token.
Currently I am using flag IS_TFA_ENABLED=Y if Y then making other ajax call to send sms to phone number received in access token,But i want this sms service to be called at server side only after credentials are validated successfullyand shoot another sms service call.
Any suggestion how to implement this ?
front end code is below
$.ajax({
type: "POST",
url: "http://localhost:8095/oauth2-service/oauth/token",
data: "username="+username+"&password="+password+"&grant_type=password",
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Basic "+btoa("clientId:password"));
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
},
success: function(msg){
**if(JSON.parse(JSON.stringify(msg)).is_tfa_enabled=="Y") {**
**var email_two_fa_url = "http://localhost:8095/user-service/users/"+JSON.parse(JSON.stringify(msg)).id
+"/emails/"+JSON.parse(JSON.stringify(msg)).userName+"/2fa";
var mobile_two_fa_url = "http://localhost:8095/user-service/users/"+JSON.parse(JSON.stringify(msg)).id
+"/mobilenumbers/"+JSON.parse(JSON.stringify(msg)).mobile+"/2fa";
var verify_2fa_url = "http://localhost:8095/user-service/users/"+JSON.parse(JSON.stringify(msg)).id
+"/codes/";**
sessionStorage.setItem("email_two_fa_url",email_two_fa_url);
sessionStorage.setItem("mobile_two_fa_url",mobile_two_fa_url);
sessionStorage.setItem("verify_2fa_url",verify_2fa_url);
sessionStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token);
sessionStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token);
if(JSON.parse(JSON.stringify(msg)).tfa_default_type=="SMS") {
two_fa_url = mobile_two_fa_url;
} else {
two_fa_url = email_two_fa_url;
}
send2facode(two_fa_url, function() {
$("#myModal").modal('show');
});
}else{
localStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token);
localStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token);
window.location.reload("permissions.html");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$(".alert-danger").show();
}
});
I propose to develop two authentication services:
The first service provide authentication user login/password. If the
credentials are corrects, it sends the SMS, saves the code in the
database for verification and returns back a temporary token that
contains only the user id and one authorization for the second service
(SECOND_FACT_AUTH for example). It is possible to insert the code
inside the to ken to avoid the access to database.
The second service secured by the authorization "SECOND_FACT_AUTH"
that checks the code in database or inside the token according to
where you store it, then it generates the traditional authentication and
refresh tokens.
I have a problem with sending API request via postman or Java lib "io.restassured".
When I do the same action on UI the request returns correct response, but when I try the same thing via postman or java code I get:
401 Bad request Your browser sent an invalid
request.
The java code
public static void main(String[] args) {
String requestUrl = "exampleBaseUrl/app/reports/api/rest/v1/graphs?context=shipper&reports_type=freights";
Response response = RestAssured.given().relaxedHTTPSValidation().header("x-csrf-token", "18ea65e740eb0ddddadf0ef435d92564").
when().
get(requestUrl);
}
I assume something is wrong with the authentication, because in dev tools i can see a Get request for CSRF_token, and it looks like this:
the endpoint for the token:
/login?get_csrf_token
and for this request I get following response:
{"csrf_token":"18ea65e740eb0ddddadf0ef435d92564"}
I am not sure how to solve this, I have also tried to get the token via java code by sending a get request to the token's endpoint /login?get_csrf_token
and this one gets my a HTML response with empty username and password input.
Error 401 means your request isn't authorized.
For authorization, usually while logging in you are given a token, which you will have to keep in your cache/local-memory and whenever you communicate with the server you have to add that in your request header (for your own introduction to the server)
It seems like in your case you can get a token from /login?get_csrf_token after logging in. Note that you don't need authorization for a login service.
Now, after getting token from the server, how to add it as a request header? See REST Assured Documentation
I am not able to do a POST request to the Composer rest server that is authenticated.
I have been trying out Hyperledger composer rest server with
authentication and multiuser enabled.
I have enabled Github based authentication by exporting
COMPOSER_PROVIDERS variable and multiuser mode with Wallet and
identities .
I authenticate the rest server in github and i am able to do rest
operations in the Composer Swagger explorer .
I am also able to do the rest operations in Postman by passing the
url with the access_token .
http://localhost:4200/api/Trader?access_token=xxxxxxxxxxx .This works
in Postman as well.
Problem is i am not able to do a post request to the composer-rest URL from java code even after passing the access token as param. I have tried with OKHttpClient,Apache HTTPClient, java.net client , CloseableHTTPClient .
All it gives me is
Server returned HTTP response code: 401
In all methods i get an "AUTHORIZATION FAILURE" error .
I dont know if i am missing anything , because i am able to do a rest operation from Postman . I take the code format from Postman itself and paste it in the Java code and it still doesnt work . I dont know what i am doing wrong ,
Suggestions , code snippets ?
THANKS !
since you managed to get this running from Postman then you're obviously missing something in your java code.
You probably have the URL correct, but might be missing a header, or a json type or something of the sorts.
Inspect your Postman request and replicate it exactly in your java code, everything, not just the URL.
Keep a log of your request and compare it against the Postman one, to see exactly what the difference is.
Try this code to retrieve cookies:
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("http://host.example.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie : cookies) {
if (cookie.getName().equalsIgnoreCase("access_token")) {
System.out.println("CookieHandler retrieved cookie: " + cookie.getValue());
break;
}
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
You can refer it from here: https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html
I have been trying hard to work this out for login authentication using angular as client and jersey exposed as rest web service at backend.
Here is what I achieved from last three days.
Angular code to capture email and password:
myApp.controller('loginController',['$scope','$http', function($scope, $http)
{
$scope.email = "" ;
$scope.password = "" ;
$scope.loginForm = function(){
alert("login controller called");
console.log($scope.email);
console.log($scope.password);
var encodedString = 'email=' +
encodeURIComponent($scope.email) +
'&password=' +
encodeURIComponent($scope.password);
$http({
method:'POST',
url: 'rs/loginResource',
data: encodedString,
headers: {'Content-Type' : 'application/x-www-form-urlencoded'}
});
};
}]);
Java rest code:
#Path("/loginResource")
public class LoginResource {
public LoginResource() {
}
#POST
#Consumes("application/x-www-form-urlencoded")
public void login(#FormParam("email") String email,
#FormParam("password") String password) {
System.out.println("Email is: " + email); //prints output
System.out.println("Password is: " + password); //prints output
}
}
And now my question is where to go from here after getting the POST data from form submit. As you can see I am just printing the values rather I would like to check the email and password against database(oracle). How would I go about it? Shall I use simple connection class and dao or go for JPA which I haven't learned yet - what is the learning curve for it?
Is there any design pattern involved? Usually I use Dao and pojo if its plain java but I am new to rest api that too struggling with angular. I hardly find any examples on vanilla java+angular where most of them are based on spring+angular.
Generally login goes like this:
Client calls server with login details
Server verifies login details against the database, if valid, sets up a session. If invalid, the server will return a very generic error response. Important to not give the client any info about which part of the submission was wrong (gives attackers more info).
For this you'll want to read into sessions. Here are some links:
https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpSession.html
https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec#.z4vdsyrty
There's plenty of information on this problem on the internet.
Also, for generic REST APIs authentication will usually happen in the form of a token. The flow looks a little different:
Client calls server with some sort of auth info
The server generates a token using something like Json Web Tokens and returns it to the client. Generally these have an expiry. The server might also expire all other tokens for the user.
The client sends the token, generally as a header, with every future request.
There's lots of ways to encrypt a password when sending it from client -> server. Here's a simple one I suggest you try: RESTful Authentication
Let's say I need to upload files to a server programmatically using uploading a file programmatically can a server whatever php java or asp.net return me a value when using POST request method instead of GET ?
If not how can I ask the server which files have been uploaded correctly or that uploads have finished ?
I mean if the server is ANOTHER server than mine I can't see how to get the response so can you give some sample code or refer to some urls.
It can, same way as GET requests e.g. server can answer with JSON format string response which will include uploaded files or it can return full html page, whatever you need.
E.g. if you want to send some data to server using POST method and you want to alert it you can do something like this (jQuery):
$.ajax({
type: "POST",
url: "http://localhost/testing.php",
data: { name: "John Doe" } // sample data sent to server
}).done(function( msg ) {
alert( "Response data: " + msg );
});
Generally it shouldn't matter if it was GET or POST, response is returned from server, the only thing you need to do is catch it and perform actions based on response content.