Swagger UI: pass custom Authorization header - asp.net-web-api

I'm using Swashbuckle and Swagger on an ASP.NET Web API. I'm trying to find a way to pass an Authorization header containing a Bearer token through Swagger UI. I've been searching around, but all the answers seem to point at this link.
However, this assumes that the content of the header is known upfront. I really need a way to change the header within Swagger UI (right before hitting the 'Try it out!' button), because the Bearer token expires every hour. Something similar to the way Postman allows you to add headers.
It seems like such a ridiculously simple problem, but what is the answer?

We ran into the same problem on our project. I also wanted to add the header parameters to the Swagger UI website. This is how we did it:
1. Define an OperationFilter class
OperationFilters are executed on every API operation every time you build Swagger. According to your code, operations will be checked according to your filters. In this example, we make the header parameter required on every operation, but make it optional on operations that have the AllowAnonymous attribute.
public class AddAuthorizationHeader : IOperationFilter
{
/// <summary>
/// Adds an authorization header to the given operation in Swagger.
/// </summary>
/// <param name="operation">The Swashbuckle operation.</param>
/// <param name="schemaRegistry">The Swashbuckle schema registry.</param>
/// <param name="apiDescription">The Swashbuckle api description.</param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation == null) return;
if (operation.parameters == null)
{
operation.parameters = new List<Parameter>();
}
var parameter = new Parameter
{
description = "The authorization token",
#in = "header",
name = "Authorization",
required = true,
type = "string"
};
if (apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
{
parameter.required = false;
}
operation.parameters.Add(parameter);
}
}
2. Tell Swagger to use this OperationFilter
In the SwaggerConfig, just add that the operation filter should be used as follows:
c.OperationFilter<AddAuthorizationHeader>();
Hope this helps you out!

Create a new operation filter that implements IOperationFilter.
public class AuthorizationHeaderOperationFilter : IOperationFilter
{
/// <summary>
/// Adds an authorization header to the given operation in Swagger.
/// </summary>
/// <param name="operation">The Swashbuckle operation.</param>
/// <param name="context">The Swashbuckle operation filter context.</param>
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
{
operation.Parameters = new List<IParameter>();
}
var authorizeAttributes = context.ApiDescription
.ControllerAttributes()
.Union(context.ApiDescription.ActionAttributes())
.OfType<AuthorizeAttribute>();
var allowAnonymousAttributes = context.ApiDescription.ActionAttributes().OfType<AllowAnonymousAttribute>();
if (!authorizeAttributes.Any() && !allowAnonymousAttributes.Any())
{
return;
}
var parameter = new NonBodyParameter
{
Name = "Authorization",
In = "header",
Description = "The bearer token",
Required = true,
Type = "string"
};
operation.Parameters.Add(parameter);
}
}
Configure the service in your Startup.cs file.
services.ConfigureSwaggerGen(options =>
{
options.OperationFilter<AuthorizationHeaderOperationFilter>();
});

