.NET Core 3 Service result to Controller to FE (data or error reason) - asp.net-core

building new app on .net core 3 and Angular. Overall all works, but I want to add more intelligence to service/controller part. This is one of the api's, but this logic can be applied to others as as well.
Here's my Login Controller:
[HttpPost]
public async Task<IActionResult> Login([FromBody] UserLoginDto userLogin)
{
var token = await _userService.LoginAsync(userLogin);
if (token != null)
{
return Ok(token);
}
else
{
return BadRequest("Something went wrong");
}
}
And here's my userService:
public async Task<string> LoginAsync(UserLoginDto userLogin)
{
var user = await _userManager.FindByEmailAsync(userLogin.Email);
if (user != null)
{
var result = await _signInManager.PasswordSignInAsync(user, userLogin.Password, false, true);
if (result.Succeeded)
{
var roles = await _userManager.GetRolesAsync(user);
var tokenJson = _jwtManager.getJwtToken(user.Email, roles);
return tokenJson;
}
else
{
return null; // Return BadRequest and result reason (Failed, lockedout, etc)
}
}
else
{
return null; // User not found, return NotFound }
}
Here's my question - how should I return result from userService to Controller so, that I could respond to API call either with Ok(token) or BadRequest/NotFound with the reason.
If I keep all this LoginAsync code in controller, then it's easy, but I want to use service.
One option I was thinking was to introduce new class, something like:
public class BaseResult
{
public object Data { get; set; }
public long ResponseCode { get; set; }
public string ErrorMessage { get; set; }
}
then always return this class from service, but not fully like that idea either.
thanks!

Here is a working demo you could follow:
Model:
public class UserLoginDto
{
public string Email { get; set; }
public string Password { get; set; }
}
IUserService:
public interface IUserService
{
Task<IActionResult> LoginAsync(UserLoginDto userLogin);
}
UserService:
public class UserService: IUserService
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly IJwtManager _jwtManager;
public UserService(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
IJwtManager jwtManager)
{
_userManager = userManager;
_signInManager = signInManager;
_jwtManager = jwtManager;
}
public async Task<IActionResult> LoginAsync(UserLoginDto userLogin)
{
var user = await _userManager.FindByEmailAsync(userLogin.Email);
if (user != null)
{
var result = await _signInManager.PasswordSignInAsync(user, userLogin.Password, false, true);
if (result.Succeeded)
{
var roles = await _userManager.GetRolesAsync(user);
var tokenJson = _jwtManager.getJwtToken(user.Email, roles);
return new OkObjectResult(tokenJson);
}
else
{
// Return BadRequest and result reason (Failed, lockedout, etc)
if (result.IsNotAllowed)
{
if (!await _userManager.IsEmailConfirmedAsync(user))
{
// Email isn't confirmed.
return new BadRequestObjectResult("Email isn't confirmed.");
}
if (!await _userManager.IsPhoneNumberConfirmedAsync(user))
{
// Phone Number isn't confirmed.
return new BadRequestObjectResult("Phone Number isn't confirmed.");
}
return new BadRequestObjectResult("Login IsNotAllowed");
}
else if (result.IsLockedOut)
{
// Account is locked out.
return new BadRequestObjectResult("Account is locked out.");
}
else if (result.RequiresTwoFactor)
{
// 2FA required.
return new BadRequestObjectResult("2FA required");
}
else
{
// Password is incorrect.
return new BadRequestObjectResult("Password is incorrect.");
}
}
}
else
{
return new NotFoundObjectResult("Username is incorrect"); // User not found, return NotFound }
}
}
}
Controller:
public class HomeController : Controller
{
private readonly IUserService _userService;
public HomeController(IUserService userService)
{
_userService = userService;
}
[HttpPost]
public async Task<IActionResult> Login([FromBody] UserLoginDto userLogin)
{
var result= await _userService.LoginAsync(userLogin);
return result;
}
}
Startup.cs:
Not sure what is _jwtManager.getJwtToken in your code,so I just guess it is an interface and owns a JwtManager class implemented this interface.And it contains a getJwtToken method which generated the token.
services.AddScoped<IUserService, UserService>();
services.AddScoped<IJwtManager, JwtManager>();

