ASP.Net Kernel, Angular2 and Token Authentication

I am writing a web application using the ASP.NET kernel for the backend / service and Angular2 as an interface, and have authentication / authorization issues.

In the ASP.NET core, I only got one html page and a controller, HomeController with an index that allows anonymous access ([AllowAnonymous]). This single page provides angular2-app to the client.

All other communications use ApiControllers (which in the ASP.NET kernel are just normal controllers, but the actions of these controllers expect and send JSON data. I want to use jwt tokens for authentication / authorization. Users, roles, claims, etc. are stored in IdentityDbContext using the EF core.

Most of the tutorials I found are outdated, incomplete, or related to third-party OAuth solutions. I'm not looking for OAuth, I just need a page with username / Passwort and using tokens for logging in, since I use the whole API to get data using the backend. I read a lot of tutorials, tried some useful libraries, but still got confused about how to set up the middleware chain for security on tokens. As far as I understand, I need to add services for identification, since I want to use IdentityDbContext:

public void ConfigureServices(IServiceCollection services) { [...] services.AddIdentity<IdentityUserEntity, IdentityRoleEntity>() .AddEntityFrameworkStores<ApplicationDbContext, long>() .AddDefaultTokenProviders(); [...] } 

But what middleware do I need to configure in the setup? Do I need app.UseIdentity () or app.UseJwtBearerAuthentication (o) enough? Wouldn't use UseIdentity for authentication before JwtBearer receives a snapshot when checking tokens ??

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { [...] app.UseIdentity(); [...] app.UseJwtBearerAuthentication(jwtOptions); [...] } 

I ask because the client automatically authenticated after I made the call to _signInManager.PasswordSignInAsync (...) in my TokenController, although my client never received jwt. So somehow, ASP.NET identity management found another way to authenticate my user after logging in, which, of course, shouldn't be.

 // simplified controller public class TokenController : Controller { [HttpPost("[action]")] [AllowAnonymous] public async Task<JsonResult> Login([FromBody]LoginViewModel loginRequest) { var signin = await _signInManager.PasswordSignInAsync(loginRequest.Username, loginRequest.Passwort, true, true); } // this will work even though I don't handle any Tokens in the Client yet, so some other authentication mechanism is at work: [HttpGet("test")] [Authorize] public IActionResult Get() { return new JsonResult(from c in User.Claims select new { c.Type, c.Value }); } } 

So, how do I perform token based authentication and nothing else?

[UPDATE]

I think I need to intercept the Cookie authentication event and reject the principal in order to disable Cookie authentication (see https://stackoverflow.com/a/125278/ ): But for some reason, my event handler is never called.

  app.UseCookieAuthentication(new CookieAuthenticationOptions() { Events = new CookieAuthenticationEvents { OnValidatePrincipal = ValidateAsync } }); public static async Task ValidateAsync(CookieValidatePrincipalContext context) { context.RejectPrincipal(); await context.HttpContext.Authentication.SignOutAsync("BsCookie"); } 

Better reads about auth, cookies and token:
- http://andrewlock.net/exploring-the-cookieauthenticationmiddleware-in-asp-net-core/
- https://stormpath.com/blog/token-authentication-asp-net-core

+2
authentication asp.net-core single-page-application jwt
source share
1 answer

MS has provided basic authentication based on the jwt token, you can see how to use it here:

https://code.msdn.microsoft.com/How-to-achieve-a-bearer-9448db57

In startup.cs, first configuration of Jwt Beare

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseJwtBearerAuthentication(new JwtBearerOptions() { TokenValidationParameters = new TokenValidationParameters() { IssuerSigningKey = TokenAuthOption.Key, ValidAudience = TokenAuthOption.Audience, ValidIssuer = TokenAuthOption.Issuer, // When receiving a token, check that we've signed it. ValidateIssuerSigningKey = true, // When receiving a token, check that it is still valid. ValidateLifetime = true, // This defines the maximum allowable clock skew - ie provides a tolerance on the token expiry time // when validating the lifetime. As we're creating the tokens locally and validating them on the same // machines which should have synchronised time, this can be set to zero. Where external tokens are // used, some leeway here could be useful. ClockSkew = TimeSpan.FromMinutes(0) } }); 

Now you can add to services

  public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​) .RequireAuthenticatedUser().Build()); }); 

Finally, use it in the controller, just add [Authorize ("Bearer")]

  [Route("api/[controller]")] public class ValuesController : Controller { [HttpGet("GetStaff")] [Authorize("Bearer")] public IActionResult GetStaff() { List<string> model = new List<string>(); foreach (User user in UserStorage.Users ){ model.Add(user.Username); } return Json(model); } } 

See the full information here: https://github.com/Longfld/ASPNETcoreAngularJWT

+3
source share

All Articles