DocSpace-client/common/ASC.Api.Core/Auth/CookieAuthHandler.cs

53 lines
2.0 KiB
C#
Raw Normal View History

2019-05-30 14:57:15 +00:00
using System.Net;
using System.Security.Authentication;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
2020-02-17 08:58:14 +00:00
2021-09-08 10:16:58 +00:00
using ASC.Common;
using ASC.Core;
2021-09-07 19:58:01 +00:00
using ASC.Web.Core;
2020-02-17 08:58:14 +00:00
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2019-09-10 12:42:15 +00:00
namespace ASC.Api.Core.Auth
{
2021-09-08 10:16:58 +00:00
[Scope]
public class CookieAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
2021-09-07 19:58:01 +00:00
private SecurityContext SecurityContext { get; }
private CookiesManager CookiesManager { get; }
public CookieAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
}
2019-09-09 12:56:33 +00:00
//
2021-09-07 19:58:01 +00:00
public CookieAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, SecurityContext securityContext, CookiesManager cookiesManager)
: this(options, logger, encoder, clock)
{
2019-09-09 12:56:33 +00:00
SecurityContext = securityContext;
2021-09-07 19:58:01 +00:00
CookiesManager = cookiesManager;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
2019-05-30 15:21:30 +00:00
var token = Context.Request.Cookies["asc_auth_key"] ?? Context.Request.Headers["Authorization"];
var result = SecurityContext.AuthenticateMe(token);
2021-09-07 19:58:01 +00:00
if (!result)
{
SecurityContext.Logout();
CookiesManager.ClearCookies(CookiesType.AuthKey);
CookiesManager.ClearCookies(CookiesType.SocketIO);
}
2019-05-31 10:47:47 +00:00
return Task.FromResult(
result ?
AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)) :
AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))
);
}
}
}