/// <summary> /// When user is not authenticated look for magic key in the header and log user in. /// </summary> /// <param name="filterContext"></param> public void OnAuthorization(AuthorizationFilterContext filterContext) { // See if the AllowAnonymous attribute has been used for the action and skip over. if (IsAllowAnonymous(filterContext.Filters) == false) { IdentityService identityService = BLL.Startup.IdentityService; // see if the user is already authenticated. if (filterContext.HttpContext.User.Identity.IsAuthenticated == true) { if (identityService.IsInRoles(filterContext.HttpContext.User, this.Roles) == false) { // The already logged in user is not allowed to access this page. filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } } else { // Check for the header token. string token = filterContext.HttpContext.Request.Headers[ApiAuthorizationController.HeaderTokenName].ToString(); if (token.IsNullOrEmpty() == false) { ApiLoginRepository loginRepo = (ApiLoginRepository)DAL.Startup.ApiLoginRepository; loginRepo.ClearExpiredLogins(ApiAuthorizationController.TimeoutHours); ApiSessionModel model = loginRepo.Fetch(token); if (model != null) { Microsoft.AspNetCore.Identity.SignInResult signInResult = (identityService.LoginAsync(new ApiLoginModel() { Email = model.Email, Password = model.Password }, mustBeInRole: "Api")).Result; if (signInResult.Succeeded == false) { filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } signInResult = null; } else { filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } model = null; loginRepo = null; } else { filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } } identityService = null; } }
public ApiAuthorizationController(IdentityService identityService, IRepository <ApiSessionModel, string> repository) { this.IdentityService = identityService; this.Repository = (ApiLoginRepository)repository; }