How to add FormsAuthentication cookie to HttpClient HttpRequestMessage - asp.net

I am trying to authenticate inside integration test by calling FormsAuthentication.SetAuthCookie("someUser", false);
After that I do need to call WebAPI and not receive unauthorized exception because I have authorized attribute applied.
I am using this code to create auth cookie :
var cookie = FormsAuthentication.GetAuthCookie(name, rememberMe);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
ticket.IsPersistent, userData.ToJson(), ticket.CookiePath);
var encTicket = FormsAuthentication.Encrypt(newTicket);
/// Use existing cookie. Could create new one but would have to copy settings over...
cookie.Value = encTicket;
Now I want to add this cookie to HttpRequestMessage inside new HttpClient and send this with my regular request in integration test.
I don't know how to add that auth cookie to HttpRequestMessage ?

For manipulating cookies, you need to use WebRequestHandler along with HttpClient. For example,
var handler = new WebRequestHandler();
var client = new HttpClient(handler);
// use handler to configure request such as add cookies to send to server
CookieContainer property will allow to access cookies collection.
On different note, I doubt if creating FormsAuthentication cookie on client will work. A same encryption key would be needed on both client/server. The best approach would be to replay the login request for actual web API - most probably, it would be a POST to login page with user credentials. Observe the same over browser using tool such as Fiddler and construct the same request within your http client.

Almost 6 years late, but still may be helpful. The solution based on this one:
https://blogs.taiga.nl/martijn/2016/03/10/asp-net-web-api-owin-authenticated-integration-tests-without-authorization-server/
First, while creating Owin TestServer you have to create DataProtector:
private readonly TestServer _testServer;
public IDataProtector DataProtector { get; private set; }
public Server(OwinStartup startupConfig)
{
_testServer = TestServer.Create(builder =>
{
DataProtector = builder.CreateDataProtector(
typeof(CookieAuthenticationMiddleware).FullName, DefaultAuthenticationTypes.ApplicationCookie, "v1");
startupConfig.Configuration(builder);
});
}
Then generate cookie like this (use DataProtector created in previous step):
public string GeterateCookie()
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Role, "your-role"),
new Claim(ClaimTypes.UserData, "user-data"),
new Claim(ClaimTypes.Name, "your-name")
};
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
var tdf = new TicketDataFormat(DataProtector);
var ticket = new AuthenticationTicket(identity, new AuthenticationProperties {ExpiresUtc = DateTime.UtcNow.AddHours(1)});
var protectedCookieValue = tdf.Protect(ticket);
var cookie = new CookieHeaderValue("yourCookie", protectedCookieValue)
{
Path = "/",
HttpOnly = true
};
return cookie.ToString();
}
Make sure to set required claims, initialize ClaimsIdentity according to settings provided to UseCookieAuthentication method, and setting correct CookieName.
The last step is to add CookieHeader to your request:
public Task<HttpResponseMessage> RequestAsync(HttpRequestMessage request)
{
request.Headers.Add("cookie", GenerateCookie());
return _client.SendAsync(request);
}

Related

Identity Server 4 custom token endpoint, get signingcredential at runtime

I am implementing a custom token endpoint for my identityserver4 project. The goal is to issue a token based on validation of a more complex credentials model (a separate user database than Identity Server's built in "client/scope" concept) and issue a Jwt token with extra claims added to help with user identity and access rights in my custom api.
My code is something like this:
[HttpPost]
public IActionResult GetCustomApiToken(CustomUserCredentialsModel credentials)
{
var customUser = GetCustomValidatedUser(credentials); //validate user from DB
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(ApplicationSettings.SigningKey); // <--- DeveloperSigningCredential ???
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("user", customUser.ToString()) /* extra custom claims */ }),
Issuer = "my identity server",
Audience = "my custom api",
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return Ok(tokenHandler.WriteToken(token));
}
Mind you I have not tested the above completely yet, but something like that should work in Production provided the key is managed in ApplicationSettings.
But it will not work in development where the signing key is added through Identity Server 4's AddDeveloperSigningCredential() extension.
One solution is to add SigningCredentials in configuration for all Dev/Test environements (= hassle).
Can I resolve the signing credential at runtime (as they are set in Program/Startup) ?
(Also, yes I know: don't store the signing keys readable in appSettings, please disregard that for the above example.)
Ok, so I figured it out, you can inject the ISigningCredentialStore singleton and resolve the signingCredential from there:
private readonly ISigningCredentialStore _signingCredentialStore;
public CustomTokenController(ISigningCredentialStore signingCredentialStore)
{
_signingCredentialStore = signingCredentialStore ?? throw new ArgumentNullException(nameof(signingCredentialStore));
}
[HttpPost]
public async Task<IActionResult> GetCustomApiToken(CustomUserCredentialsModel credentials)
{
var userId = GetCustomValidatedUser(credentials);
if (userId == null) return Unauthorized();
var signingCredentials = await _signingCredentialStore.GetSigningCredentialsAsync();
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("userId", userId.ToString()) /* extra custom claims */ }),
Issuer = "my IdentityServer",
IssuedAt = DateTime.UtcNow,
Audience = "my api",
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = signingCredentials
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return Ok(tokenHandler.WriteToken(token));
}
This worked for me and the Jwt token generated can be validated just like any token issued by the built in "connect/token" endpoint.