Related

Shopifysharp AuthorizationService.IsAuthenticRequest Returns false

Please see the following code snippet:
This is my controller:
[Produces("application/json")]
[Route("api/Shopify")]
[AllowAnonymous]
[ServiceFilter(typeof(ShopifyVerificationFilter))]
//[ApiExplorerSettings(IgnoreApi = true)]
public class ShopifyController : Controller
{
private readonly ILogger logger;
public ShopifyController(ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger<StoreLocatorController>();
}
[HttpGet("fetch_stock.json")]
public async Task<IActionResult> GetInventoryLevels(ShopifyFetchStock shopifyFetchStock, [FromServices] IShopifyFulfillmentServices shopifyFulfillmentServices)
{
try
{
var inventoryData = await shopifyFulfillmentServices.GetInventoryLevels(shopifyFetchStock);
return Ok(inventoryData);
}
catch (Exception ex)
{
return Ok();
}
}
}
This is my ShopifyVerificationFilter:
public class ShopifyVerificationFilter : Attribute, IAuthorizationFilter
{
private readonly IOptions<ShopifySettings> _shopifySettings;
private readonly IShopifyVerify _shopifyVerify;
public ShopifyVerificationFilter(IOptions<ShopifySettings> shopifySettings, IShopifyVerify shopifyVerify)
{
_shopifySettings = shopifySettings;
_shopifyVerify = shopifyVerify;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var isVerified = _shopifyVerify.IsAuthenticShopifyRequest(context.HttpContext.Request.QueryString.Value, _shopifySettings.Value.APISecretKey);
if (!isVerified)
{
context.HttpContext.Request.EnableRewind();
isVerified = _shopifyVerify.IsAuthenticShopifyWebhook(context.HttpContext.Request.Headers, context.HttpContext.Request.Body, _shopifySettings.Value.APISecretKey, context.HttpContext.Request.QueryString.Value);
if (!isVerified)
{
context.Result = new UnauthorizedResult();
}
else
{
context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
}
}
}
}
This is the implementation for the IsAuthenticShopifyRequest method:
public class ShopifyVerify : IShopifyVerify
{
public bool IsAuthenticShopifyRequest(string queryString, string APIKey)
{
var result = AuthorizationService.IsAuthenticRequest(queryString, APIKey);
return result;
}
}
When a call is made to AuthorizationService.IsAuthenticShopifyRequest(string queryString, string APIKey), it always returns false and thus not able to authenticate the shop. This piece of code was running without error before now. This issue started some couple of weeks back.
Did anything change in shopifysharp? If not please what do I need to do to get this work and if shopifysharp changed the implementation of AuthorizationService.IsAuthenticRequest(queryString, APIKey); please I need help in resolving this.
Thanks.

Rename default admin role in ABP framework