You could do it in different ways depending on how you collect the Authorization header and whether you want the code to handle everything or if you want the user to be able to enter what ever Authorization header they want.
When I first tried this, I was able to show an Authorization header text in each endpoint's parameter field area where a user could type in an Authorization header but that was not what I wanted.
In my situation, I had to send a request to the /token endpoint with the user's cookie in order to get a valid Authorization token. So I did a mix of things to achieve this.
First in SwaggerConfig.cs I uncommented c.BasicAuth() to get the basic auth scheme into the API schema and I also injected a custom index.html page where I inserted an AJAX request in order to grab the Authorization token, using the user's cookie (index.html code shown below):
public static void Register() {
System.Reflection.Assembly thisAssembly = typeof(SwaggerConfig).Assembly;
System.Web.Http.GlobalConfiguration.Configuration
.EnableSwagger(c => {
...
c.BasicAuth("basic").Description("Bearer Token Authentication");
...
})
.EnableSwaggerUi(c => {
...
c.CustomAsset("index", thisAssembly, "YourNamespace.index.html");
...
});
}
Then head here to download the swashbuckle index.html which we will customize to insert an Authorization header.
Below I simply make an AJAX call to my /token endpoint with a valid cookie, get the Authorization token, and give it to swagger to use with window.swaggerUi.api.clientAuthorizations.add():
...
function log() {
if ('console' in window) {
console.log.apply(console, arguments);
}
}
$.ajax({
url: url + 'token'
, type: 'POST'
, data: { 'grant_type': 'CustomCookie' }
, contentType: 'application/x-www-form-urlencoded'
, async: true
, timeout: 60000
, cache: false
, success: function(response) {
console.log('Token: ' + response['token_type'] + ' ' + response['access_token']);
window.swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", response['token_type'] + ' ' + response['access_token'], "header"));
}
, error: function(request, status, error) {
console.log('Status: ' + status + '. Error: ' + error + '.');
}
});
I removed a few things from the AJAX call to make it more simple and obviously your implementation will probably be different depending on how you gather your Authorization token and stuff but that gives you an idea. If you have any specific issues or questions, let me know.
*Edit: Did not notice you actually did want the user to type in their Authorization header. In that case it is very easy. I used this post. Simply created the following class to do the work:
public class AddRequiredHeaderParameter : IOperationFilter {
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {
if (operation.parameters == null) {
operation.parameters = new List<Parameter>();
}
operation.parameters.Add(new Parameter {
name = "Foo-Header",
#in = "header",
type = "string",
required = true
});
}
}
Then added the class to my SwaggerConfig like so:
...
c.OperationFilter<AddRequiredHeaderParameter>();
...

In Swashbuckle 5 this is done in Startup.cs with the following file.
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "JWT Authorization header using the Bearer scheme."
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
},
new string[] {}
}
});
});

Related

Enable CORS for Web Api 2 and OWIN token authentication