How do I make an HTTP request using cookies on UWP?

I'd like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequent requests). It'd be nice to preserve any and all cookies
The built in Windows.Web.Http.HttpClient can manage cookies if you pass in an instance of HttpBaseProtocolFilter to its constructor. This class then has a CookieManager property which contains the cookies and you can even modify it and add your custom cookies for next requests.
However, you should instead reference the System.Net.Http NuGet package and use its HttpClient which always is up-to-date and regularly updated. In this case the HttpClient class accepts a HttpClientHandler instance in its constructor and this class in turn has the CookieContainer property which works in a similar manner as CookieManager in Windows.Web.Http.
System.Net.Http.HttpClient
Send custom cookie
var handler = new HttpClientHandler()
{
CookieContainer = new System.Net.CookieContainer(),
UseCookies = true
};
var client = new System.Net.Http.HttpClient(handler);
handler.CookieContainer.Add(targetUri, new System.Net.Cookie("name", "value"));
var response = await client.GetAsync(targetUri);
Retrieve cookie
var cookie = handler.CookieContainer["name"];
Windows.Web.Http.HttpClient
Send custom cookie
var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter()
{
CookieUsageBehavior = Windows.Web.Http.Filters.HttpCookieUsageBehavior.Default
};
filter.CookieManager.SetCookie(new Windows.Web.Http.HttpCookie("name", "domain", "path")
{
Value = "value"
});
var client = new Windows.Web.Http.HttpClient(filter);
var response = await client.GetAsync(targetUri);
Retrieve a cookie
var cookie = filter.CookieManager.GetCookies(targetUri).
FirstOrDefault(cookie => cookie.Name == "name");

Cookie-based Forms Authentication Across MVC 5 and ASP.NET Core applications

