Spring oauth2 Authorization provider - java

I am new to Oauth, I have application with Spring Oauth2 with xml
configuration. Have taken reference from
http://www.beingjavaguys.com/2014/10/spring-security-oauth2-integration.html
So the URL below to get the token is
http://localhost:8080/SpringRestSecurityOauth/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=beingjavaguys&password=spring#java
It gives the token reseponse.
So here in request url the client_id is hardcoded inside xml file.And I want to send the clientId,grantType at run time.
What things need to be taken care of here.

Normally you would send the client_id/client_secret in a header.
OAuth2 is only secure if https is used as there are secret data transmitted.
Here an example (angularjs):
auth = 'Basic ' + window.btoa(client_id + ':' + client_secret);
$http.defaults.headers.common.Authorization = auth;
$http.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
grantparam= 'grant_type=password&username='+loginData.username + '&password=' + loginData.password;
$http.post('https://localhost:8123/oauth/token?'+grantparam)
here in curl from postman:
curl -X POST -H "Accept: application/json" -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic 111111111111111" -H "Cache-Control: no-cache" -H "Postman-Token: 11111111-111111111111111" "https://localhost:8443/sf/api/oauth/token?grant_type=password&username=11111111111&password=**********"

Related

Adding an authentication token to header in Restlet

I am trying to make an API call using Restlet in java however when I run my code I get an org.restlet.resource.ResourceException: Unauthorized (401) - The request requires user authentication
The format for the API call is as follows for shell: curl "<api_url>" \ -H "Authorization: Bearer <api_token_here>"
However I am unsure how to add this authorization header in Restlet, as you are not able to add the header using .getRequest().getHeaders().add();
Additionally I have tried to set a challenge response however this also does not appear to work.
API = new ClientResource(RequestURL);
API.setProtocol(Protocol.HTTPS);
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.CUSTOM);
AuthHeader.setRawValue("Authorization: Bearer " + APIKey);
API.getRequest().setChallengeResponse(AuthHeader);
API.get();
I appear to have solved the issue with the following code:
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
AuthHeader.setRawValue(APIKey);
AuthHeader.setIdentifier("Bearer");
API.setChallengeResponse(AuthHeader);

How to accept json, xml, x-www-form-urlencoded in openapi driven spring boot application?