I have an ASP.NET MVC 5 webproject (localhost:81) that calls functions from my WebApi 2 project (localhost:82) using Knockoutjs, to make the communication between the two projects I enable CORS. Everything works so far until I tried to implement OWIN token authentication to the WebApi.
To use the /token endpoint on the WebApi, I also need to enable CORS on the endpoint but after hours of trying and searching for solutions it is still now working and the api/token still results in:
XMLHttpRequest cannot load http://localhost:82/token. No 'Access-Control-Allow-Origin' header is present on the requested resource.
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
TokenConfig.ConfigureOAuth(app);
...
}
TokenConfig
public static void ConfigureOAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
AuthorizationProvider
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var appUserManager = context.OwinContext.GetUserManager<AppUserManager>();
IdentityUser user = await appUserManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
... claims
}
IdentityConfig
public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
{
// Tried to enable it again without success.
//context.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
var manager = new AppUserManager(new UserStore<AppUser>(context.Get<ApplicationDbContect>()));
...
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<AppUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
EDIT:
1. Important note is that opening the endpoint directly (localhost:82/token) works.
2. Calling the Api (localhost:82/api/..) from the webproject also works, so the CORS is enabled for WebApi.
I know your issue was solved inside comments, but I believe is important to understand what was causing it and how to resolve this entire class of problems.
Looking at your code I can see you are setting the Access-Control-Allow-Origin header more than once for the Token endpoint:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
And inside GrantResourceOwnerCredentials method:
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
This, looking at the CORS specifications, is itself an issue because:
If the response includes zero or more than one Access-Control-Allow-Origin header values, return fail and terminate this algorithm.
In your scenario, the framework is setting this header two times, and understanding how CORS must be implemented, this will result in the header removed in certain circumstances (possibly client-related).
This is also confirmed by the following question answer: Duplicate Access-Control-Allow-Origin: * causing COR error?
For this reason moving the call to app.UseCors after the call to ConfigureOAuth allows your CORS header to be set only once (because the owin pipeline is interrupted at the OAuth middleware, and never reaches the Microsoft CORS middleware for the Token endpoint) and makes your Ajax call working.
For a better and global solution you may try to put again app.UseCors before the OAuth middleware call, and remove the second Access-Control-Allow-Origin insertion inside GrantResourceOwnerCredentials.
Follow below steps and you will have your API working:
Remove any code like config.EnableCors(), [EnableCors(header:"*"....)] from your API.
Go to startup.cs and add below line
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
before
ConfigureAuth(app);
Uou will also need to install Microsoft.owin.cors package to use this functionality
Solving the problem without using app.UseCors()
I had the same problem. I used a Vue.Js client with axois to access my REST-API with cross-corps. On my Owin-Api-Server I was not able to add Microsoft.Owin.Cors nuget due to version conflicts with other 3rd party components. So I couldn't use app.UseCors() method but I solved it by using the middleware pipeline.
private IDisposable _webServer = null;
public void Start(ClientCredentials credentials)
{
...
_webServer = WebApp.Start(BaseAddress, (x) => Configuration(x));
...
}
public void Configuration(IAppBuilder app)
{
...
// added middleware insted of app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.Use<MyOwinMiddleware>();
app.UseWebApi(config);
...
}
public class MyOwinMiddleware : OwinMiddleware
{
public MyOwinMiddleware(OwinMiddleware next) :
base(next)
{ }
public override async Task Invoke(IOwinContext context)
{
var request = context.Request;
var response = context.Response;
response.OnSendingHeaders(state =>
{
var resp = (IOwinResponse)state;
// without this headers -> client apps will be blocked to consume data from this api
if (!resp.Headers.ContainsKey("Access-Control-Allow-Origin"))
resp.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
if (!resp.Headers.ContainsKey("Access-Control-Allow-Headers"))
resp.Headers.Add("Access-Control-Allow-Headers", new[] { "*" });
if (!resp.Headers.ContainsKey("Access-Control-Allow-Methods"))
resp.Headers.Add("Access-Control-Allow-Methods", new[] { "*" });
// by default owin is blocking options not from same origin with MethodNotAllowed
if (resp.StatusCode == (int)HttpStatusCode.MethodNotAllowed &&
HttpMethod.Options == new HttpMethod(request.Method))
{
resp.StatusCode = (int)HttpStatusCode.OK;
resp.ReasonPhrase = HttpStatusCode.OK.ToString();
}
}, response);
await Next.Invoke(context);
}
}
So I created my own middleware and manipulated the response. GET calls only needed the Access-Control-Allow headers whereas for OPTIONS calls I also needed to manipulate the StatusCode because axois.post() is calling first with OPTIONS-method before sending the POST. If OPTIONS return StatusCode 405, the POST will never be sent.
This solved my problem. Maybe this can help somebody too.

How to pass custom headers while calling a web api using Swagger(Swashbuckle)

We are using Swashbuckle to document our web apis and use it to test our web apis. I want to know how one can pass multiple custom headers with different values for each request using Swagger UI.
I have seen an answer like below in the internet to pass a header in Swagger UI but was unable to get my head around it. What's confusing is about the SwaggerExtensions file. What is the purpose of this file and why is there a mention of this file in the qualified name of the js file.
1.Add new file named “SwaggerExtensions”, then added new JS file named “onComplete.js”, you have to change the build action for this file to “Embedded Resource”.
2.Inside the file “onComplete.js” paste the following code:
$('#input_apiKey').change(function () {
var key = $('#input_apiKey')[0].value;
if (key && key.trim() != "") {
key = "Bearer " + key;
window.authorizations.add("key", new ApiKeyAuthorization("Authorization", key, "header"));
}
});
3.Open file “SwaggerConfig.cs” and inside the register method paste the code below:
SwaggerUiConfig.Customize(c =>
{
c.SupportHeaderParams = true;
c.InjectJavaScript(typeof(SwaggerConfig).Assembly, "AngularJSAuthentication.API.SwaggerExtensions.onComplete.js");
});
Swashbuckles implementation of swagger reads XML code comments to generate the required swagger specification. Unfortunately, if you require an authorization header (access token) to make requests, the XML code comments does not provide this info to Swashbuckle. You'll have to manually inject this new parameter during swagger specification generation.
Swashbuckle provides an interface called IOperationFilter to apply new parameters. Implementing this interface will look something like this.
public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
var isAuthorized = filterPipeline
.Select(filterInfo => filterInfo.Instance)
.Any(filter => filter is IAuthorizationFilter);
var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
operation.parameters.Add(new Parameter {
name = "Authorization",
#in = "header",
description = "access token",
required = true,
type = "string"
});
}
}
}
Inside your SwaggerConfig.cs file, add the following
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
c.SingleApiVersion("v1", "API").Description("An API ")
.TermsOfService("Some terms")
.Contact(cc => cc.Name("Team")
.Email("team#team.com"));
c.OperationFilter(() => new AuthorizationHeaderParameterOperationFilter()));
}
}
Swashbuckle suggest to use InjectJavaScript to accomplish this.
https://github.com/domaindrivendev/Swashbuckle#injectjavascript
I use the following code to add a bearer token for authorization in http header.
httpConfiguration
.EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API")) co
.EnableSwaggerUi(c =>
{
c.InjectJavaScript(containingAssembly, "ProjectName.SwaggerUIEnableBearerToken.js");
});
SwaggerUIEnableBearerToken.js
$(function () {
$('#input_apiKey').attr("placeholder", "bearer token");
$('#input_apiKey').off();
$('#input_apiKey').change(function () {
var token = this.value;
if (token && token.trim() !== '') {
token = 'Bearer ' + token;
var apiKeyAuth = new window.SwaggerClient.ApiKeyAuthorization("Authorization", token, "header");
window.swaggerUi.api.clientAuthorizations.add("token", apiKeyAuth);
}
}
});
})();
See more from this issue thread:
https://github.com/domaindrivendev/Swashbuckle/issues/222
You can add a parameter with SwaggerUI :
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("api_key", key, "header"));
I have stumbled across this question when trying to add a custom header containing some authentication information. This article suggests a way to accomplish this without injecting JavaScript (pure .NET approach) by providing a SecurityDefinition when configuring swagger integration:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1.0", new Info { Title = "Main API v1.0", Version = "v1.0" });
// Swagger 2.+ support
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
};
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(security);
});
This always to define a security token at API level or method level (some sort of log in) and this token will be used for all subsequent requests until logged out.

