WebApi: Token-Based-Windows-Authentication - c#

Is there any way to user both Token based authentication and Windows authentication in a web api application?
We have a "standard" web-api-application using token based (bearer) authentication.
The OAuth-Configuration looks like this:
OAuthOptions = new OAuthAuthorizationServerOptions {
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
};
app.UseOAuthBearerTokens(OAuthOptions);
Everything works fine. When calling the "/Token"-endpoint you get your token and are authorized.
Now I want to add windows authentication, to enable "signle-sign-on" with the logged in user of the windows-os of the client calling the web-api.
What I did so far:
Changed the web.config and added
<system.web>
<identity impersonate="true" />
<validation validateIntegratedModeConfiguration="false" />
</system.web>
Now every Request is authenticated with the windows user, without using the token process.
So I added anoother provider, to log in with your windows identity and get a token:
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions {
TokenEndpointPath = new PathString("/IdentityToken"),
Provider = new WindowsIdenityAuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
});
The provider should do almost the same as the ApplicationOAuthProvider that generates the token for a request with username and password, except the validation of the password.
Unfortunatly, there is no user/identity set in the request against the "/IdentityToken"-endpoint.
Can anyone help me with this or am I completely on the wrong track?

Related

Form authentication slidingExpiration does not work

I have below code
int intTimeout = (FormsAuthentication.Timeout.Hours * 60) +
FormsAuthentication.Timeout.Minutes;
var authTicket = new FormsAuthenticationTicket(1, Utility.userCookie, DateTime.Now,
DateTime.Now.AddMinutes(intTimeout), true, cookieValue);
string strEncryptedTicket = HttpUtility.UrlEncode(FormsAuthentication.Encrypt(authTicket));
var authCookie = new HttpCookie(Utility.userCookie, strEncryptedTicket);
authCookie.Expires = authTicket.Expiration;
//FormsAuthentication.RedirectFromLoginPage("", false);
authCookie.Secure = FormsAuthentication.RequireSSL;
//authCookie.Secure = true;
HttpContext.Current.Response.Cookies[Utility.userCookie].Expires = authTicket.Expiration;
HttpContext.Current.Response.Cookies[Utility.userCookie].Value = authCookie.Value;
Below web.config
<authentication mode="Forms">
<forms timeout="2" slidingExpiration="true" requireSSL="true" />
</authentication>
I keep hitting page link, still it expires in 2 minutes.
Please pay attention to the structure of custom forms–based authentication in web.config:
<forms
name="name"
loginUrl="URL"
defaultUrl="URL"
protection="[All|None|Encryption|Validation]"
timeout="[MM]"
path="path"
requireSSL="[true|false]"
slidingExpiration="[true|false]">
enableCrossAppRedirects="[true|false]"
cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]"
domain="domain name"
ticketCompatibilityMode="[Framework20|Framework40]">
<credentials>...</credentials>
</forms>
As you see, timeout property works based on minutes where you set it 2 (e.g. 2 minutes).
Generally, if you enable slidingExpiration in web.config. You have no need to regenerate a new cookie manually. For your scenario, I suggest you to use a trace tool e.g. Fiddler. When you refresh the page, you can check from Fiddler that whether the cookie expired time is reset.
I found a good example in Weird Timeouts With Custom ASPNETFormsAuthentication which can do some clearance for you.
Maybe the problem is related to lack of static machineKey section in the web.config file. when you call FormsAuthentication.Encrypt or FormsAuthentication.Decrypt, the methods use the machineKey values which is provided in the web.config file to perform the operation. if you do not provide strict values for machineKey, a new unique validationKey and decryptionKey would generate at the start point of the web application. sometimes depend on the server settings(for example small Idle-Time values for application pool settings), application is terminated before the expiration time of the FormsAuthenticationTicket. in this case because of the new machineKey values the Decrypt method can't validate the Ticket. I just recommend you to set a static machineKey.
see the following link:
https://msdn.microsoft.com/en-us/library/w8h3skw9(v=vs.100).aspx
Try to remove this line from your code and try again:
HttpContext.Current.Response.Cookies[Utility.userCookie].Expires = authTicket.Expiration;
In web.config file either remove <clear/> element or add following after <clear/> element if not present.
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
In my application, I define cookieAuthenticationOptions in Startup.cs like this and it works fine
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
ExpireTimeSpan = TimeSpan.FromHours(1),
SlidingExpiration = true,
CookieHttpOnly = true,
CookieName = "App.Authentication",
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
});
Do you define those options ?
Why you don't use the SignIn method of AuthenticationManager ?

Unable to authenticate Asp.net WebApi using OAuth and twitter external provider

I have created Asp.net WebApi and enable TwitterAuthentication code.
On HomeController.cs used [Authorize] attribute.
Now how can I verify credentials and give access to Authorize Controller without open login box ?
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
app.UseTwitterAuthentication(
consumerKey: "mykey",
consumerSecret: "mysecret");
}
I have added one application into twitter app - get the consumer key.
and consumer secret.
I do not want a twitter login popup to be opened
for login credentials while authorizing webapi.

Cookie expiry in ASP NET Core Authentication using Azure AD OpenIdConnect and custom middleware

