I'm trying to implement swagger into my Asp.Net Web API, and i'm running into a problem.
I'm using the password resource owner flow, and i'm having to add a work around in order to do this, which is covered in the following stack overflow question :-
Swagger/Swashbuckle: OAuth2 with Resource Owner Password Credentials Grant
I've got everything working, the Bearer token is added via javascript to the request header in the current browser window, but the api calls to the controller methods requiring authorization are still return "401 - Authorization Failed".
Here is the JavaScript that gets the bearer token and adds the header :-
$('#input_apiKey').change(function () {
var key = $('#input_apiKey')[0].value;
var credentials = key.split(':'); //username:password expected
$.ajax({
url: "http://localhost:42291/token",
type: "post",
contenttype: 'x-www-form-urlencoded',
data: "grant_type=password&username=" + credentials[0] + "&password=" + credentials[1],
success: function (response) {
var bearerToken = 'Bearer ' + response.access_token;
window.swaggerUi.api.clientAuthorizations.add('Authorization', new window.SwaggerClient.ApiKeyAuthorization('Authorization', bearerToken, 'header'));
window.swaggerUi.api.clientAuthorizations.remove('api_key');
alert("Login Succesfull!");
},
error: function (xhr, ajaxoptions, thrownerror) {
alert("Login failed!");
}
});
});
The Curl in the response in Swagger is :-
curl -X GET --header "Accept: application/json" --header "Authorization: Bearer NqlSG-WyTx2zkYE8xFklGyZWlQDZdsCKZBHruEXvX47N7PAzw4-jZ4eH5D0yFzQTXj13RwKFFt1rUZt2fzWj1vR5UR87wdlKC3YvsTojYV4-3DsWwY7qYRfiKPuM0j09c3X5lnrtlBVJ1rBRUH0TLjfw_yGxgoLBwOJl9xyC1YWNoPOe2nzL4lMOHodAnMem0IBMJmUo3Rt575tnWAbBsQXWhlImDIxCZXvkZdJtlXfIfBSUdY9gfRWL0ZjKbf7m2-yLzH0gpMAMuKaADmJlIudJc0d4SP1Nn2Kh2HuVH8CX4QgZuu4egl9N6rY2smorP2vBSC4_dC4CpmYYzOTu2wUnUhHDY2Q6NWl377ijDKwZLcW9jtD-2tBiEGmFuRV0mVGnh0zc4w9Ao9jPCdtrbSyGitgloBW-UG2bfyao3eE" "http://localhost:42291/api/v1/claims"
I cant see anything wrong with this at all.
I've then used Postman to call the exact same URL call, using the same access token that was generated in the javascript call...
Guess what... it works fine.
EDIT
I've tried removing the authorization attribute from the controller, so that i can check the request as it hits the controller method.
looking in the request headers, the Authorization property is null.
Not sure why this is. the CURL suggests its been placed into the request.
EDIT 2
Ive included my Security Definitions:-
"securityDefinitions": {
"oauth2": {
"type": "oauth2",
"description": "OAuth2 Password Grant",
"flow": "password",
"tokenUrl": "http://localhost:42291/token",
"scopes": {}
}
}
EDIT 3 The cURL displayed in the Swagger UI for this api call, when exposed through cURL directly at the command line works without issue.
Now I'm completely confused.
See Question&Answers more detail:os