My angular application is connected with an asp.net web API project. Token expiry timeout is 20 mins. Below is my startup class
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
app.UseCors(CorsOptions.AllowAll);
OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new ApplicationOAuthProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(5),
AllowInsecureHttp = true
};
app.UseOAuthAuthorizationServer(option);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
The problem is that my token is not getting refreshed on every call and it is automatically getting expired after 20 mins. How can I refresh a token on every API call?
Pls add refresh token provider in the config method -
{
public void Configuration(IAppBuilder app)
{
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
//The Path For generating the Toekn
TokenEndpointPath = new PathString("/token"),
//Setting the Token Expired Time (30 minutes)
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
//MyAuthorizationServerProvider class will validate the user credentials
Provider = new MyAuthorizationServerProvider(),
//For creating the refresh token and regenerate the new access token
RefreshTokenProvider = new RefreshTokenProvider()
};
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
}
}
Related
I'm working with a .net framework 4.7 app hosted in IIS. The api needs to be secured with JWT token. Identity is provided by another server and clients will send the JWT as bearer token in the header. I like to use OWIN pipeline for authorization. Currently the app uses Global.asax for startup and I like to keep it as is. I just want OWIN for authorization using JWT. I will use the [Authorize] attribute on the controllers needing jwt authorization. IIS doesn't do any authorization at the moment.
I have this in the Startup.cs for Owin.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = ConfigHelper.GetAudience(),
ValidIssuer = ConfigHelper.GetIssuer(),
ValidateLifetime = true,
ValidateIssuerSigningKey = true
}
});
}
}
How do I call the Startup.Configure() from Global.asax so Owin pipeline handles the authorization for incoming requests.
Thanks
You can have both global.asax and OWIN startup in the same project. ASP.NET will first call the global.asax and hand the control over to OWIN's startup. Make sure you have the Microsoft.Owin.Host.SystemWeb package installed in the project. And you have a class with the name Startup and a method Configuration(IAppBuilder app). There are other ways to let OWIN know where it should start.
You should also be aware of the fact that in .NET framework, there is a manual process to retrieve the signing keys from the authority that issued the JWT token. Otherwise, you will get the mismatched key error. Once you get the keys, you will assign them to ValidSigningKeys property in TokenValidationParameters. Search SO for examples.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = ConfigHelper.GetAudience(),
ValidIssuer = ConfigHelper.GetIssuer(),
ValidateLifetime = true,
ValidateIssuerSigningKey = true
}
});
}
I am trying to authenticate my app using ADFS and oauth2. I found a lot of documentation to do this with an azure service (using ADAL). But there is no info about how to do it with a local server.
I tested all the info below with an angular app and the authentication works!
public class AuthenticationService
{
public static string clientId = "uri:tst-amdm-website.mycompany.be";
private static string commonAuthority = "https://claim.mycompany.be/";
public static Uri returnUri = new Uri("http://www.google.be");
const string graphResourceUri = "uri:tst-amdm-api.mycompany.be";
public async void GetAccessToken(IPlatformParameters platformParameters)
{
AuthenticationResult authResult = null;
JObject jResult = null;
//List<User> results = new List<User>();
try
{
AuthenticationContext authContext = new AuthenticationContext(commonAuthority);
if (authContext.TokenCache.ReadItems().Any())
authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, platformParameters);
var test = authResult.AccessToken;
}
catch (Exception ee)
{
//results.Add(new User { error = ee.Message });
//return results;
}
}
}
This is the error I get, but in angular this url: https://claim.mycompany.be/ works perfectly.
'authority' Uri should have at least one segment in the path (i.e. https://<host>/<path>/...)
There's good references here but note that you need ADFS 4.0 to do this.
For ADFS 3.0. your choices are limited. Good overview here.
I have Web Api. It works good on my local computer but when I publish it on my server/hosting. Only Url to request OAuth Token returns "No HTTP resource was found that matches the request". All others controllers works fine.
Any ideas why it happens only in production?
My Startup.cs
using System;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
[assembly: OwinStartup(typeof(Api.Startup))]
namespace Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseWebApi(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/v1/oauth/token"), //TODO: FROM WEB CONFIG
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), //TODO: FROM WEB CONFIG
Provider = new AuthorizationProvider()
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}
Best Regards
Im getting an infinite redirect after i logged in with ADFS 2.0.
My ConfigureAuth.cs is like
//defines default authentication to WSFederation
app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
//Defines the MetadataAddress and realm
app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
{
MetadataAddress = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"],
Wtrealm = ConfigurationManager.AppSettings["ida:Audience"]
});
//Defines WSFederation cookie as default authentication type
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
});
i can get to the ADFS login page, but when it returns to my app it keeps asking ADFS for a valid authentication, after 6 requests i get blocked by ADFS.
UPDATE 1
It turns out i needed to specify the Issuer, TokenEndpoint and the certificate key, for some reason owin didnt get these values from the metadata, so i ended up copying the values of the metadata and using them in the webconfig under appsettings.
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions { });
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = ConfigurationManager.AppSettings["ida:Audience"],
AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
Configuration = getWsFederationConfiguration()
}
);
}
private static WsFederationConfiguration getWsFederationConfiguration()
{
WsFederationConfiguration configuration = new WsFederationConfiguration
{
Issuer = ConfigurationManager.AppSettings["wsFederation:trustedIssuer"],
TokenEndpoint = ConfigurationManager.AppSettings["wsFederation:issuer"],
};
configuration.SigningKeys.Add(new X509SecurityKey(new X509Certificate2(Convert.FromBase64String(ConfigurationManager.AppSettings["wsFederation:trustedIssuerSigningKey"]))));
return configuration;
}
How do you trigger authentication? If it is through an [Authorize], do you happen to request special user or roles? If you request a role that the signed in user does not have, you'll end up bouncing around.
Also, you should change the order of your calls: first set the cookie middleware, then the protocol one.
It turns out i needed to specify the Issuer, TokenEndpoint and the certificate key, for some reason owin didnt get these values from the metadata, so i ended up copying the values of the metadata and using them in the webconfig under appsettings.
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions { });
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = ConfigurationManager.AppSettings["ida:Audience"],
AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
Configuration = getWsFederationConfiguration()
}
);
}
private static WsFederationConfiguration getWsFederationConfiguration()
{
WsFederationConfiguration configuration = new WsFederationConfiguration
{
Issuer = ConfigurationManager.AppSettings["wsFederation:trustedIssuer"],
TokenEndpoint = ConfigurationManager.AppSettings["wsFederation:issuer"],
};
configuration.SigningKeys.Add(new X509SecurityKey(new X509Certificate2(Convert.FromBase64String(ConfigurationManager.AppSettings["wsFederation:trustedIssuerSigningKey"]))));
return configuration;
}
I am creating a simple authentication server using the default owin oauth server. After supplying the correct credentials a bearer token is generated and returned to the client. I used among others this tutorial by Taiseer
I would like to store the token in a database before the token is send to the client.
Maybe I completely overlooked it, but where can I get the token before it is send? As far as I know the token is generated after the ticket is validated in the GrantResourceOwnerCredentials method.
I am guessing the token is stored in the context. How can I get it out?
Startup.cs
private void ConfigureAuthServer(IAppBuilder app) {
// Configure the application for OAuth based flow
var oAuthServerOptions = new OAuthAuthorizationServerOptions {
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
Provider = new ApplicationOAuthProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
ApplicationOAuthProvider
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
//Dummy check here
if (context.UserName != context.Password) {
context.SetError("invalid_grant", "The user name or password is incorrect");
return Task.FromResult<object>(null);
}
var claims = new List<Claim> {
new Claim(ClaimTypes.NameIdentifier, context.UserName),
new Claim(ClaimTypes.Name, context.UserName)
};
var oAuthIdentity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
context.Validated(ticket);
return Task.FromResult<object>(null);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context) {
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) {
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
Note: for those who wonder why I want to store the tokens.. it is a requirement I have to fulfill.
To fetch the token before it is sent to the client you must override TokenEndpointResponse:
public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
{
return base.TokenEndpointResponse(context);
}
the context object has a property AccessToken which will contains the representation of the token as a string.
OAuthTokenEndpointResponseContext contains a dictionary of objects
IDictionary<string, object> in AdditionalResponseParameters which allows us to find all the claims for the indentity.
If we wanted to fetch the expiration of the token we would find the claim .expires in the dictionary:
context.AdditionalResponseParameters[".expires"]
There's a github repository if someone is interested to play with a simple integration of client and server interaction.