Swagger/Swashbuckle: OAuth2 with Resource Owner Password Credentials Grant
OK, I solved it like this:
Add a JavaScript completion-handler to swagger:
config
.EnableSwagger(c => {
//do stuff
})
.EnableSwaggerUi(c => {
c.InjectJavaScript(typeof(Startup).Assembly, "MyNamespace.SwaggerExtensions.onComplete.js");
});
Take username:password from the API_KEY textbox:
$('#input_apiKey').change(function () {
var key = $('#input_apiKey')[0].value;
var credentials = key.split(':'); //username:password expected
$.ajax({
url: "myURL",
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.authorizations.add('key', new ApiKeyAuthorization('Authorization', bearerToken, 'header'));
},
error: function (xhr, ajaxoptions, thrownerror) {
alert("Login failed!");
}
});
});
Thank you @Dunken. Your answer almost solve my problem, but to make it work with latest Swashbuckle version I had to change it a bit like this
$('#explore').off();
$('#explore').click(function () {
var key = $('#input_apiKey')[0].value;
var credentials = key.split(':'); //username:password expected
$.ajax({
url: "yourAuthEndpoint",
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 SwaggerClient.ApiKeyAuthorization('Authorization', bearerToken, 'header'));
window.swaggerUi.api.clientAuthorizations.remove("api_key");
alert("Login successfull");
},
error: function (xhr, ajaxoptions, thrownerror) {
alert("Login failed!");
}
});
});