I have used forms authentication across different sites already, even between different versions of .NET, but now we're looking into starting a new project in ASP.NET 5 (MVC 6) ASP.NET Core and would like to use cookie-based forms authentication across both. The login is done in "old" MVC 5 application.
Is some cross-applications configuration for cookie-based forms authentication even possible or supported with current version of ASP.NET 5?
Could this be implemented on MVC6 ASP.NET Core side using FormsAuthenticationModule or can it play along somehow with the new authentication middleware? Any other suggestions?
I have been beating my head over this same problem for the last few days... but I have solved it... (it seems to be holding up)
This is for converting windows and later forms Authentication to forms Authentication for MVC5 and MVC6 so hopefully you can change enough code to make it work for you... I plan to change some parts when I re-write the login scripts. (and this is alpha so will be making some changes!)
I put the following code in our MVC5 Intranet Site to grab the Roles for windows Authentication
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
// Get current windows Identity to get the roles out of it
WindowsIdentity ident = WindowsIdentity.GetCurrent();
string[] roles = new string[ident.Groups.Count];
int i = 0;
// get the groups from the current Identity
foreach (var g in ident.Groups)
{
roles[i] = g.Translate(typeof(System.Security.Principal.NTAccount)).Value.ToString();
i++;
}
// join into a single string the roles that the user is a member of
string roleData = String.Join(";", roles) ;
// create the forms ticket that all MVC5 sites with the same machine key will pick up.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, ident.Name, DateTime.Now, DateTime.Now.AddMinutes(30), false, roleData, "/");
string encTicket = FormsAuthentication.Encrypt(ticket);
// add the user name first from the Principle and add Windows as this will come from Windows Auth
roleData = ident.Name + ";" + "Windows;" + roleData;
//use machine key to encrypt the data
var encTicket2 = MachineKey.Protect(System.Text.Encoding.UTF8.GetBytes(roleData),
"Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware",
"ApplicationCookie", "v1");
//create a new cookie with a base64string of the encrypted bytes
HttpCookie hc2 = new HttpCookie("cookie1", Convert.ToBase64String(encTicket2));
hc2.Domain = ".domain.com";
hc2.Expires = DateTime.Now.AddHours(8);
Response.Cookies.Add(hc2);
// NOTE: The name of the HttpCookie must match what the FormsAuth site expects.
HttpCookie hc = new HttpCookie("cookie2", encTicket);
hc.Domain = ".domain.com";
hc.Expires = DateTime.Now.AddHours(8);
Response.Cookies.Add(hc);
// Ticket and cookie issued, now go to the FormsAuth site and all should be well.
Response.Redirect("http://www.yoursite.com");
}
this will create to a windows Authentication Ticket in both the forms and MVC6 method.
The string for MVC6 will look something like "John.Doe;Windows;Admin"
Then in the MVC6 startup file I have put the following code into the configure section...
app.Use(async (context, next) =>
{
Logger _logger = new Logger("C:\\\\Logs\\Log.txt");
try
{
var request = context.Request;
var cookie = request.Cookies.Get("cookie1");
var ticket = cookie.ToString();
ticket = ticket.Replace(" ", "+");
var padding = 3 - ((ticket.Length + 3)%4);
if (padding != 0)
ticket = ticket + new string('=', padding);
var bytes = Convert.FromBase64String(ticket);
bytes = System.Web.Security.MachineKey.Unprotect(bytes,
"Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware",
"ApplicationCookie", "v1");
string ticketstring = System.Text.Encoding.UTF8.GetString(bytes);
var ticketSplit = ticketstring.Split(';');
var claims = new Claim[ticketSplit.Length];
var OriginalIssuer = "";
for (int index = 0; index != ticketSplit.Length; ++index)
{
if (index == 0)
{
claims[index] = new Claim(ClaimTypes.Name, ticketSplit[index], "Windows");
}
else if (index == 1)
{
OriginalIssuer = ticketSplit[1];
}
else
{
claims[index] = new Claim(ClaimTypes.Role,ticketSplit[0], OriginalIssuer);
}
}
var identity = new ClaimsIdentity(claims, OriginalIssuer, ClaimTypes.Name,ClaimTypes.Role);
var principal = new ClaimsPrincipal(identity);
_logger.Write(principal.Identity.Name);
context.User = principal;
_logger.Write("Cookie End");
await next();
} catch (Exception ex)
{
_logger.Write(ex.Message);
_logger.Write(ex.StackTrace);
}
});
This then takes the cookie and creates a new claims identity from it. I've only just finished the logic to get it working so I'm sure it can be tidied up... Just thought I would get it to you so you can see if you can get some ideas about it.
WebForms is not a part of ASP.NET 5. This is change #2 according to this blog post
Updated
The new lifecycle of ASP.NET MVC 6 uses a middleware to compose services. You can use Security package to authenticate, but the old "Forms" authentication is not supported anymore.
This is my simple code in Asp.net core mvc,hope will help:
In Startup.cs
In Function ConfigureServices add services.AddAuthorization(); after service.AddMvc()
In Function Configure add code like this
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "UserLoginCookie",
LoginPath = new PathString("/Account/Login"),
AccessDeniedPath = new PathString("/Account/Forbidden"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
before app.UseMvc....
In login Method:
core code like this:
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Name,userName here),
new Claim("UserCodeInMyWebApp",Anything you want),
new Claim(ClaimTypes.Role,"Admin")
};
var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "UserLoginClaimsIdentity"));
//signin
await HttpContext.Authentication.SignInAsync("UserLoginCookie", userPrincipal, new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
});
return RedirectToAction("AuthPage", "Home");
then you can access claim value by keyvalue or check if authenticated:
bool flag = User.Identity.IsAuthenticated
ClaimsIdentity user = User.Identity as ClaimsIdentity
user.Name or user.FindFirst(the key value string you created).Value
and check like this:
[HttpGet]
[AllowAnonymous]
public IActionResult Index()
{
return View();
}
[Authorize(Roles = "Admin")]
[HttpGet]
public IActionResult AuthPage()
{
return View();
}
public IActionResult About()
{
return View();
}

How to create Refresh Token with External Login Provider?