Is there a way to rename the default admin role to something else, e.g. system admin or super admin ? In some contexts , admin may refer to task administrator or maybe other administrator and I'd use that for something else.
Yes, I can delete all permission granted to admin and grant them to system admin, however I'm not sure other places where the default admin are used in.
And since data seeder is hardcoded to admin, I'm kinda stuck here.
This is how I handled it:
public static class IdentityDataSeederProperties
{
public static String AdminUserName { get; set; } = "admin";
public static String AdminRoleName { get; set; } = "admin";
}
[Dependency(ReplaceServices = true)]
public class IdentityDataSeeder : ITransientDependency, IIdentityDataSeeder
{
protected IGuidGenerator GuidGenerator { get; }
protected IIdentityRoleRepository RoleRepository { get; }
protected IIdentityUserRepository UserRepository { get; }
protected ILookupNormalizer LookupNormalizer { get; }
protected IdentityUserManager UserManager { get; }
protected IdentityRoleManager RoleManager { get; }
protected ICurrentTenant CurrentTenant { get; }
protected IOptions<IdentityOptions> IdentityOptions { get; }
protected ILogger<IdentityDataSeeder> Logger { get; }
public IdentityDataSeeder(
IGuidGenerator guidGenerator,
IIdentityRoleRepository roleRepository,
IIdentityUserRepository userRepository,
ILookupNormalizer lookupNormalizer,
IdentityUserManager userManager,
IdentityRoleManager roleManager,
ICurrentTenant currentTenant,
IOptions<IdentityOptions> identityOptions,
ILogger<IdentityDataSeeder> logger)
{
GuidGenerator = guidGenerator;
RoleRepository = roleRepository;
UserRepository = userRepository;
LookupNormalizer = lookupNormalizer;
UserManager = userManager;
RoleManager = roleManager;
CurrentTenant = currentTenant;
IdentityOptions = identityOptions;
Logger = logger;
}
public virtual async Task<IdentityDataSeedResult> SeedAsync(String adminEmail, String adminPassword, Guid? tenantId = null)
{
Check.NotNullOrWhiteSpace(adminEmail, nameof(adminEmail));
Check.NotNullOrWhiteSpace(adminPassword, nameof(adminPassword));
using (CurrentTenant.Change(tenantId))
{
await IdentityOptions.SetAsync().ConfigureAwait(false);
var result = await CreateAdminUserAndRoleAsync(adminEmail, adminPassword, tenantId).ConfigureAwait(false);
await AddAdminUserToAdminRole().ConfigureAwait(false);
return result;
}
}
[UnitOfWork]
private async Task AddAdminUserToAdminRole()
{
var adminUser = await UserRepository
.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName(IdentityDataSeederProperties.AdminUserName))
.ConfigureAwait(false);
(await UserManager.AddToRoleAsync(adminUser, IdentityDataSeederProperties.AdminRoleName).ConfigureAwait(false)).CheckErrors();
}
[UnitOfWork]
private async Task<IdentityDataSeedResult> CreateAdminUserAndRoleAsync(String adminEmail, String adminPassword, Guid? tenantId)
{
return new IdentityDataSeedResult
{
CreatedAdminUser = await CreateAdminUserIfItDoesNotExistAsync(tenantId, adminEmail, adminPassword).ConfigureAwait(false),
CreatedAdminRole = await CreateAdminRoleIfItDoesNotExistAsync(tenantId).ConfigureAwait(false)
};
}
private async Task<Boolean> CreateAdminRoleIfItDoesNotExistAsync(Guid? tenantId)
{
var adminRole = await RoleRepository
.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName(IdentityDataSeederProperties.AdminRoleName))
.ConfigureAwait(false);
if (adminRole == null)
{
adminRole = new IdentityRole(GuidGenerator.Create(), IdentityDataSeederProperties.AdminRoleName, tenantId)
{
IsStatic = true,
IsPublic = true
};
(await RoleManager.CreateAsync(adminRole).ConfigureAwait(false)).CheckErrors();
Logger.LogInformation("Created Role: {RoleName} ({RoleId})", adminRole.Name, adminRole.Id);
return true;
}
return false;
}
private async Task<Boolean> CreateAdminUserIfItDoesNotExistAsync(Guid? tenantId, String adminEmail, String adminPassword)
{
var adminUser = await UserRepository.FindByNormalizedUserNameAsync(
LookupNormalizer.NormalizeName(IdentityDataSeederProperties.AdminUserName)
).ConfigureAwait(false);
if (adminUser == null)
{
adminUser = new IdentityUser(GuidGenerator.Create(), IdentityDataSeederProperties.AdminUserName, adminEmail, tenantId)
{
Name = IdentityDataSeederProperties.AdminUserName
};
(await UserManager.CreateAsync(adminUser, adminPassword, validatePassword: false).ConfigureAwait(false)).CheckErrors();
Logger.LogInformation("Created User: {RoleName} ({RoleId})", adminUser.Name, adminUser.Id);
return true;
}
return false;
}
}
The key is the [Dependency(ReplaceServices = true)] attribute. It causes the DI system to replace the default implementation with mine.
NOTE: I refactored the default implementation (and added logging) which is why I didn't just inherit from it, as suggested in #9641.

FluentValidation failure not returning BadRequest

