Skip to content

Commit

Permalink
added token auth
Browse files Browse the repository at this point in the history
  • Loading branch information
rushi216 committed Feb 22, 2016
1 parent 72e4068 commit 6c9bea8
Show file tree
Hide file tree
Showing 9 changed files with 190 additions and 20 deletions.
3 changes: 3 additions & 0 deletions MvcStarter/App_Start/AutofacConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using System.Web.Mvc;
using System.Data.Entity;
using MvcStarter.Repository;
using Microsoft.Owin.Security.OAuth;

namespace MvcStarter.App_Start
{
Expand All @@ -32,6 +33,8 @@ public static IComponentContext RegisterDependancies(IAppBuilder app)
builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication);
builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider());

builder.RegisterType<ApplicationOAuthProvider>().As<IOAuthAuthorizationServerProvider>().SingleInstance();

// register mvc controllers
builder.RegisterControllers(typeof(MvcApplication).Assembly);

Expand Down
37 changes: 34 additions & 3 deletions MvcStarter/App_Start/Startup.Auth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
using Owin;
using MvcStarter.Models;
using MvcStarter.Identity;
using Microsoft.Owin.Security.OAuth;
using Autofac;

namespace MvcStarter
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
public void ConfigureAuth(IAppBuilder app, IComponentContext container)
{
// 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
Expand All @@ -28,11 +30,40 @@ public void ConfigureAuth(IAppBuilder app)
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),

OnApplyRedirect = ctx =>
{
if(!new Func<IOwinRequest, bool>(x => {
IReadableStringCollection query = x.Query;
if ((query != null) && (query["X-Requested-With"] == "XMLHttpRequest"))
{
return true;
}
IHeaderDictionary headers = x.Headers;
return ((headers != null) && (headers["X-Requested-With"] == "XMLHttpRequest"));
})(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
}
});
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

app.UseOAuthBearerTokens(
new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/Token"),
Provider = container.Resolve<IOAuthAuthorizationServerProvider>(),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// Note: Remove the following line before you deploy to production:
AllowInsecureHttp = true
});



// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

Expand Down
13 changes: 10 additions & 3 deletions MvcStarter/App_Start/WebApiConfig.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
Expand All @@ -9,9 +10,15 @@ public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//We include this to bypass cookie(host) authentication, so it cant process webapi request for authentication/authorization
//This also helps to return 401 instead of login page when cookie authentication comes in between
//But currently it is commented as we want to authorize webapi request also with cookies
//But by commenting this it will return login page instead of 401 while webapi, so for that I have overrided cookie authentication config


// Web API routes
//config.SuppressDefaultHostAuthentication();
//config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
Expand Down
29 changes: 29 additions & 0 deletions MvcStarter/Controllers/SecureController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using MvcStarter.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MvcStarter.Controllers
{
[Authorize]
public class SecureController : ApiController
{
private readonly ApplicationUserManager _userManger;

public SecureController(ApplicationUserManager userManager)
{
_userManger = userManager;
}


[HttpGet]
[Route("api/me")]
public IHttpActionResult Me()
{
return Ok(true);
}
}
}
92 changes: 92 additions & 0 deletions MvcStarter/Identity/ApplicationOAuthProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using System.Security.Claims;
using Microsoft.AspNet.Identity.Owin;

namespace MvcStarter.Identity
{
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly ApplicationUserManager _userManager;

public ApplicationOAuthProvider(ApplicationUserManager userManager)
{
_userManager = userManager;
}

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

ApplicationUser user = await _userManager.FindAsync(context.UserName, context.Password);

if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}

ClaimsIdentity oAuthIdentity = await _userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await _userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}

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);
}

public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}

return Task.FromResult<object>(null);
}

public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == "self")
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");

if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
}

return Task.FromResult<object>(null);
}

public static AuthenticationProperties CreateProperties(string userName)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "userName", userName }
};
return new AuthenticationProperties(data);
}
}
}
19 changes: 13 additions & 6 deletions MvcStarter/MvcStarter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,23 @@
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.Owin">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Owin.5.2.3\lib\net45\System.Web.Http.Owin.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
Expand Down Expand Up @@ -121,12 +132,6 @@
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.Formatting">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.2\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.2\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.WebHost">
<HintPath>..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.2\lib\net45\System.Web.Http.WebHost.dll</HintPath>
</Reference>
Expand Down Expand Up @@ -187,9 +192,11 @@
<Compile Include="Controllers\AccountController.cs" />
<Compile Include="Controllers\HomeController.cs" />
<Compile Include="Controllers\ManageController.cs" />
<Compile Include="Controllers\SecureController.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Identity\ApplicationOAuthProvider.cs" />
<Compile Include="Identity\ApplicationSignInManager.cs" />
<Compile Include="Identity\ApplicationUser.cs" />
<Compile Include="Identity\ApplicationUserManager.cs" />
Expand Down
2 changes: 1 addition & 1 deletion MvcStarter/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public void Configuration(IAppBuilder app)

DatabaseConfig.Initialize(container);

ConfigureAuth(app);
ConfigureAuth(app, container);
}
}
}
10 changes: 5 additions & 5 deletions MvcStarter/Web.config
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>

<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</handlers></system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
Expand Down Expand Up @@ -78,15 +78,15 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Expand Down
5 changes: 3 additions & 2 deletions MvcStarter/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
<package id="Microsoft.AspNet.Razor" version="3.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="3.2.2" targetFramework="net45" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.2" targetFramework="net45" />
Expand Down

0 comments on commit 6c9bea8

Please sign in to comment.