http basic auth with swashbuckle api documentation

could anyone know how could i integrate basic auth with swashbuckle api's documentation?
I saw that there's a basicAuth function in the swaggerconfig file:
c.BasicAuth("basic").Description("Basic HTTP Authentication");
What i've done:
uncommented the previous line but nothing changed!
does anyone have any idea what did i miss?
Thanks!
A minor improvement on #MarwaAhmad 's most excellent answer, is to check for null parameters (e.g. a simple GET or call with all params in the URL) . Also added details for Basic Auth.
Also, if you already use a global IAuthorizationFilter for say enforcing HTTPS, then you will want to change the more general
filter => filter is IAuthorizationFilter
to a specific
filter => filter is AuthorizeAttribute
public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance)
.Any(filter => filter is IAuthorizationFilter);
var allowAnonymous =
apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters?.Add(new Parameter
{
name = "Authorization",
#in = "header",
description = "Basic HTTP Base64 encoded Header Authorization",
required = true,
type = "string"
});
}
}
}
Here's how i did httpbasic authentication:
public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
var isAuthorized = filterPipeline
.Select(filterInfo => filterInfo.Instance)
.Any(filter => filter is IAuthorizationFilter);
var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
operation.parameters.Add(new Parameter {
name = "Authorization",
#in = "header",
description = "access token",
required = true,
type = "string"
});
}
}
}
The api's user shall write in the field value: basic [un:pw].tobase64.
References:
swashbuckle's issue 326
swashbuckle issue 2