I have wired up FluentValidation as per instructions, and when debuging test I can see that model is invalid based on the test setup, but exception is not thrown, but rather method on the controller is being executed. This is on 3.1 with EndPoint routing enabled. Is there anything else one needs to do to get this to work and throw. What happens is that validation obviously runs; it shows as ModelState invalid and correct InstallmentId is invalid, but it keeps processing in Controller instead of throwing exception.
services.AddMvc(
options =>
{
options.EnableEndpointRouting = true;
//// options.Filters.Add<ExceptionFilter>();
//// options.Filters.Add<CustomerRequestFilter>();
})
.AddFluentValidation(
config =>
{
config.RegisterValidatorsFromAssemblyContaining<Startup>();
})
Command and Validator
public class ProcessManualPayment
{
public class Command
: CustomerRequest<Result?>
{
public Guid PaymentPlanId { get; set; }
public Guid InstallmentId { get; set; }
public Guid PaymentCardId { get; set; }
}
public class Validator : AbstractValidator<Command>
{
public Validator()
{
this.RuleFor(x => x.CustomerId)
.IsValidGuid();
this.RuleFor(x => x.PaymentPlanId)
.IsValidGuid();
this.RuleFor(x => x.InstallmentId)
.IsValidGuid();
this.RuleFor(x => x.PaymentCardId)
.IsValidGuid();
}
}
Controller
[Authorize]
[HttpPost]
[Route("payments")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ProcessManualPayment(
[FromBody]
ProcessManualPayment.Command command)
{
Test
[Fact]
public async Task When_Command_Has_Invalid_Payload_Should_Fail()
{
var client = this.factory.CreateClient();
// Arrange
var validCmd = new ProcessManualPayment.Command()
{
CustomerId = Guid.NewGuid(),
PaymentPlanId = Guid.NewGuid(),
InstallmentId = Guid.NewGuid(),
PaymentCardId = Guid.NewGuid(),
};
var validCmdJson = JsonConvert.SerializeObject(validCmd, Formatting.None);
var jObject = JObject.Parse(validCmdJson);
jObject["installmentId"] = "asdf";
var payload = jObject.ToString(Formatting.None);
// Act
var content = new StringContent(payload, Encoding.UTF8, MediaTypeNames.Application.Json);
var response = await client.PostAsync(MakePaymentUrl, content);
var returned = await response.Content.ReadAsStringAsync();
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
[Fact]
public async Task When_Payload_Is_Null_Should_Fail()
{
// Arrange
var client = this.factory.CreateClient();
// Act
var response = await client.PostAsJsonAsync(MakePaymentUrl, null);
// Assert
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
GuidValidator
public class GuidValidator : PropertyValidator
{
public GuidValidator()
: base("'{PropertyName}' value {AttemptedValue} is not a valid Guid.")
{
}
protected override bool IsValid(PropertyValidatorContext context)
{
context.MessageFormatter.AppendArgument("AttemptedValue", context.PropertyValue ?? "'null'");
if (context.PropertyValue == null)
{
return false;
}
Guid.TryParse(context.PropertyValue.ToString(), out var value);
return IsValid(value);
}
private static bool IsValid(Guid? value) =>
value.HasValue
&& !value.Equals(Guid.Empty);
}
Mystery solved, I was missing [ApiController] attribute on the controller.

How to extract methods from controller?

I want to extract "what I can" to the service. I have this method in the controller:
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
LoginViewModel loginViewModel = new LoginViewModel
{
ReturnUrl = returnUrl,
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
};
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View("Login", loginViewModel);
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ModelState.AddModelError(string.Empty, "Error loading external login information.");
return View("Login", loginViewModel);
}
var signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (signInResult.Succeeded)
{
return LocalRedirect(returnUrl);
}
else
{
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
if (email != null)
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
{
user = new ApplicationUser
{
UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
Email = info.Principal.FindFirstValue(ClaimTypes.Email)
};
await _userManager.CreateAsync(user);
}
await _userManager.AddLoginAsync(user, info);
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
ViewBag.ErrorTitle = $"Nie otrzymano informacji o adresie e-mail od dostawcy: {info.LoginProvider}";
ViewBag.ErrorMessage = "Proszę skontaktować się z supportem fryzjer#aplikacjafryzjer.com";
return View("Error");
}
}
Some properties are available only for classes that inherit from Controller, eg. ModelState or Url.
Can I extract these parts of the code too? A service can inherit from a controller, but won't it become a controller then?
------------------------------------------------------------ EDIT ---------------------------------------------------------------
Ok I tried separate my method from the controller. Below my previous code Controller:
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailService _emailService;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailService emailService)
{
_userManager = userManager;
_signInManager = signInManager;
_emailService = emailService;
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
//register functionality
var user = new ApplicationUser
{
FirstName = model.FirstName,
LastName = model.LastName,
UserName = model.Email,
Email = model.Email,
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
if (_signInManager.IsSignedIn(User) && User.IsInRole("Admin"))
{
return RedirectToAction("ListUsers", "Administrator");
}
//login user
await _signInManager.SignInAsync(user, isPersistent: false);
//generation of the email token
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var link = Url.Action(nameof(VerifyEmail), "Home", new { userId = user.Id, code }, Request.Scheme, Request.Host.ToString());
await _emailService.SendAsync(user.Email, "Weryfikacja adresu e-mail", $"Potwierdź e-mail", true);
return RedirectToAction("EmailVerification");
}
}
return View(model);
}
}
And my Controller now:
public class AccountController : Controller
{
private readonly IUserManager _userManager;
public AccountController(
IUserManager userManager)
{
_userManager = userManager;
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
(string action, string controller) = await _userManager.Register(model);
return RedirectToAction(action, controller);
}
return View(model);
}
}
I am sure, something is wrong. I have no idea how separate this logic from the controller, but on the other forums I heard "U have to separate your logic from the controller! Your controller have to be simple - only get request and send response, thats all!". but now, when I started rebuild my project, I am not sure isn't this more complicated...
In my service I return a tuple (???), because I have not better idea...
public async Task<(string, string)> Register(RegisterViewModel model)
{
//register functionality
var user = new ApplicationUser
{
FirstName = model.FirstName,
LastName = model.LastName,
UserName = model.Email,
Email = model.Email,
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
if (_signInManager.IsSignedIn(User) && User.IsInRole("Admin"))
{
return ("ListUsers", "Administrator");
}
//login user
await _signInManager.SignInAsync(user, isPersistent: false);
//generation of the email token
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var link = _urlHelper.Action(nameof(VerifyEmail), "Home", new { userId = user.Id, code });
await _emailService.SendAsync(user.Email, "Weryfikacja adresu e-mail", $"Potwierdź e-mail", true);
return ("EmailVerification", "Administrator");
}
return ("Register", "Administrator");
}
As far as I know, if you want to use Url in other custom service which is not inherit from controller. You could inject the IActionContextAccessor and use IUrlHelperFactory to create the it. Besides, if you want to use other controller based property or method, you could refer asp.net core source codes and find it work and then you could write the codes by yourself.
More details, you could refer to below codes:
Firstly you could inject the IActionContextAccessor in the startup.cs ConfigureServices method:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
Then you could use DI and factory to create the URLhelper like below:
public class GetRoute : IGetRoute
{
private IUrlHelper _urlHelper;
private IActionContextAccessor _IActionContextAccessor;
public IUrlHelper Url
{
get
{
if (_urlHelper == null)
{
_urlHelper = _urlHelperFactory.GetUrlHelper(_IActionContextAccessor.ActionContext);
}
return _urlHelper;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_urlHelper = value;
}
}
private readonly IUrlHelperFactory _urlHelperFactory ;
public GetRoute(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider, IUrlHelperFactory urlHelperFactory, IActionContextAccessor actionContextAccessor)
{
_IActionContextAccessor = actionContextAccessor;
_urlHelperFactory = urlHelperFactory;
}
public string Getlink() {
return Url.Link("default", "aaaa");
}
}