I have searched over the web and could not find a solution to my problem. I am implementing OAuth in my app. I am using ASP .NET Web API 2, and Owin. The scenario is this, once a user request to the Token end point, he or she will receive an access token along with a refresh token to generate a new access token. I have a class the helps me to generate a refresh token. Here is it :
public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
{
private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
var refreshTokenId = Guid.NewGuid().ToString("n");
using (AuthRepository _repo = new AuthRepository())
{
var refreshTokenLifeTime = context.OwinContext.Get<string> ("as:clientRefreshTokenLifeTime");
var token = new RefreshToken()
{
Id = Helper.GetHash(refreshTokenId),
ClientId = clientid,
Subject = context.Ticket.Identity.Name,
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.AddMinutes(15)
};
context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
token.ProtectedTicket = context.SerializeTicket();
var result = await _repo.AddRefreshToken(token);
if (result)
{
context.SetToken(refreshTokenId);
}
}
}
// this method will be used to generate Access Token using the Refresh Token
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
string hashedTokenId = Helper.GetHash(context.Token);
using (AuthRepository _repo = new AuthRepository())
{
var refreshToken = await _repo.FindRefreshToken(hashedTokenId);
if (refreshToken != null )
{
//Get protectedTicket from refreshToken class
context.DeserializeTicket(refreshToken.ProtectedTicket);
// one refresh token per user and client
var result = await _repo.RemoveRefreshToken(hashedTokenId);
}
}
}
public void Create(AuthenticationTokenCreateContext context)
{
throw new NotImplementedException();
}
public void Receive(AuthenticationTokenReceiveContext context)
{
throw new NotImplementedException();
}
}
now i am allowing my users to register through facebook. Once a user register with facebook, I generate an access token and give it to him. Should I generate a refresh token as well ? Onething comes to my mind, is to generate a long access token like one day, then this user has to login with facebook again. But if i do not want to do that, I can give the client, a refresh token, and he can use it to refresh the generated access token and get a new. How do I create the refresh token and attach it to the response when someone register or login with facebook or externally ?
Here is my external registration API
public class AccountController : ApiController
{
[AllowAnonymous]
[Route("RegisterExternal")]
public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var accessTokenResponse = GenerateLocalAccessTokenResponse(model.UserName);
return Ok(accessTokenResponse);
}
}
// Private method to generate access token
private JObject GenerateLocalAccessTokenResponse(string userName)
{
var tokenExpiration = TimeSpan.FromDays(1);
ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, userName));
identity.AddClaim(new Claim("role", "user"));
var props = new AuthenticationProperties()
{
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
};
var ticket = new AuthenticationTicket(identity, props);
var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
JObject tokenResponse = new JObject(
new JProperty("userName", userName),
new JProperty("access_token", accessToken),
// Here is what I need
new JProperty("resfresh_token", GetRefreshToken()),
new JProperty("token_type", "bearer"),
new JProperty("refresh_token",refreshToken),
new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
);
return tokenResponse;
}
I spent a lot of time to find the answer to this question. So, i'm happy to help you.
1) Change your ExternalLogin method.
It usually looks like:
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
}
Now, actually, it is necessary to add refresh_token.
Method will look like this:
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
// ADD THIS PART
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
Request.GetOwinContext(),
Startup.OAuthOptions.AccessTokenFormat, ticket);
await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
properties.Dictionary.Add("refresh_token", context.Token);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
}
Now the refrehs token will be generated.
2) There is a problem to use basic context.SerializeTicket in SimpleRefreshTokenProvider CreateAsync method.
Message from Bit Of Technology
Seems in the ReceiveAsync method, the context.DeserializeTicket is not
returning an Authentication Ticket at all in the external login case.
When I look at the context.Ticket property after that call it’s null.
Comparing that to the local login flow, the DeserializeTicket method
sets the context.Ticket property to an AuthenticationTicket. So the
mystery now is how come the DeserializeTicket behaves differently in
the two flows. The protected ticket string in the database is created
in the same CreateAsync method, differing only in that I call that
method manually in the GenerateLocalAccessTokenResponse, vs. the Owin
middlware calling it normally… And neither SerializeTicket or
DeserializeTicket throw an error…
So, you need to use Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer to searizize and deserialize ticket.
It will be look like this:
Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer
= new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
token.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));
instead of:
token.ProtectedTicket = context.SerializeTicket();
And for ReceiveAsync method:
Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
context.SetTicket(serializer.Deserialize(System.Text.Encoding.Default.GetBytes(refreshToken.ProtectedTicket)));
instead of:
context.DeserializeTicket(refreshToken.ProtectedTicket);
3) Now you need to add refresh_token to ExternalLogin method response.
Override AuthorizationEndpointResponse in your OAuthAuthorizationServerProvider. Something like this:
public override Task AuthorizationEndpointResponse(OAuthAuthorizationEndpointResponseContext context)
{
var refreshToken = context.OwinContext.Authentication.AuthenticationResponseGrant.Properties.Dictionary["refresh_token"];
if (!string.IsNullOrEmpty(refreshToken))
{
context.AdditionalResponseParameters.Add("refresh_token", refreshToken);
}
return base.AuthorizationEndpointResponse(context);
}
So.. thats all! Now, after calling ExternalLogin method, you get url:
https://localhost:44301/Account/ExternalLoginCallback?access_token=ACCESS_TOKEN&token_type=bearer&expires_in=300&state=STATE&refresh_token=TICKET&returnUrl=URL
I hope this helps)
#giraffe and others offcourse
A few remarks. There's no need to use the custom tickerserializer.
The following line:
Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
Request.GetOwinContext(),
Startup.OAuthOptions.AccessTokenFormat, ticket);
As tokenformat: Startup.OAuthOptions.AccessTokenFormat is used. Since we want to provide a refeshtoken this needs te be changed to: Startup.OAuthOptions.RefreshTokenFormat
Otherwise if you want to get a new accesstoken and refresh the refreshtoken ( grant_type=refresh_token&refresh_token=...... ) the deserializer/unprotector will fail. Since it uses the wrong purposes keywords at the decrypt stage.
Finally found the solution for my problem.
First of all, if you EVER encounter any problems with OWIN and you cannot figure out what is going wrong, I advise you to simply enable symbol-debugging and debug it. A great explanation can be found here:
http://www.symbolsource.org/Public/Home/VisualStudio
My mistake simply was, that I was calculating a wrong ExiresUtc when using external login providers. So my refreshtoken basically was always expired right away....
If you are implementing refresh tokens, then look at this gread blog article:
http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/
And to make it work with refresh tokens for external providers, you have to set the two requried parameters ("as:clientAllowedOrigin" and "as:clientRefreshTokenLifeTime") on the context
so instead of
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
Request.GetOwinContext(),
Startup.OAuthOptions.AccessTokenFormat, ticket);
await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
properties.Dictionary.Add("refresh_token", context.Token);
you need to get the client first and set the context parameters
// retrieve client from database
var client = authRepository.FindClient(client_id);
// only generate refresh token if client is registered
if (client != null)
{
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
var context = new AuthenticationTokenCreateContext(Request.GetOwinContext(), AuthConfig.OAuthOptions.RefreshTokenFormat, ticket);
// Set this two context parameters or it won't work!!
context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());
await AuthConfig.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
properties.Dictionary.Add("refresh_token", context.Token);
}

