HTTP header authentication not working with gradle publish - github

The following documentation describes how to use HTTP header authentication:
https://docs.gradle.org/current/userguide/declaring_repositories.html#sec:authentication_schemes
I did as described, answer: Received status code 401 from server: Unauthorized
publishing {
repositories {
maven {
url "my-url-does-not-matter-now"
credentials(HttpHeaderCredentials) {
name = "Authorization"
value = "token my-token"
}
authentication {
header(HttpHeaderAuthentication)
}
}
}
}
Interesting enough, if i change to password protected works.
publishing {
repositories {
maven {
url "my-url-does-not-matter-now"
credentials {
username "user"
password "my-token"
}
}
}
}
I can assume my url and token works.
Thoughts please? thanks in advance

Related

GraphQL query to GitHub failing with HTTP 422 Unprocessable Entity

I am currently working on a simple GitHub GraphQL client in NodeJS.
Given that GitHub GraphQL API is accessible only with an access token, I set up an OAuth2 request to grab the access token and then tried to fire a simple GraphQL query.
OAuth2 flow gives me the token, but when I send the query, I get HTTP 422.
Here below simplified snippets from my own code:
Prepare the URL to display on UI side, to let user click it and perform login with GitHub
getGitHubAuthenticationURL(): string {
const searchParams = new URLSearchParams({
client_id,
state,
login,
scope,
});
return `https://github.com/login/oauth/authorize?${searchParams}`;
}
My ExpressJs server listening to GitHub OAuth2 responses
httpServer.get("/from-github/oauth-callback", async (req, res) => {
const {
query: { code, state },
} = req;
const accessToken = await requestGitHubAccessToken(code as string);
[...]
});
Requesting access token
async requestToken(code: string): Promise<string> {
const { data } = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id,
client_secret,
code
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
);
return data.access_token;
}
Firing simple graphql query
const data = await axios.post(
"https://graphql.github.com/graphql/proxy",
{ query: "{ viewer { login } }"},
{
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
Do you guys have any clue?
Perhaps I am doing something wrong with the OAuth2 flow? As in most of the examples I found on the web, a personal token is used for this purpose, generated on GitHub, but I would like to use OAuth2 instead.
Thanks in advance for any help, I really appreciate it!
EDIT
I changed the query from { query: "query { viewer { login } }"} to { query: "{ viewer { login } }"}, nonetheless, the issue is still present.
I finally found the solution:
Change the URL from https://graphql.github.com/graphql/proxy to https://api.github.com/graphql, see here
Add the following HTTP headers
"Content-Type": "application/json"
"Content-Length"
"User-Agent"
Hope this will help others out there.

spring cloud contract - use the request's body as the response body

in spring cloud contract (v1.2.5) using this contract:
Contract.make {
description "update sthg"
request {
method PUT()
url value($(consumer('/path/to/sthg'),
producer(execute('somePutPathPath(0,\"xxx\")'))))
body(producer(
file('files/givens/my-body.json')
))
}
response {
status 200
headers {
contentType(applicationJson())
}
body(fromRequest().body())
}
}
I get an error when generating the tests
org.springframework.cloud:spring-cloud-contract-maven-plugin:1.2.5.RELEASE:generateTests failed:net.minidev.json.parser.ParseException: Unexpected character ({) at position 1. -> [Help 1]
but everything is fine if i use: body(someProp: fromRequest().body())
Contract.make {
description "update sthg"
request {
method PUT()
url value($(consumer('/path/to/sthg'),
producer(execute('somePutPathPath(0,\"xxx\")'))))
body(producer(
file('files/givens/my-body.json')
))
}
response {
status 200
headers {
contentType(applicationJson())
}
body(someProp: fromRequest().body())
}
}
How could I set the body response to be the request's body.
I solved this by using request.getBody() instead of : body(fromRequest().body())
body($(
c(request.getBody()),
p(file('some.json'))
))

spray authenticate directive returns different HTTP status codes

I am trying a basic authentication on post request in spray.io 1.3.2 using authenticate directive. My code looks following:
val route: Route = {
pathPrefix("ato") {
pathPrefix("v1") {
path("orders" / "updateStatus") {
post {
authenticate(BasicAuth(userPasswordAuthenticator _, realm = "bd ato import api")) {
user =>
entity(as[String]) {e =>
complete {
s"Hello $e "
}
}
}
}
}
}
}
}
def userPasswordAuthenticator(userPass: Option[UserPass]): Future[Option[String]] =
Future {
if (userPass.exists(up => up.user == ato_import_v1_usr && up.pass == ato_import_v1_pwd)) Some("ato_v1")
else None
}
This works perfectly fine, authorized Status Ok 200, unauthorized 401. However when the order of directives is changed as follows:
val route: Route = {
pathPrefix("ato") {
pathPrefix("v1") {
authenticate(BasicAuth(userPasswordAuthenticator _, realm = "bd ato import api")) {
user =>
path("orders" / "updateStatus") {
post {
entity(as[String]) {e =>
complete {
s"Hello $e "
}
}
}
}
}
}
}
}
I am getting Status 405, HTTP method not allowed for unauthorized access. I am not sure why that happens. From certain point it make sense, path is not matched because of missing credentials etc.
Could someone please clarify that?
The reason why I wanted to put authorization at v1 level is that I wanted to make every version protected by different password. Is there a way how to achieve that? What is the best practice in chaining directives?
I would like to follow DRY principle.
Thanks

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;
}

Codeigniter-restserver does not accept POST method CORS

I'm developing a REST API using Codeigniter-restserver for a mobile applications in Phonegap.
Since Phonegap loads index.html using file://, my API should support CORS. And I'm new to this CORS.
I've set headers in libraries/REST_Controller.php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept');
And I'm using Backbone.js.
Here is my Controller
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH.'/libraries/REST_Controller.php';
class Prop extends REST_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
function property_get()
{
...
}
function property_post()
{
...
}
function attach_image($file_type)
{
if($this->post($file_type) != ""){
save_base64_image($file_type,$this->post($file_type));
$this->email->attach($_SESSION[$file_type]);
}
}
function property_delete()
{
...
}
function share_post()
{
$email_id = $this->post('emailid');
$config['mailtype'] = "html";
$this->email->initialize($config);
$this->email->from('myid#gmail.com', 'mobile app');
$this->email->to($email_id);
$this->email->subject('subject');
$this->email->message('message');
if ( ! $this->email->send() )
{
$this->response("Internal server error.", 500);
}
else
{
$result = new stdClass();
$result->message = 'Email has been sent.';
$this->response($result, 200); // 200 being the HTTP response code
}
}
public function send_post()
{
var_dump($this->request->body);
}
public function send_put()
{
var_dump($this->put('foo'));
}
}
Here's my jQuery ajax call.
$.ajax( {
url: PMSApp.apiUrl + "/share/format/json",
type: 'post',
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.done(function(response) {
console.log(JSON.stringify(response));
})
.fail(function(response) {
console.log(JSON.stringify(response));
})
.always(function(response) {
console.log(JSON.stringify(response));
});
I'm able to access this /share/format/json API with POSTMAN, chrome extension, but not with file:// or localhost://.
EDIT:
I've also tried changing share_post() to share_gett(), It worked. But i need it in POST.
I'm stuck on this for the past 48 hours. Tried many solutions, but nothing helped me with this issue. Please help me.
Phonegap provides option to whitelist your webservice domain. It is set up the access origin in config xml
http://docs.phonegap.com/en/2.3.0/guide_whitelist_index.md.html
You have to start Chrome with Access-Control-Allow-Origin
This thread:
https://superuser.com/questions/384871/overriding-access-control-allow-origin-restriction-in-google-chrome
Check this tread:
Origin is not allowed by Access-Control-Allow-Origin