I'm implementing a petstore server in spring using the gradle plugin to generate classes for the API:
https://github.com/swagger-api/swagger-petstore/blob/swagger-petstore-v3-1.0.5/src/main/resources/openapi.yaml
An example for such a generated API code is
...
public interface UserApi {
...
#PostMapping(
value = "/user",
produces = { "application/json", "application/xml" },
consumes = { "application/json", "application/xml", "application/x-www-form-urlencoded" }
)
default ResponseEntity<User> createUser(#ApiParam(value = "Created user object" ) #Valid #RequestBody(required = false) User user) {
....
For a minimal example I don't even overwrite the above method.
With springdoc I can create a swagger ui page at http://localhost:8080/swagger-ui.html that is generated from the code.
There, I can generate curl requests for all media types offered y the api:
curl -X POST "http://localhost:8080/user" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"id\":0,\"username\":\"string\",\"firstName\":\"string\",\"lastName\":\"string\",\"email\":\"string\",\"password\":\"string\",\"phone\":\"string\",\"userStatus\":0}"
curl -X POST "http://localhost:8080/user" -H "accept: application/json" -H "Content-Type: application/xml" -d "<?xml version=\"1.0\" encoding=\"UTF-8\"?><User>\t<id>0</id>\t<username>string</username>\t<firstName>string</firstName>\t<lastName>string</lastName>\t<email>string</email>\t<password>string</password>\t<phone>string</phone>\t<userStatus>0</userStatus></User>"
curl -X POST "http://localhost:8080/user" -H "accept: application/json" -H "Content-Type: application/x-www-form-urlencoded" -d "id=0&username=string&firstName=string&lastName=string&email=string&password=string&phone=string&userStatus=0"
The first(json) works, but for xml and x-www-form-urlencoded
I get:
{"timestamp":"2020-10-19T22:42:43.215+00:00","status":415,"error":"Unsupported Media Type","message":"","path":"/user"}
That response code is not in the generated default implementation, it must be thrown in the steps before.
There are similar questions already on stackoverflow, but through openapi I cannot just leave out annotations. Is there a way for me to implement a request accepting all three media types using openapi and spring boot?

wiremock how to get post data

i'm trying to get data from the post does any one try
{
"name":"sasha",
"age":"15",
"country":"italy"
}
I will like to get the value sash from the post, any ideas?
only find to reply...
http://wiremock.org/docs/request-matching/
buy I don't want to reply, I want the data.
I would like something linke this:
String name = wiremock.withRequestBody(name());
print name -> sasha
something like this:
Body postBody = aResponse().withBody(matching("[?(#.name]"));
I'm trying to get data from the POST like curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d "{'json':{'name':'sasha'}}" 127.0.0.1:8080/to/post I want to get sasha

Java REST API that uses OpenAM token to determine user?

I am having trouble being able to validate a users token with OpenAM. Particularly what type of Agent I should create. Is there anyone that can recommend a solution?
Essentially the REST API will read the users OpenAM tokenid and validate the token with OpenAM which then will return data which contains a username. That username can be used in the REST API method to identify who is accessing the method.
Even more simplified is how can I use a OpenAM token to get the OpenAM user info.
Thanks!
You can use the following endpoints:
Authenticate user:
curl --request POST --header "X-OpenAM-Username: demo" \
--header "X-OpenAM-Password: changeit" \
--header "Content-Type: application/json"
"http://openam.example.com:8080/sso/json/authenticate"
{"tokenId":"AQIC5wM2LY4SfcyTReB5nbrLt3QaH-7GhPuU2-uK2k5tJsA.*AAJTSQACMDEAAlNLABMyOTUxODgxODAwOTE0MTA4NDE3*","successUrl":"/sso/console"}
Validate token:
curl --request POST \
--header "Content-Type: application/json" \
"http://openam.example.com:8080/sso/json/sessions/AQIC5wM2LY4SfczadxSebQWi9UEyd2ZDnz_io0Pe6NDgMhY.*AAJTSQACMDEAAlNLABM3MTMzMTYwMzM1NjE4NTE4NTMx*?_action=validate"
{"valid":true,"uid":"demo","realm":"/"}
Get profile attributes:
curl --request GET \
--header "iPlanetDirectoryPro: AQIC5wM2LY4SfczadxSebQWi9UEyd2ZDnz_io0Pe6NDgMhY.*AAJTSQACMDEAAlNLABM3MTMzMTYwMzM1NjE4NTE4NTMx*" \
"http://openam.example.com:8080/sso/json/users/demo"
{"username":"demo","realm":"/","uid":["demo"],"userPassword":["{SSHA}cIgTNGHWd4t4Ff3SHa6a9pjMyn/Z3e3EOp5mrA=="],"sn":["demo"],"createTimestamp":["20160406210602Z"],"cn":["demo"],"givenName":["demo"],"inetUserStatus":["Active"],"dn":["uid=demo,ou=people,dc=example,dc=com"],"objectClass":["devicePrintProfilesContainer","person","sunIdentityServerLibertyPPService","inetorgperson","sunFederationManagerDataStore","iPlanetPreferences","iplanet-am-auth-configuration-service","organizationalperson","sunFMSAML2NameIdentifier","oathUser","inetuser","forgerock-am-dashboard-service","iplanet-am-managed-person","iplanet-am-user-service","sunAMAuthAccountLockout","top"],"universalid":["id=demo,ou=user,dc=openamcfg,dc=example,dc=com"]}
I ended up going with with idFromSession:
curl --request POST \
--header "iplanetdirectorypro: AQIC5wM2LY4SfczUFNs-TJwFrCVAKgR0NulIAyNaIkQmjis.*AAJTSQACMDEA
AlNLABQtNTQ3NDE2Njc5ODk4MjYzMzA2MQ..*" \
--header "Content-Type: application/json"
http://openam.example.com:8080/openam/json/users?_action=idFromSession
Then in my java REST API method I used:
String httpsURL = "https://openam.example.com:8080/openam/json/users?_action=idFromSession";
URL url = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
//add request headers
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
// Add session token as header
con.setRequestProperty("iplanetdirectorypro", "AQIC5wM2LY4SfczUFNs-TJwFrCVAKgR0NulIAyNaIkQmjis.*AAJTSQACMDEA
AlNLABQtNTQ3NDE2Njc5ODk4MjYzMzA2MQ..*");
// Send post request
con.setDoOutput(true);
// Read output
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
Based the HTTP POST off of: https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
don't you need cookies to be set ..
Response fieldResponse = given().auth().oauth2( oAuthLogin.getToken())
.config(new RestAssuredConfig().
decoderConfig(
new DecoderConfig("UTF-8")
).encoderConfig(
new EncoderConfig("UTF-8", "UTF-8")
))
.header("iplanetDirectoryPro", oAuthLogin.getToken())
.header("Content-Type", "application/json")
// .contentType("application/json")
.body(myRequest).with()
.when()
.post(dataPostUrl)
.then()
.assertThat()
.log().ifError()
.statusCode(200)
.extract().response();
is failing as bad request 400.Same content header is working in postman.
Only difference i see is cookie.enter image description here
Working as per postman
Not working one which used restassured framework enter image description here

Curl not working for HTTP Post to Spring-data-rest RequestMapping

I have a RequestMapping setup in a spring #Controller and I am unable to correctly send a CURL request to it. I keep getting a HTTP 400 return code when trying to send various ways. I am not sure what is setup incorrectly.
Here is the request
curl -v -X POST localhost:8082/api/registerDevice -d '{"serial":"FA541YJ05065"}' -H "Content-Type:application/json;charset=UTF-8"
Here is the output
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying ::1...
* Connected to localhost (::1) port 8082 (#0)
> POST /api/registerDevice HTTP/1.1
> Host: localhost:8082
> User-Agent: curl/7.49.0
> Accept: */*
> Content-Type:application/json;charset=UTF-8
> Content-Length: 23
>
* upload completely sent off: 23 out of 23 bytes
< HTTP/1.1 400 Bad Request
< Server: Apache-Coyote/1.1
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Thu, 16 Jun 2016 02:48:50 GMT
< Connection: close
<
{"timestamp":1466045330556,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Could not read document: Unexpected character (''' (code 39)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream#3bae0839; line: 1, column: 2]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream#3bae0839; line: 1, column: 2]","path":"/api/registerDevice"}* Closing connection 0
Spring RequestMapping
#RequestMapping(value = "registerDevice", method = RequestMethod.POST)
public ResponseEntity<String> registerDevice(#RequestBody Map<String, Object> payload) throws Exception {
Update
As mentioned below it was an issue with escaping the quotes and related to windows. The same CURL command worked fine on centos.
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "{"""serial""":"""FA541YJ05065"""}" http://localhost:8082/api/deregisterDevice
On Centos
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"serial":"FA541YJ05065"}' http://localhost:8082/api/registerDevice
I suspect that you end up sending ' at the start of the json. You can try using double quotes around the json and escaping them in it.
See also
curl -v -X POST localhost:8082/api/registerDevice -d "{\"serial\":\"FA541YJ05065\"}" -H "Content-Type:application/json;charset=UTF-8"
The only reason behind this is that fact that your request is not formatted correctly
Check out this Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how to get it right once for all? for more information.

Categories

Resources