I am currently struggling with setting the timeout on the cookie/auth token when authenticating my .NET Core App using Azure AD via the OpenIdConnect authentication model.
The sign-in scheme is being set in the ConfigureServices method via the following:
services.AddAuthentication(options => options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
I am then setting up my configuration as follows:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieName = "MyCookie",
ExpireTimeSpan = TimeSpan.FromHours(2)
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions()
{
Authority = authorityUri.AbsoluteUri,
ClientId = azureOptions.ClientId,
ClientSecret = azureOptions.ClientSecret,
ResponseType = OpenIdConnectResponseTypes.CodeIdToken,
Events = new OpenIdConnectEvents()
{
OnAuthorizationCodeReceived = async context =>
{
await aAuthenticateMiddleware.OnAuthenticate(context, logger);
}
}
});
app.UseMiddleware<aAuthenticateMiddleware>();
Note, that I am not using the built in Identity (as its not practical for our purposes) but rather using a custom middleware.
Within the middleware layer I am checking whether the user is authenticated and if not a challenge is issued:
var authenticationProperties = new AuthenticationProperties() { RedirectUri = context.Request.Path.Value ?? "/" };
authenticationProperties.AllowRefresh = false;
authenticationProperties.IssuedUtc = DateTime.Now;
authenticationProperties.ExpiresUtc = DateTime.Now.AddHours(2);
await context.Authentication.ChallengeAsync(
authenticationManager.IdentityProvider.AuthenticationScheme,
authenticationProperties,
ChallengeBehavior.Automatic
);
This is all works fine and authenticates the user correctly etc however this is issuing the auth token (and cookie) with a 15 minute expiry and ignoring my 2 hour expiry that I have tried setting.
I have been referring to the latest source examples from GitHub from the aspnet/security repository for examples.... however none of these mention anything about overriding the default expiry issued.
https://github.com/aspnet/Security/tree/dev/samples/OpenIdConnect.AzureAdSample
Most examples I have found are still referencing the old AspNet libraries rather than the AspNetCore libraries.
Some articles suggest that using the SignInAsync with persistent set to True allows the ExpireTimeSpan to be honored, however this throws a "Not Supported Exception" when calling it. Perhaps SignInAsync is not supported via Azure AD?
Does anyone have any insight on how to achieve this?
in UseOpenIdConnectAuthentication set UseTokenLifetime = false

Authenticating user/password against Active Directory using ASP.NET Identity + own database (custom asp.net identity)

I have implemented custom asp.net identity with database first approach. I have implemented token based implementation using OWIN.
app.CreatePerOwinContext<OVT_UserEntities>(() => new OVT_UserEntities());
app.CreatePerOwinContext<UserManager<User, int>>(
(IdentityFactoryOptions<UserManager<User, int>> options, IOwinContext context) =>
new UserManager<User, int>(new UserStore(context.Get<OVT_UserEntities>())));
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new OVTApplicationOAuthProvider(
"self", () => HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User, int>>()),
AuthorizeEndpointPath = new PathString("/api/account/authorize"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
});
OVT_UserEntities is my custom db context which will validate the entered username with my own database.
now i want to do active directory authentication for organizational users account.
How can i implement both database asp.net identity authentication + active directory implementation in asp.net identity authentcation.
if the user enters his creditentials, first i will check in database ,if it's not available then will go for active directory for further checking. if is avail in AD(active directory) then will redirect some other page by getting some tokens.
any references would be appreciated.

Generate bearer token using c#

I have a web application. My requirement is that i need to generate oauth2 bearer token on every login. Currently we are using thinktecture to generate token, but this procedure is taking almost 7 seconds to generate token everytime. Is there any way i can generate token without using thinktecture ?
If you have created a new ASP.NET Web Application -> Web API with Individual User Accounts. Have a look at App_Start -> Startup.Auth.cs.
It should contain something like this:
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
This means that you can send a request for an access token, example request:
You can then verify that the access token works:
With this token you can now access all protected resources that the user has access to.
Asp.net default implementation will use DPAPI in your Authorization Server, so it will use the “validationKey” value in machineKey node stored in machine.config file to issue the access token and protect it. The same case applies when you send the access token to your Resource Server, it will use the same machineKey to decrypt the access token and extract the authentication ticket from it.
ASP.NET
If you want to generate a JWT encoded Bearer Token, you should override ISecureDataFormat<AuthenticationTicket>.Protect() Method:
CustomJwtFormat.cs
string symmetricKeyAsBase64 = audience.Base64Secret;
var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
var signingKey = new HmacSigningCredentials(keyByteArray);
var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc;
JwtSecurityToken token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime,expires.Value.UtcDateTime, signingKey);
var handler = new JwtSecurityTokenHandler();
//serialize the JSON Web Token to a string
var jwt = handler.WriteToken(token);
return jwt;
Add your custom JWT formatter to OAuth Option
OAuthAuthorizationServerOptions OAuthServerOptions = new
OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
AccessTokenFormat = new CustomJwtFormat("http://localhost:5001")
};
// Generation and validation
app.UseOAuthBearerTokens(OAuthServerOptions);
The app.UseOAuthBearerTokens helper method creates both the token server and the middleware to validate tokens for requests in the same application.
If this is an Authorization server(generate token) , you should use app.UseOAuthAuthorizationServer(OAuthServerOptions) in the last line
ASP.NET Core
Unforturnately, the ASP.NET team simply decided not to port OAuthAuthorizationServerMiddleware to asp.net core: https://github.com/aspnet/Security/issues/83
community-provided, open source authentication options for ASP.NET Core:
AspNet.Security.OpenIdConnect.Server:low-level, protocol-first OpenID Connect server framework for ASP.NET Core and OWIN/Katana.
IdentityServer:OpenID Connect and OAuth 2.0 framework for ASP.NET Core, officially certified by the OpenID Foundation and under governance of the .NET Foundation.
OpenIddict: easy-to-use OpenID Connect server for ASP.NET Core.
I followed below article http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
Downloaded their sourcecode and checked it. They have good example on how to create token.

Categories

Resources