Web API Individual Accounts Register User

I am developing a ASP.NET Web API using ASP.NET Identity (Individual Accounts) for authentication/authorization. I am able to successfully login by making a call to /token URI.
All I want is to automatically sign in my user when he register himself to my application. I am able to do the half of the task by signing in the user in Register method using following code:
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
Is there a way I can return the same OAuth like response which I get when I make successful call to /token. Some thing like following:
{"access_token":"access-token","token_type":"bearer","expires_in":1209599,"userName":"username",".issued":"Sat, 22 Mar 2014 08:12:14 GMT",".expires":"Sat, 05 Apr 2014 08:12:14 GMT"}
Actually I'm facing same issue moments ago, I handled it in such an ugly way-- Inside Register method, I made another web request to access "/token", just after created the new user, and pass the latest username and password.
private string GetTokenForNewUser(string username, string password)
{
using (var client = new HttpClient())
{
var host = Request.RequestUri.Scheme + "://" + Request.RequestUri.Host + ":" + Request.RequestUri.Port;
client.BaseAddress = new Uri(host);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Dictionary<string, string> credential = new Dictionary<string, string>();
credential.Add("grant_type", "password");
credential.Add("username", username);
credential.Add("password", password);
HttpResponseMessage response = client.PostAsync(host + "token", new FormUrlEncodedContent(credential)).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
}
//if we go this far, something error happens
return string.Empty;
}
I don't think this is a good way to do so, but it just works.
You can add payload for the token (it also depends on the token you are using). Then, you can also retrieve the payload value from the token during request.
var token = new JwtSecurityToken(_config["Jwt:Issuer"], _config["Jwt:Issuer"], signingCredentials: credentials, expires: DateTime.Now.AddDays(2));
token.Payload["UserId"] = user.Id;

Resources