Find out which federated partner issued token to WIF - asp.net

I have an application that uses the Windows Identity Foundation to enable federated single-sign-on from multiple partners (let's call them Org1, Org2, Org3, etc). My WIF configuration, therefore, contains thumbprints of all the partners' certificates - the config looks like this (irrelevant parts omitted for brevity):
<system.identityModel>
<identityConfiguration>
<issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry">
<trustedIssuers>
<add name="Org1" thumbprint="...certificate1..." />
<add name="Org2" thumbprint="...certificate2..." />
<add name="Org3" thumbprint="...certificate3..." />
</trustedIssuers>
</issuerNameRegistry>
</identityConfiguration>
However, I don't understand how to determine which of the certificates was actually used when an incoming token was validated. That is, how do I know whether it was Org1, Org2 or Org3 that has sent me the token? I.e., in the following code:
var authModule = FederatedAuthentication.WSFederationAuthenticationModule;
var request = new HttpRequestWrapper(Request);
if (authModule.CanReadSignInResponse(request, true))
{
var principal = Thread.CurrentPrincipal;
var message = authModule.GetSignInResponseMessage(request);
var token = authModule.GetSecurityToken(request) as SamlSecurityToken;
//???
}
... How can I use the principal/message/token variables (or perhaps some other method entirely) to determine whether it was Org1, Org2 or Org3 that has sent me the token? I know about token.Assertion.Issuer, but this seems to come straight from the token, so it seems like e.g. Org1 can issue a token listing Org2 as the issuer, thus resulting in an impersonation attack. Is there a way to identify the issuing organization securely, based on which certificate was used for token validation?

I managed to find 2 solutions:
METHOD 1:
Create a custom IssuerNameRegistry that derives from System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, and set it as your name registry (e.g. <issuerNameRegistry type="MyNamespace.MyConfigurationBasedIssuerNameRegistry, My.Assembly.Name">).
In your custom registry, override the GetIssuerName overload that takes both a token and a string (which is the token's issuer according to the token itself).
In this override, call the base GetIssuerName method, and you will get back the name property of the <add thumbprint="..." name="..."> statement for the certificate that was actually used to verify the token signature.
At this point, you have all the information you need (who the token claims to be, and who it is actually from). Compare the two, and return null if the token is impersonated (this will cause WIF to reject the token), or return what you got from the base method otherwise.
If your name property in <add> statements is always the intended token issuer URL, then all this becomes very easy:
class ValidatingConfigurationBasedIssuerNameRegistry : ConfigurationBasedIssuerNameRegistry
{
public override string GetIssuerName(SecurityToken securityToken, string requestedIssuerName)
{
var configuredName = base.GetIssuerName(securityToken, requestedIssuerName);
return (configuredName == requestedIssuerName) ? configuredName : null;
}
}
METHOD 2:
As stated in the answers here, you can get to the Claims on Thread.CurrentPrincipal as ClaimsPrincipal, and each Claim has an Issuer property. It turns out that this property will always be set to the name property in the <add thumbprint="..." name="..."> statement for the certificate that was actually used to verify the token signature.
This is a bit inconvenient - if you're processing a WS-Federation sign-in response, there's no way of knowing where this particular response's token came from - you're looking at the current Identity where the claims could potentially come from multiple sources. But I think in most realistic scenarios this should be sufficient.

Related

Asp.net core 2 AuthenticationProperties storing jwt tokens

I am trying to get a better understanding of how jwt tokens are stored (id, access, refresh). When you add OpenIdConnect, one of the options you can set is saving tokens. With below configuration, whenever the user logs in, the jwt tokens are generated (without having to have a separate call to the authorization endpoint to retrieve tokens).
.AddOpenIdConnect("Test", options => {
options.SaveTokens = true;
}
From what I have read, they are saved in the AuthenticationProperties collection returned along with the ClaimsPrincipal. You can retrieve them via HttpContext.GetTokenAsync.
Example below:
var accessToken = await HttpContext.GetTokenAsync("access_token");
I am trying to understand more about how these values are stored and retrieved. I know that the claimsprincial is a collection of identities / claims associated with a user. But how exactly are authentication properties set? How can I access the collection of authentication properties individually? Is there a class / interface I can use to get direct access to the class properties? I didn't see anything about authentication properties in the ClaimsPrincial class.
Also, as the access token is stored in the authentication properties, is the only way to update the value is to re-authenticate (i.e. challenge the user to login again)? How can I update the value? Or would it be better off extracting the value is storing it elsewhere to update?
I have been looking into this a bit myself as well. The OpenID Connect middleware seems to usually persist data into a signed cookie via a second cookie authentication scheme, specified by the SignInScheme option. Extending your example from before with an explicitly configured example:
.AddOpenIdConnect("Test", options => {
options.SignInScheme = "MyCookieScheme";
options.SaveTokens = true;
}
This example implies that a cookie authentication scheme has also been set up with a call like this:
.AddCookie("MyCookieScheme")
From the documentation comments on SignInScheme:
Gets or sets the authentication scheme corresponding to the middleware responsible of persisting user's identity after a successful authentication. This value typically corresponds to a cookie middleware registered in the Startup class. When omitted, Microsoft.AspNetCore.Authentication.AuthenticationOptions.DefaultSignInScheme is used as a fallback value.
(Note that this property actually comes from a RemoteAuthenticationOptions class that OpenIdConnectOptions extends)
Tracing what happens in default setup scenarios where you don't explicitly give a cookie authentication scheme is a bit tricky but I imagine it sets one up by default, or relies on one being there. Also, I guess that in theory, any other type of authentication scheme could be used for this persistence (e.g. your own JWT issuing and signing scheme), but I have not seen any examples of this.
As for what is actually stored in the cookie and how it gets put there by the OpenID Connect middleware, you would probably have to do a lot of digging through all of the code to work that out for sure - the specifics of all this low-level middleware doesn't seem to have been documented much yet. All I know for sure is that the DataProtection middleware is involved in encrypting the contents of the cookie.
You could look into decrypting the cookie itself to see what's there - see the answers here: How to manually decrypt an ASP.NET Core Authentication cookie?
(oh and for the record, all these examples are based off ASP.NET Core v2.0)
Another option is to use TokenValidationParameters.SaveSigninToken
From source code
if (validationParameters.SaveSigninToken)
identity.BootstrapContext = jwtToken.RawData;
It will store the original token in the BoostrapContext property of the current identity.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddJwtBearer(options =>
{
options.TokenValidationParameters.SaveSigninToken = true;
});
}
}
Then access the identity of the current user
((ClaimsIdentity)this.User.Identity).BoostrapContext // => original JWT token

C#/OWIN/ASP.NET: can I *manually* generate and get a valid bearer token string in my API code?

I am using the OWIN OAuthAuthorizationServer library in an OWIN ASP.NET C# web API to generate and process bearer tokens.
Right now, I have a single endpoint (which you set in the OAuthAuthorizationServerOptions struct) that accepts the grant_type, username and password fields from the frontend. I created a provider class that performs the validation, and then calls context.Validated() or context.SetError() accordingly. The middleware then handles generating the token and returning it to the user, and also "takes over" the login endpoint, doing all the work internally.
Now, I am adding a new feature to my API where the user can change their "role" (e.g. an admin can set themselves as a regular user to view the results of their work, a user can select among multiple roles, etc.) Since I already handle this through the bearer token (I store the user's role there and all my endpoints use the bearer token to determine the current role), I now have a reason to update the contents of the bearer token from the API backend.
What I'm looking to do is to allow the frontend to call an endpoint (e.g. api/set_role) that will accept a parameter. The user requests a certain role, and their current bearer token would accompany the request. The server then would check if the user in question is allowed to use that specific role and, if so, would generate a new token and return it to the user in the response body. The frontend would then update its token in local storage. Or, of course, if the user is not permitted to switch to that role, the backend would return an appropriate error and the frontend would react accordingly.
To do this I basically want to be able to manually generate a token. Similar to how I use identity.AddClaim() in my login provider, I'd like to be able to do that at any arbitrary position within the API's code. The method would take responsibility for transferring over any necessary existing information (e.g. the user's username) into the new token, since it already has the existing one.
Pseudocode for what I want:
if (!userCanUseRole(requestedRoleId)) return Request.CreateErrorResponse(...);
// we have a struct containing parsed information for the current token in the variable cToken
bearerToken newToken = new bearerToken();
newToken.AddClaim(new Claim("user", cToken.user));
newToken.AddClaim(new Claim("role", requestedRoleId));
string tokenToReturnToFrontend = newToken.getTokenString(); // string suitable for using in Authorization Bearer header
return Request.CreateResponse(new StringContent(tokenToReturnToFrontend));
I am not too familiar with "refresh" tokens, but the only way I am using them right now is extending token expiration. To that end the frontend explicitly requests a refresh token and provides its own, which the backend simply copies to a new token and edits the expiry time. The problem with this is that there's a single method for getting a refresh token, and since I have now at least one other reason to refresh a token (and possibly, future developments could add even more reasons to change token contents at various times), I'd then have to deal with storing transient data somewhere (E.g. "when requesting a refresh token, what is the thing the user wanted to do? has it been too long since they requested to do that? etc.) It'd be much easier if I could simply generate a bearer token on demand in the same way that the OAuthAuthorizationServer itself does. (I know it uses the MachineKey to do this, but I don't know exactly how it does it, nor how I would go about doing what I'm trying to do.)
Of note: In another project I provided internal access to the OAuthBearerAuthenticationOptions class that is passed to the authorization server instance, and was able to use that to decode a bearer token inside of a test. I haven't seen anything obvious thought that would let me encode a bearer token this way.
EDIT: I explored the (extremely tersely, almost uselessly documented) OWIN namespace and found the AccessTokenFormat class which appears that it should do what I want. I wrote this code:
Microsoft.Owin.Security.AuthenticationTicket at = new Microsoft.Owin.Security.AuthenticationTicket(new ClaimsIdentity
{
Label="claims"
}
, new Microsoft.Owin.Security.AuthenticationProperties
{
AllowRefresh=true,
IsPersistent=true,
IssuedUtc=DateTime.UtcNow,
ExpiresUtc=DateTime.UtcNow.AddMinutes(5),
});
at.Identity.AddClaim(new Claim("hello", "world"));
string token = Startup.oabao.AccessTokenFormat.Protect(at);
return Request.CreateResponse(HttpStatusCode.OK, new StringContent(token, System.Text.Encoding.ASCII, "text/plain"));
which seems like it should work. (I again allow access to the OAuthBearerAuthenticationOptions class passed to the OAuthAuthorizationServer instance.) However, this code throws an ArgumentNull exception. The stacktrace indicates that it is writing to a BinaryWriter but the OWIN code is passing a null value to the Write method on the BinaryWriter.
Still have no solution.
I did figure out the code to make this work. One could argue I'm "not using OAuth right", but strictly, this code WILL accomplish what I want - to generate a token in code at any arbitrary point and get the string.
First, as I said, I have to provide access to the OAuthBearerAuthenticationOptions class instance. When the OAuth server initializes I'm guessing it populates this class with all of the various objects used for tokens. The key is that we do have access to Protect and Unprotect which can both encode and decode bearer tokens directly.
This code will generate a token assuming that oabao is the OAuthBearerAuthenticationOptions class that has been passed to the OAuthAuthorizationServer instance:
Microsoft.Owin.Security.AuthenticationTicket at = new Microsoft.Owin.Security.AuthenticationTicket(new ClaimsIdentity("Bearer", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"),
new Microsoft.Owin.Security.AuthenticationProperties
{
AllowRefresh = true,
IsPersistent = true,
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.AddDays(1) // whenever you want your new token's expiration to happen
});
// add any claims you want here like this:
at.Identity.AddClaim(new Claim("userRole", role));
// and so on
string token = oabao.AccessTokenFormat.Protect(at);
// You now have the token string in the token variable.

Authorization by Role/Group in ASP.NET using Auth0

Thanks in advance for your help in this matter!
I was hoping someone could help me figure out how to authorize API access by Group assigned in the Auth0 Authorization extension.
I currently am using the [Authorize] attribute in the web api perfectly - it allows an api call if they have signed in successfully and blocks it if not.
However, if I try [Authorize(Roles = "myGroupName")] authorization fails. Same occurs if I add it to the users app_metadata manually in the Users dashboard on the Auth0 website instead of assigning through the extension.
My project is set up by following the Angular Quick Start and Asp.Net Quick Start. My webapiconfig where I validate the token server side is:
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
var clientID = WebConfigurationManager.AppSettings["auth0:ClientId"];
var clientSecret = WebConfigurationManager.AppSettings["auth0:ClientSecret"];
configuration.MessageHandlers.Add(new JsonWebTokenValidationHandler()
{
Audience = clientID,
SymmetricKey = clientSecret
});
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
The Auth0 Authorization extension currently supports authorization decisions through the concept of groups. You can create a group, assign users to that group and that configure an application to only be accessible to user within a specific group. All of this would be handled automatically and any user outside of the application expected groups would be denied complete access.
Your use case is a bit different, but valid nonetheless. You want the groups configured with the extension to be sent along the generated token so that the application itself makes authorization decisions based on those values.
In order for the groups configured within the extension to be sent along in the token, the first thing you need to do is request them. For this, you need to include the groups scope when performing the authentication requests.
Add the user's group membership to the outgoing token (which can be requested via the OpenID groups scope);
(emphasis is mine, source: Authorization Extension Docs, section Rule Behavior)
If you request a token using that scope and then decode it in jwt.io, you would get something similar to this (the actual groups would vary by user):
{
"groups": [
"GROUP-1",
"GROUP-2"
],
"iss": "https://[tenant].auth0.com/"
}
Now, for the validation of this information on the ASP .NET API side. Assuming the sample you're using is this one (ASP.NET Web API), the group information contained within the token would be mapped to the following claims:
Type: groups | Value: GROUP-1
Type: groups | Value: GROUP-2
This happens because of the logic that exists in the JsonWebToken class which handles arrays coming from the JWT payload by creating per-value claim that share the same type.
The final part is making sure the AuthorizeAttribute checks these claims of type groups instead of trying to lookup role claims. You should be able to accomplish this, by changing the RoleClaimType constant in the JsonWebToken class to have the value "groups" instead of "http://schemas.microsoft.com/ws/2008/06/identity/claims/role".
Like you certrainly know, the Authorize attribute works using what is in the principal: something that inherits IPrincipal.
In web api, it is even more specific; it is something that inherits ClaimsPrincipal (this implements himself IPrincipal).
As you certainly know already, a claim is like a key-value pair.
The ClaimsPrincipal contains a serie of key-value pairs that are directly taken from the authentication token. This authentication token is issued by the authentication server most of time as JWT (Json Web Token). Most of time as well, the authentication server is using OAuth, like is your case.
If the user group, that you expect to be the role in your application doesn't work by using the out-of-the-box Authorize attribute, it's because it is not mapped correctly: Auhtorize checks the claim with claim type: http://schemas.microsoft.com/ws/2008/06/identity/claims/role (the "claim type" is the "key" of the key-value pair). That means that if you want your Authorize to work, this claim must be valued with the group.
You can do several things to have a clean authorization in your application.
Make a custom Authorize attribute. This Authorize attribute would check the role using a different claim type. The claim type that refers to the user group depends on your authentication server. If you don't find what claim type is used for groups in the doc of your authentication server, run your application in debug, and check every claim that is contained in the property User of your controller. You will certainly find what the claim type you are interested in.
Change the setup of your authorization server by redefining the mapping between user information and claims of the token that is produced (in your case, map groups of the user to the claim that has the type http://schemas.microsoft.com/ws/2008/06/identity/claims/role). Generally, this can be setup per client application or even globally. For example this is the way that must be done if you use an ADFS authentication, AzureAD or WSO2 authentication server (http://wso2.com/products/identity-server/)
Add an owin middleware to modify the current principal. It will change the current principal by copying the value of the claim that contains groups into the claim type http://schemas.microsoft.com/ws/2008/06/identity/claims/role. This middleware must be inserted in the flow after the authentication middleware
I have no rights to comment so I'm going to inquire from here. Why are you doing this
[Authorize(Roles = "myGroupName")]
as far as I remember when I was implementing group based authorization I was still typing
[Authorize(Roles = "myRoleName")]
Not other way around.

ASP.NET MVC Anti Forgery Token Insecure

I can actually see the verification token key generated by MVC3 framework in plain text when making a request to the server without ssl.
This key is stored in a cookie called: _RequestVerificationToken_Lw__
In mixed security environment it is actually possible to see this token in plain text sent to the server on the initial request to the non ssl site. This token is also static for the duration of the user's session. Then what's the use of having this token when it can easily be stolen by an attacker, because the cookie gets thrown around in plain text.
Shouldn't this cookie be marked as secure and never to be sent across in plain text? Or at the very least be regenerated on every request such that the secure information doesn't leak out of the ssl channel?
I'm talking about this block in MVC 3 AntiForgeryWorker class
private string GetAntiForgeryTokenAndSetCookie(HttpContextBase httpContext, string salt, string domain, string path)
{
string forgeryTokenName = AntiForgeryData.GetAntiForgeryTokenName(httpContext.Request.ApplicationPath);
AntiForgeryData token = (AntiForgeryData) null;
HttpCookie httpCookie = httpContext.Request.Cookies[forgeryTokenName];
if (httpCookie != null)
{
try
{
token = this.Serializer.Deserialize(httpCookie.Value);
}
catch (HttpAntiForgeryException ex)
{
}
}
if (token == null)
{
token = AntiForgeryData.NewToken();
string str = this.Serializer.Serialize(token);
HttpCookie cookie = new HttpCookie(forgeryTokenName, str)
{
HttpOnly = true,
Domain = domain
};
if (!string.IsNullOrEmpty(path))
cookie.Path = path;
httpContext.Response.Cookies.Set(cookie); //Ma, Why isn't this marked as "SECURE"
}
return this.Serializer.Serialize(new AntiForgeryData(token)
{
Salt = salt,
Username = AntiForgeryData.GetUsername(httpContext.User)
});
}
That's quite the inflammatory question title you have there.
The built-in MVC anti-forgery functionality is as secure as the application is configured to be. All cookies written to Response.Cookies will be automatically marked with the "secure" modifier if <httpCookies requireSSL="true" /> is set in Web.config (see MSDN docs). MVC's anti-forgery cookie also gets this behavior if this switch is set.
Combine this with other functionality like setting the HSTS header in your responses, and you're essentially providing a guarantee that the browser will never send sensitive data over plaintext channels.
Additionally, the anti-forgery system does allow storing custom data in the tokens, and you can receive a callback to verify the custom data when the token is validated. See AntiForgeryConfig.AdditionalDataProvider for more information.
With protection against CSRF attacks, an optimal solution is to always use SSL. Without SSL, yes, the nonce--as it is called--is vulnerable to a MITM attack. When using cookies to store the nonce, the cookie must be marked HTTP-only. This prevents JavaScript from reading the cookie. You should also render the nonce as an <input type="hidden" value="nonce"> tag within all <form>s in addition to a cookie.
Anyone with access to the browser itself would be able to read the nonce, and the only way to prevent a replay attack is to have nonces expire the first time after they are validated for the first time by the server. This approach can cause a terrible user experience when the user uses the back button and resubmits a request with the same nonce, however. Because you're using ASP.NET MVC's built-in anti-CSRF protection mechanism, it may not be easy to change its behavior to only allow a nonce to be used once. (EDIT: Thanks to Levi below for informing me that ASP.NET MVC actually makes this quite simple)
If you want better control over generating and validating the nonces then I suggest rolling your own implementation, as I did with my JuniorRoute framework. In fact, feel free to take a look at JuniorRoute's source code to see how I implemented it. It's too much code for a Stack Overflow post.
My Take
a) The form submission is deemed not forged based on comparison of
__RequestVerificationToken cookie &
__RequestVerificationToken form field.
The 2 values are some kind of symmetrically match and hence not same.
b) Cookie can never be marked default must-use-secure-channel by the framework because some applications do not use https.
c) The __RequestVerificationToken implementation is protection against CSRF & cannot help valid user from snooping into process memory:p.

User Authentication in ASP.NET Web API

I need to develop an iPhone client that consumes JSON data from somewhere. I chose Web API from MS because it seemed easy enough but when it comes to authenticating users, things get quite frustrating.
I am amazed how I've not been able to find a clear example of how to authenticate a user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.
This is not a question but a request for an example of how to do this exactly. I have looked at the following pages:
Making your ASP.NET Web API's Secure
Basic Authentication With ASP.NET Web API
Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.
Anyone willing to write a nice simple example or point me in the right direction, please?
I am amazed how I've not been able to find a clear example of how to authenticate a user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.
That's because you are getting confused about these two concepts:
Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:
Who is the user?
Is the user really who he/she represents himself to be?
Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:
Is user X authorized to access resource R?
Is user X authorized to perform operation P?
Is user X authorized to perform operation P on resource R?
The Authorize attribute in MVC is used to apply access rules, for example:
[System.Web.Http.Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
The above rule will allow only users in the Admin and Super User roles to access the method
These rules can also be set in the web.config file, using the location element. Example:
<location path="Home/AdministratorsOnly">
<system.web>
<authorization>
<allow roles="Administrators"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
However, before those authorization rules are executed, you have to be authenticated to the current web site.
Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.
From here, we could split the problem in two:
Authenticate users when consuming the Web API services within the same Web application
This would be the simplest approach, because you would rely on the Authentication in ASP.Net
This is a simple example:
Web.config
<authentication mode="Forms">
<forms
protection="All"
slidingExpiration="true"
loginUrl="account/login"
cookieless="UseCookies"
enableCrossAppRedirects="false"
name="cookieName"
/>
</authentication>
Users will be redirected to the account/login route, there you would render custom controls to ask for user credentials and then you would set the authentication cookie using:
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
Cross - platform authentication
This case would be when you are only exposing Web API services within the Web application therefore, you would have another client consuming the services, the client could be another Web application or any .Net application (Win Forms, WPF, console, Windows service, etc)
For example assume that you will be consuming the Web API service from another web application on the same network domain (within an intranet), in this case you could rely on the Windows authentication provided by ASP.Net.
<authentication mode="Windows" />
If your services are exposed on the Internet, then you would need to pass the authenticated tokens to each Web API service.
For more info, take a loot to the following articles:
http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/
http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/
If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.
void EnsureAuthenticated(string role)
{
string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
if (role != null && !Roles.IsUserInRole(parts[0], role))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}
From the client side, this helper creates a HttpClient with the authentication header in place:
static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
return client;
}
I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.
The client side code (CoffeeScript) to get the token is:
getAuthenticationToken = (username, password) ->
dataToSend = "username=" + username + "&password=" + password
dataToSend += "&grant_type=password"
$.post("/token", dataToSend).success saveAccessToken
If successful the following is called, which saves the authentication token locally:
saveAccessToken = (response) ->
window.authenticationToken = response.access_token
Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:
{ "Authorization": "Bearer " + window.authenticationToken }

Resources