How to trace the rest request authentication parameters(username/password) - rest

I have build a rest api with spring security. I'm getting the 401 errors in the nginx logs.
Now I want to intercept and trace the username, password, request body and URL before the authentication when i send a post request via rest client.
I'm able to get the url as String url = httpRequest.getRequestURL().toString();
Could any one please let me know how can i get the username, password and request body from HttpServletRequest.

Below code worked for me to get the username and password from the httpRequest for the information sent from the rest client.
String header = httpRequest.getHeader("Authorization");
if ((header != null) && (header.startsWith("Basic "))) {
String base64Token = header.substring(6);
String token = new String(Base64.decodeBase64(base64Token.getBytes()));
String username = "";
String password = "";
int delim = token.indexOf(":");
if (delim != -1) {
username = token.substring(0, delim);
password = token.substring(delim + 1);
}
}

Related

PayPal API - (401) Unauthorized when requesting Access Token

I am trying to incorporate PayPal payments into our project, but I am failing at the moment hehe.
Basically, first step is to get the access token request and response, which I am trying to do with WebRequest, but it spits out 401 at me.
Following instructions from: https://developer.paypal.com/docs/integration/direct/make-your-first-call/
Here's the code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
WebRequest request = WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Credentials = new NetworkCredential("client_id", "secret");
request.PreAuthenticate = true;
string body = "grant_type=client_credentials";
byte[] buffer = Encoding.UTF8.GetBytes(body);
request.ContentLength = buffer.LongLength;
var reqStr = request.GetRequestStream();
reqStr.Write(buffer, 0, buffer.Length);
reqStr.Close();
WebResponse response = request.GetResponse();
Ofcourse, client_id and secret are replaced with real values in the code :)
Thank you for your help!
Figured it out thanks to: C# HttpWebRequest using Basic authentication
Turns out I was not using Basic Auth as intended by PayPal.
Oops :D
Hope someone finds this useful.

Issue using Insights Edge API

I am trying to get some insights data using Insights Edge API, but running into permissions issue:
Here is the code I am using:
string applicationId = "";
string applicationSecret = "";
string accountId = "";
System.Net.WebClient client = new System.Net.WebClient();
string accessToken = client.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=" + applicationId + "&client_secret=" + applicationSecret + "&grant_type=client_credentials").Replace("access_token=","");
System.Net.WebRequest req = System.Net.WebRequest.Create("https://graph.facebook.com/v2.4/act_"+accountId+"/insights?access_token=" + accessToken);
System.Net.WebResponse response = req.GetResponse();
using(System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
string s = sr.ReadToEnd();
Console.WriteLine(s);
}
I am getting the following JSON back:
{
"error": {
"message": "(#10) You do not have sufficient permissions to perform this action",
"type": "OAuthException",
"code": 10
}
}
Application in question was created under the same Facebook account as the ad account. What do I need to check in account/application settings to see if I have all the correct permissions to access Ad Insights API? The code will need to run in the service that doesn't require user intervention, is application access token the right way to access ad insight data in this case?

RestAssured oAuth2 http status code 401

I'm trying to implement integration test using RestAssured library and Spring MVC REST oAuth2 secured endpoint.
This is my test:
#Test
public void testCreateDecision() throws Exception {
File createDecisionJsonFile = ResourceUtils.getFile(getClass().getResource("/json/decisions/create-decision.json"));
// #formatter:off
final String createDecisionRequest = FileUtils.readFileToString(createDecisionJsonFile)
.replace("{{name}}", "Test decision name")
.replace("{{description}}", "Test decision description");
// #formatter:on
String accessToken = getAccessToken("user", "user");
// #formatter:off
given()
.auth()
.oauth2(accessToken, OAuthSignature.HEADER)
.body(createDecisionRequest)
.contentType("application/json; charset=UTF-8")
.when()
.post(format("http://localhost:%d/api/v1.0/decisions/create", port))
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("id", notNullValue())
.body("createDate", notNullValue());
// #formatter:on
}
The accessToken is valid but I'm continuously getting 401 http code.
What could be wrong with my code ?
I know this is an old post, but just wanted to document this in case someone else needed the answer.
I was able to implement using the following format:
First retrieve the token (in my case I did not store user tokens, jut got them before each test)
// we need to get the oauth token before we can perform the request
private void authenticateUser(String username, String password) {
String response =
given()
.parameters("username", username, "password", password,
"grant_type", "password", "scope", "read write",
"client_id", "clientapp", "client_secret", "123456")
.auth()
.preemptive()
.basic("clientapp","123456")
.when()
.post("/oauth/token")
.asString();
JsonPath jsonPath = new JsonPath(response);
accessToken = jsonPath.getString("access_token");
}
And them on the test I used the retrieved token:
#Test
public void testGetUserDefaultUserOwner() {
authenticateUser(testData.user1.getLogin(), "1");
User user =
given()
.auth().oauth2(accessToken)
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.expect()
.log().all()
.statusCode(HttpStatus.OK.value())
.when()
.get(USER_RESOURCE, testData.user1.getId())
.as(User.class);
assertThat(user).isEqualTo(testData.user1);
}
I am using Restassured and AssertJ for the tests, and SpringBoot with OAuth2 for the Rest APIs.
I have reimplemented my test using OAuth2RestTemplate:
ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setUsername("user");
resourceDetails.setPassword("user");
resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port));
resourceDetails.setClientId("clientapp");
resourceDetails.setClientSecret("123456");
resourceDetails.setGrantType("password");
resourceDetails.setScope(asList("read", "write"));
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);
auth2RestTemplate.setMessageConverters(asList(new MappingJackson2HttpMessageConverter()));
Assert.assertNotNull(auth2RestTemplate.getAccessToken());
DecisionRequest decisionRequest = new DecisionRequest(name, description, parentDecisionId);
auth2RestTemplate.postForObject(format("http://localhost:%d/api/v1.0/decisions/create", port), decisionRequest, Decision.class);
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved here.</p>
</body></html>