How do I use my custom ServiceStack authentication provider with Redis?

I have implemented a custom CredentialsAuthProvider for my authentication and used it with the default in memory session storage.
Now I tried to change the session storage to Redis and added this to my Configure() method in the AppHost:
container.Register<IRedisClientsManager>(c =>
new PooledRedisClientManager("localhost:6379"));
container.Register<ICacheClient>(c => (ICacheClient)c
.Resolve<IRedisClientsManager>()
.GetCacheClient()).ReusedWithin(Funq.ReuseScope.None);
Now when I authenticate, I can see that a key with urn:iauthsession:... is added to my Redis server. But all routes with the [Authenticate] attribute give a 401 Unauthorized error.
The CustomCredentialsAuthProvider is implemented like this:
public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
if (userName != string.Empty && password != string.Empty)
{
// Database call ...
var session = (CustomSession)authService.GetSession();
session.ClientId = login.ClientId;
// Fill session...
authService.SaveSession(session, SessionExpiry);
return true;
}
return false;
}
}
ServiceStack Version: 3.9.71
EDIT :
I tried to override the CredentialsAuthProvider IsAuthorized method but without success.
But I'm inheriting my session object from AuthUserSession, which also has a IsAuthorized method. When I return true from this method the Redis session does work with the Authenticate Attribute.
public class CustomSession : AuthUserSession
{
public int ClientId { get; set; }
...
public override bool IsAuthorized(string provider)
{
return true;
}
}
The Authenticate attribute calls the IsAuthorized of the AuthUserSession class.
In my case to make it work with the Redis cache client, I've done the following
public override bool IsAuthorized(string provider)
{
string sessionKey = SessionFeature.GetSessionKey(this.Id);
ICacheClient cacheClient = AppHostBase.Resolve<ICacheClient>();
CustomUserSession session = cacheClient.Get<CustomUserSession>(sessionKey);
if (session == null)
{
return false;
}
return session.IsAuthenticated;
}
I couldn't figure out a way to get the [Authenticate] Attribute to work with Redis storage.
I had to write a custom [SessionAuth] Attribute
public class SessionAuthAttribute : RequestFilterAttribute
{
public ICacheClient cache { get; set; }
public string HtmlRedirect { get; set; }
public SessionAuthAttribute()
{
}
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
string sessionId = req.GetSessionId();
if (string.IsNullOrEmpty(sessionId))
{
HandleNoSession(req, res);
}
else
{
var session = cache.Get<CustomSession>("urn:iauthsession:" + sessionId);
if (session == null || !session.IsAuthenticated)
{
HandleNoSession(req, res);
}
}
}
private void HandleNoSession(IHttpRequest req, IHttpResponse res)
{
if (req.ResponseContentType.MatchesContentType(MimeTypes.Html))
{
res.RedirectToUrl(HtmlRedirect);
res.End();
}
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.Write("not authorized");
res.Close();
}
}
In my AppHost Configure() method I just register the SessionFeature and the IRedisClientsManager/ICacheClient:
Plugins.Add(new SessionFeature());
container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));
container.Register<ICacheClient>(c => (ICacheClient)c.Resolve<IRedisClientsManager>()
.GetCacheClient()).ReusedWithin(Funq.ReuseScope.None);
The CustomSession class inherits from AuthUserSession:
public class CustomSession : AuthUserSession
{
public int ClientId { get; set; }
...
}
And I have a normal service route on /login/auth for the authentication part and a /login/logout route to remove the session:
public class LoginService : Service
{
public ICacheClient cache { get; set; }
public object Post(AuthRequest request)
{
string userName = request.UserName;
string password = request.Password;
// check login allowed
if (IsAllowed)
{
var session = SessionFeature.GetOrCreateSession<CustomSession>(cache);
session.ClientId = login.ClientId;
...
session.IsAuthenticated = true;
session.Id = SessionFeature.GetSessionId();
this.SaveSession(session, TimeSpan.FromSeconds(30 * 60));
return true;
}
return false;
}
[SessionAuth]
public object Any(LogoutRequest request)
{
this.RemoveSession();
return true;
}
}
}
I'm still interested in a solution that works with the normal [Authenticate] Attribute.