ASP.NET WEB API 2 OWIN Authentication unsuported grant_Type

Hi I am trying to set up OAuth bearrer token authentication in my ASP.NET Web API 2 project.
I have two project one will be the WEB API Project and the other a SPA project.
Here is what I have done so far:
I have created the OWIN Startup class:
[assembly: OwinStartup(typeof(CodeArt.WebApi.App_Start.Startup))]
namespace CodeArt.WebApi.App_Start
{
public class Startup
{
static Startup()
{
PublicClientId = "self";
UserManagerFactory = () => new UserManager<UserModel>(new UserStore<UserModel>());
OAuthOptions = new OAuthAuthorizationServerOptions {
TokenEndpointPath = new PathString("/Token"),
Provider = new OAuthAuthorizatonServer(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static Func<UserManager<UserModel>> UserManagerFactory { get; set; }
public static string PublicClientId { get; private set; }
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalBearer);
app.UseOAuthBearerTokens(OAuthOptions);
}
}
I have configured Web API to use only bearer token authentication:
private static void ConfigureBearerTokenAuthentication(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));
}
I have configured WEB API to support CORS:
private static void ConfigureCrossOriginResourseSharing(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
I have created the OAuthAuthorizationServerProvider class.From this class I only managed to make my code call this method:
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
if(context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
The if condition inside of it always gets executed.
On my spa project I have the following:
This is my viewModel:
var vm = {
grant_type: "password",
userName: ko.observable(),
password: ko.observable()
};
When the login button gets clicked I call this function:
var http = {
post:function(url, data) {
return $.ajax({
url: url,
data: data,
type: 'POST',
contentType: 'application/json',
dataType: 'jsonp'
});
}
}
function loginClick() {
var model = ko.mapping.toJS(vm.loginModel);
var rez = $.param(model);
http.post("http://localhost:3439/Token", rez)
.done(function (data) {
console.log(data);
})
.fail(function(eror, stuff, otherstuff) {
console.log(eror);
console.log(stuff);
console.log(otherstuff);
});
}
My first attempt I have set the post calls dataType to json and I got this errors:
OPTIONS ...:3439/Token 400 (Bad Request) jquery.js:7845
OPTIONS ...:3439/Token No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'...:3304' is therefore not allowed access.
jquery.js:7845
XMLHttpRequest cannot load ...3439/Token. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '...3304' is therefore not allowed
access.
The 3 dots represent http://localhost.
The second time arround I set it datatype to jsonp and I got back an error that stated unsupported "unsupported_grant_type".
Both calls make it to ValidateClientAuthentication that I mentioned above but they are both sent back as a failed request.
Now I am guessing that the problem is more related to how I am sending data instead of the grand_type because the SPA template in Visual Studion set's the grant type to grant_type: "password" like I did.
Also I have read that I have to serialize the data not send it in json in order for this to work here is the exact json serialized data that get's sent:
"grant_type=password&userName=aleczandru&password=happynewYear&moduleId=models%2FappPostModels%2FloginModel"
The model id property get's set to all my object in my SPA template by Durandal Framework.
Can anyone tell me what I am doing wrong I have been trying to figure this out for the last two days?
Add the following line of code to GrantResourceOwnerCredentials, which will add the header to the response.
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
for more information refer to:
web-api-2-0-cors-and-individual-account-identity
Like Robin Karlsson said, you should use:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
in your Startup configuration.
And make sure it's the only cors statement (don't mix them) and the first statement in your Startup.

Forms validation in Nancy not working with AJAX login requests

I'm trying to implement an extremely simple spike using Nancy as an alternative to ASP.NET MVC.
It should take a username (no password) and provide meaningful error messages on the same login page without requiring a refresh. If login was successful, the response includes the URL to navigate to.
The POCO for the response looks like this:
public class LoginResponseModel
{
public bool IsSuccess { get; set; }
public string RedirectUrl { get; set; }
public string ErrorMessage { get; set; }
}
The JS handler for the login request:
$.ajax({
url: '/login',
type: "POST",
data: { UserName: username }
}).done(function (response) {
if (response.IsSuccess) {
showSuccess();
document.location.href = response.RedirectUrl;
return;
}
showError(response.ErrorMessage);
}).fail(function (msg) {
showError("Unable to process login request: " + msg.statusText);
});
The problem I'm having is with Nancy's Forms-based authentication. I've walked through half a dozen different tutorials which all more or less do the same thing, as well as gone over the Nancy authentication demos. The one thing they all have in common is that they rely on the LoginAndRedirect extension method. I don't want to return a redirect. I want to return a result of the login attempt and let the client handle the navigation.
The IUserMapper implementation I'm using:
public class UserMapper : IUserMapper
{
public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
{
// Don't care who at this point, just want ANY user...
return AuthenticatedUser {UserName = "admin"};
}
}
The relevant part of my LoginModule action:
var result = _userMapper.ValidateUser(input.AccessCode);
if (result.Guid != null) this.Login(UserMapper.GUID_ADMIN, expiry);
return Response.AsJson(result.Response);
but for subsequent requests Context.CurrentUser is always null.
If I add the following method to the Nancy.Demo.Authentication.Forms sample it reproduces the behaviour I'm seeing in my own project, leading me to believe LoginWithoutRedirect doesn't work how I expected.
Get["/login/{name}"] = x =>
{
Guid? userGuid = UserDatabase.ValidateUser(x.Name, "password");
this.LoginWithoutRedirect(userGuid.Value, DateTime.Now.AddYears(2));
return "Logged in as " + x.Name + " now <a href='~/secure'>see if it worked</a>";
};
The problem turns out to be that Context.CurrentUser with FormsAuthentication is dependent upon a cookie which isn't set if you don't return the NancyModule.Login() response.
var result = _userMapper.ValidateUser(input.AccessCode);
if (result.IsSuccess) {
this.LoginWithoutRedirect(result.Guid);
}
return Response.AsJson(result);
In this example, the LoginWithoutRedirect call returns a Response object with the cookie set. To handle this in an Ajax scenario I've had to add a AuthToken property to the LoginAjaxResponse class, then pass the cookie like so:
var result = _userMapper.ValidateUser(input.AccessCode);
var response = Response.AsJson(result);
if (result.IsSuccess) {
var authResult = this.LoginWithoutRedirect(result.Guid);
result.AuthToken = authResult.Cookies[0].Value;
}
return Response.AsJson(result);
On the client, the Ajax response handler changes to (assuming use of jQuery cookie plugin:
$.ajax({
url: '/login',
type: "POST",
data: { UserName: username }
}).done(function (response) {
if (response.IsSuccess) {
showSuccess();
$.cookie("_ncfa", response.AuthToken); // <-- the magic happens here
document.location.href = response.RedirectUrl;
return;
}
showError(response.ErrorMessage);
}).fail(function (msg) {
showError("Unable to process login request: " + msg.statusText);
});
The AuthToken is the GUID which has been encrypted and base64-encoded. Subsequent requests with this.RequiresAuthentication() enabled will first check for this auth token cookie.
If no "_ncfa" cookie is present,the UserMapper's GetUserFromIdentifier() is never called.
If the value in Context.Request.Cookies["_ncfa"] does not result in a valid GUID when base64-decoded and decrypted, GetUserFromIdentifier() is never called.
If GetUserFromIdentifier() isn't called, Context.CurrentUser is never set.
If you want the source for a working example it's on GitHub.
LoginAndRedirect is only one option, there are equivalent methods for not redirecting (LoginWithoutRedirect), or one that picks up on whether it's an AJAX request and handles it appropriately (Login). The same applies to logging out.
This is all covered, in detail, in the documentation.

Resources