How to get Authenticated with spring security rest plugin in Grails

I'm using Grails version 2.4.3 . I am creating an application that supports RESTful APIs. Since access to these APIs should be authenticated , I tried out the Spring Security REST plugin. I checked out this example and what I could understand is , the /api/login controller is the authentication point which receives the user credentials in JSON format and after successful authentication it provides the acces token as response. I tried sending a POST request to /api/login/ with valid JSON data using the POSTMAN Rest Client. But it gives me the following error.
401 Unauthorized , Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.
I also tried using IntellijIDEA's REST Client but doesn't work.
Then i tried by sending AJAX Request to /api/login/ with valid JSON data
, but getting 401 on console. What is the problem here? Is this the correct login end point? How can i get authenticated using JQuery?
Try this
$.ajax({
url: " http://localhost:8080/AppName/api/login",
type: "POST",
crossDomain: true,
data: JSON.stringify({"username":"yourusername" , "password":"yourpassword"}),
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (response) {
console.log(response);
},
error: function (xhr, status) {
alert("error");
}
}) });
You can try this code for authentication,I am sending user id and password in request header you can try as you wish :-
inject following services:-
def springSecurityService
def authenticationManager
and use following code
def login = {
final String authorization = request.getHeader("Authorization");
if (authorization != null && authorization.startsWith("Basic")) {
boolean authResult = authenticateUser(authorization)
if (authResult) {
render response.status
} else {
render authFailed(response)
}
} else {
render authFailed(response)
}
}
protected boolean authenticateUser(String authorization) {
// Authorization: Basic base64credentials
def base64Credentials = authorization.substring("Basic".length()).trim();
byte[] credentials = base64Credentials.decodeBase64()
String actualCredential = new String(credentials)
// credentials format like username:password
final String[] values = actualCredential.split(":", 2);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(values[0], values[1]);
try {
def authentication = authenticationManager.authenticate(authRequest);
def securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
def session = request.session;
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}
catch (BadCredentialsException exception) {
return false
}
return true
}
protected HttpServletResponse authFailedResponse(HttpServletResponse response) {
response.setStatus(401)
response.setHeader("WWW-Authenticate", "Basic realm=\"nmrs_m7VKmomQ2YM3:\"")
return response;
}

What might cause errors validating verification code? (facebook oAuth from MVC3 issue)

I've recently started having trouble logging into my site using Facebook. I keep seeing this error message:
Facebook.FacebookOAuthException: (OAuthException) Error validating verification code.
There have been significant changes to the site and software; before I dig in to the changes, I'd like to eliminate some of the simple, common causes.
Could this be a firewall issue (the site is behind a firewall and not accessible from outside our network)? What are the most common causes for this error message?
Make sure your redirectUri parameter is the same as the redirecturi you used on https://www.facebook.com/dialog/oauth call.
For example, given an initial authentication request
using Facebook;
public ActionResult fbLogOn( string token, string returnUrl )
{
var oAuthClient = new FacebookOAuthClient( FacebookApplication.Current );
oAuthClient.RedirectUri =
new Uri( "http://" + "localhost:3434" + "/Home/fbOAuth" );
<... etc ...>
Make sure the handler for the facebook response sets the redirect URI to the exact same URI:
using Facebook;
public ActionResult fbOAuth(string code, string state )
{
FacebookOAuthResult oauthResult;
if (FacebookOAuthResult.TryParse( Request.Url, out oauthResult ))
{
string token = HttpUtility.UrlDecode( state );
if (oauthResult.IsSuccess)
{
var oAuthClient = new FacebookOAuthClient( FacebookApplication.Current );
oAuthClient.RedirectUri =
new Uri( "http://" + "localhost:3434" + "/Home/fbOAuth" );
dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken( code );
string accessToken = tokenResult.access_token;
<... etc ...>