public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { IAuthTokens tokens = Init(authService, ref session, request); IRequest httpRequest = authService.Request; string error = httpRequest.QueryString["error"] ?? httpRequest.QueryString["error_uri"] ?? httpRequest.QueryString["error_description"]; bool hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error($"Yandex error callback. {httpRequest.QueryString}"); return authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error))); } string code = httpRequest.QueryString["code"]; bool isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { string preAuthUrl = $"{PreAuthUrl}?response_type=code&client_id={ApplicationId}&redirect_uri={CallbackUrl.UrlEncode()}&display=popup&state={Guid.NewGuid().ToString("N")}"; this.SaveSession(authService, session, SessionExpiry); return authService.Redirect(PreAuthUrlFilter(this, preAuthUrl)); } try { string payload = $"grant_type=authorization_code&code={code}&client_id={ApplicationId}&client_secret={ApplicationPassword}"; string contents = AccessTokenUrl.PostStringToUrl(payload); var authInfo = JsonObject.Parse(contents); //Yandex does not throw exception, but returns error property in JSON response // http://api.yandex.ru/oauth/doc/dg/reference/obtain-access-token.xml string accessTokenError = authInfo.Get("error"); if (!accessTokenError.IsNullOrEmpty()) { Log.Error($"Yandex access_token error callback. {authInfo}"); return authService.Redirect(session.ReferrerUrl.SetParam("f", "AccessTokenFailed")); } tokens.AccessTokenSecret = authInfo.Get("access_token"); session.IsAuthenticated = true; return OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()) ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))); } catch (WebException webException) { //just in case Yandex will start throwing exceptions var statusCode = ((HttpWebResponse)webException.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))); } } return authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown"))); }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { session.ReferrerUrl = "".MapHostAbsolutePath(); session.IsAuthenticated = true; authService.SaveSession(session, new TimeSpan(7, 0, 0, 0)); }
public static Response<PedidoItem> Get(this PedidoItem request,Factory factory, IAuthSession authSession) { try{ var data = factory.Execute(proxy=>{ var visitor = ReadExtensions.CreateExpression<PedidoItem>(); visitor.Where(r=>r.IdPedido==request.IdPedido); return proxy.Get(visitor); }); return new Response<PedidoItem>(){ Data=data }; } catch(Exception e){ ResponseStatus rs = new ResponseStatus(){ Message= e.Message, StackTrace=e.StackTrace, ErrorCode= e.ToString() }; return new Response<PedidoItem>(){ ResponseStatus=rs }; } }
public bool HasAnyPermissions(IAuthSession session) { return this.RequiredPermissions .Any(requiredPermission => session != null && session.UserAuthId != null && session.HasPermission(requiredPermission)); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { IAuthTokens tokens = Init(authService, ref session, request); IRequest httpRequest = authService.Request; string error = httpRequest.QueryString["error"]; bool hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error($"Odnoklassniki error callback. {httpRequest.QueryString}"); return authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error))); } string code = httpRequest.QueryString["code"]; bool isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { string preAuthUrl = $"{PreAuthUrl}?client_id={ApplicationId}&redirect_uri={CallbackUrl.UrlEncode()}&response_type=code&layout=m"; this.SaveSession(authService, session, SessionExpiry); return authService.Redirect(PreAuthUrlFilter(this, preAuthUrl)); } try { string payload = $"client_id={ApplicationId}&client_secret={SecretKey}&code={code}&redirect_uri={CallbackUrl.UrlEncode()}&grant_type=authorization_code"; string contents = AccessTokenUrlFilter(this, AccessTokenUrl).PostToUrl(payload, "*/*", RequestFilter); var authInfo = JsonObject.Parse(contents); //ok.ru does not throw exception, but returns error property in JSON response string accessTokenError = authInfo.Get("error"); if (!accessTokenError.IsNullOrEmpty()) { Log.Error($"Odnoklassniki access_token error callback. {authInfo}"); return authService.Redirect(session.ReferrerUrl.SetParam("f", "AccessTokenFailed")); } tokens.AccessTokenSecret = authInfo.Get("access_token"); tokens.UserId = authInfo.Get("user_id"); session.IsAuthenticated = true; return OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()) ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))); } catch (WebException webException) { //just in case it starts throwing exceptions HttpStatusCode statusCode = ((HttpWebResponse)webException.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))); } } return authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown"))); }
protected IAuthTokens Init(IServiceBase authService, ref IAuthSession session, Authenticate request) { Logger.Debug("SamlAuthProvider::Init:ENTER"); if (this.CallbackUrl.IsNullOrEmpty()) { this.CallbackUrl = authService.Request.AbsoluteUri; Logger.Debug("CallbackUrl was null, setting to: {0}".Fmt(this.CallbackUrl)); } if (session.ReferrerUrl.IsNullOrEmpty() && authService.Request != null && authService.Request.Verb == "POST") { session.ReferrerUrl = this.IdpInitiatedRedirect; } else { session.ReferrerUrl = GetReferrerUrl(authService, session, request); } Logger.Debug("Session ReferrerUrl Set to: {0}".Fmt(session.ReferrerUrl)); var tokens = session.ProviderOAuthAccess.FirstOrDefault(x => x.Provider == this.Provider); if (tokens == null) { Logger.Debug("Tokens were null, initializing"); session.ProviderOAuthAccess.Add(tokens = new AuthTokens { Provider = this.Provider }); } Logger.Debug("Tokens contains"); Logger.Debug(tokens.ToJson()); Logger.Debug("SamlAuthProvider::Init:RETURN"); return tokens; }
public string CreateOrMergeAuthSession(IAuthSession authSession, IOAuthTokens tokens) { using (var redis = factory.GetClient()) { UserOAuthProvider oAuthProvider = null; var oAuthProviderId = GetAuthProviderByUserId(redis, tokens.Provider, tokens.UserId); if (!oAuthProviderId.IsNullOrEmpty()) oAuthProvider = redis.As<UserOAuthProvider>().GetById(oAuthProviderId); var userAuth = GetUserAuth(redis, authSession, tokens) ?? new UserAuth { Id = redis.As<UserAuth>().GetNextSequence(), }; if (oAuthProvider == null) { oAuthProvider = new UserOAuthProvider { Id = redis.As<UserOAuthProvider>().GetNextSequence(), UserAuthId = userAuth.Id, Provider = tokens.Provider, UserId = tokens.UserId, }; var idx = IndexProviderToUserIdHash(tokens.Provider); redis.SetEntryInHash(idx, tokens.UserId, oAuthProvider.Id.ToString()); } oAuthProvider.PopulateMissing(tokens); userAuth.PopulateMissing(oAuthProvider); redis.Store(userAuth); redis.Store(oAuthProvider); redis.AddItemToSet(IndexUserAuthAndProviderIdsSet(userAuth.Id), oAuthProvider.Id.ToString()); return userAuth.Id.ToString(); } }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, System.Collections.Generic.Dictionary<string, string> authInfo) { base.OnAuthenticated(authService, session, tokens, authInfo); if (session.Email == AuthTestsBase.AdminEmail) session.Roles.Add(RoleNames.Admin); }
public void LoadUserAuth(IAuthSession session, IAuthTokens tokens) { session.ThrowIfNull("session"); var userAuth = GetUserAuth(session, tokens); LoadUserAuth(session, (UserAuth)userAuth); }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { session.UserName = session.UserAuthName; //Important: You need to save the session! authService.SaveSession(session, SessionExpiry); }
public IUserAuth GetUserAuth(IAuthSession authSession, IAuthTokens tokens) { if (!string.IsNullOrEmpty(authSession.UserAuthId)) { var userAuth = GetUserAuth(authSession.UserAuthId); if (userAuth != null) return userAuth; } if (!string.IsNullOrEmpty(authSession.UserAuthName)) { var userAuth = GetUserAuthByUserName(authSession.UserAuthName); if (userAuth != null) return userAuth; } if (tokens == null || string.IsNullOrEmpty(tokens.Provider) || string.IsNullOrEmpty(tokens.UserId)) return null; var nhSession = GetCurrentSessionFn(sessionFactory); var oAuthProvider = nhSession.QueryOver<UserAuthDetailsNHibernate>() .Where(x => x.Provider == tokens.Provider) .And(x => x.UserId == tokens.UserId) .SingleOrDefault(); if (oAuthProvider != null) { return nhSession.QueryOver<UserAuthNHibernate>() .Where(x => x.Id == oAuthProvider.UserAuthId) .SingleOrDefault(); } return null; }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { session.ReferrerUrl = "/TripThru.TripThruGateway/"; session.IsAuthenticated = true; authService.SaveSession(session, new TimeSpan(7, 0, 0, 0)); }
protected object Authenticate(IServiceBase authService, IAuthSession session, string userName, string password) { if (!LoginMatchesSession(session, userName)) { authService.RemoveSession(); session = authService.GetSession(); } if (TryAuthenticate(authService, userName, password)) { session.IsAuthenticated = true; if (session.UserAuthName == null) session.UserAuthName = userName; var response = OnAuthenticated(authService, session, null, null); if (response != null) return response; return new AuthenticateResponse { UserId = session.UserAuthId, UserName = userName, SessionId = session.Id, }; } throw HttpError.Unauthorized(ErrorMessages.InvalidUsernameOrPassword); }
public bool HasAllRoles(IAuthSession session, IAuthRepository authRepo) { if (session == null) return false; return this.RequiredRoles.All(x => session.HasRole(x, authRepo)); }
public bool HasAllRoles(IAuthSession session) { if (session == null) return false; return this.RequiredRoles.All(session.HasRole); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { var user = authService.Request.GetUser(); var userName = user.GetUserName(); if (!LoginMatchesSession(session, userName)) { authService.RemoveSession(); session = authService.GetSession(); } if (IsAuthorized(user)) { session.IsAuthenticated = true; if (session.UserAuthName == null) { session.UserAuthName = userName; } var aspReq = (HttpRequestBase)authService.Request.OriginalRequest; var loginUser = aspReq.ServerVariables["LOGON_USER"].ToNullIfEmpty(); var remoteUser = aspReq.ServerVariables["REMOTE_USER"].ToNullIfEmpty(); var identityName = aspReq.LogonUserIdentity != null ? aspReq.LogonUserIdentity.Name : null; session.DisplayName = loginUser ?? remoteUser ?? identityName; var tokens = new AuthTokens { Provider = Name, UserName = userName, DisplayName = session.DisplayName, Items = new Dictionary<string, string> { {"LOGON_USER", loginUser}, {"REMOTE_USER", remoteUser}, {"LogonUserIdentityName", identityName}, } }; if (session.Roles == null) session.Roles = new List<string>(); foreach (var role in AllRoles.Safe()) { if (user.IsInRole(role)) session.Roles.AddIfNotExists(role); } OnAuthenticated(authService, session, tokens, new Dictionary<string, string>()); return new AuthenticateResponse { UserName = userName, SessionId = session.Id, DisplayName = session.DisplayName, ReferrerUrl = request.Continue }; } throw HttpError.Unauthorized("Windows Auth failed"); }
public string CreateOrMergeAuthSession(IAuthSession authSession, IOAuthTokens tokens) { var userAuth = GetUserAuth(authSession, tokens) ?? new UserAuth(); return dbFactory.Exec(dbCmd => { var oAuthProvider = dbCmd.FirstOrDefault<UserOAuthProvider>( "Provider = {0} AND UserId = {1}", tokens.Provider, tokens.UserId); if (oAuthProvider == null) { oAuthProvider = new UserOAuthProvider { Provider = tokens.Provider, UserId = tokens.UserId, }; } oAuthProvider.PopulateMissing(tokens); userAuth.PopulateMissing(oAuthProvider); dbCmd.Save(userAuth); oAuthProvider.UserAuthId = userAuth.Id != default(int) ? userAuth.Id : (int) dbCmd.GetLastInsertId(); dbCmd.Save(oAuthProvider); return oAuthProvider.UserAuthId.ToString(); }); }
private object AuthenticateImpl(IServiceBase authService, IAuthSession session, string userName, string password, string referrerUrl) { if (!LoginMatchesSession(session, userName)) { authService.RemoveSession(); session = authService.GetSession(); } if (TryAuthenticate(authService, userName, password)) { session.IsAuthenticated = true; if (session.UserAuthName == null) { session.UserAuthName = userName; } var response = OnAuthenticated(authService, session, null, null); if (response != null) return response; var bytes = Encoding.UTF8.GetBytes(userName + ":" + password); return new CustomAuthenticateResponse { UserId = session.UserAuthId, UserName = userName, SessionId = session.Id, ReferrerUrl = referrerUrl, AccessToken = Convert.ToBase64String(bytes) }; } throw HttpError.Unauthorized(ErrorMessages.InvalidUsernameOrPassword); }
public UserAuth GetUserAuth(IAuthSession authSession, IOAuthTokens tokens) { if (!authSession.UserAuthId.IsNullOrEmpty()) { var userAuth = GetUserAuth(authSession.UserAuthId); if (userAuth != null) return userAuth; } if (!authSession.UserAuthName.IsNullOrEmpty()) { var userAuth = GetUserAuthByUserName(authSession.UserAuthName); if (userAuth != null) return userAuth; } if (tokens == null || tokens.Provider.IsNullOrEmpty() || tokens.UserId.IsNullOrEmpty()) return null; var oAuthProvider = Session.QueryOver<UserOAuthProviderPersistenceDto>() .Where(x => x.Provider == tokens.Provider) .And(x => x.UserId == tokens.UserId) .SingleOrDefault(); if (oAuthProvider != null) { return Session.QueryOver<UserAuthPersistenceDto>() .Where(x => x.Id == oAuthProvider.UserAuthId) .SingleOrDefault(); } return null; }
public IUserAuth GetUserAuth(IAuthSession authSession, IAuthTokens tokens) { //if (!authSession.UserAuthId.IsNullOrEmpty()) //{ // var userAuth = GetUserAuth(authSession.UserAuthId); // if (userAuth != null) // { // return userAuth; // } //} if (!authSession.UserAuthName.IsNullOrEmpty()) { var userAuth = GetUserAuthByUserName(authSession.UserAuthName); if (userAuth != null) { return userAuth; } } if (tokens == null || tokens.Provider.IsNullOrEmpty() || tokens.UserId.IsNullOrEmpty()) { return null; } return null; }
public bool HasAllPermissions(IAuthSession session) { if (session == null) return false; return this.RequiredPermissions.All(session.HasPermission); }
public bool HasAllPermissions(IAuthSession session, IAuthRepository authRepo) { if (session == null) return false; return this.RequiredPermissions.All(x => session.HasPermission(x, authRepo)); }
/// <summary> /// Saves the Auth Tokens for this request. Called in OnAuthenticated(). /// Overrideable, the default behaviour is to call IUserAuthRepository.CreateOrMergeAuthSession(). /// </summary> protected virtual void SaveUserAuth(IServiceBase authService, IAuthSession session, IUserAuthRepository authRepo, IOAuthTokens tokens) { if (authRepo == null) return; if (tokens != null) { session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens); } authRepo.LoadUserAuth(session, tokens); foreach (var oAuthToken in session.ProviderOAuthAccess) { var authProvider = AuthService.GetAuthProvider(oAuthToken.Provider); if (authProvider == null) continue; var userAuthProvider = authProvider as OAuthProvider; if (userAuthProvider != null) { userAuthProvider.LoadUserOAuthProvider(session, oAuthToken); } } authRepo.SaveUserAuth(session); var httpRes = authService.RequestContext.Get<IHttpResponse>(); if (httpRes != null) { httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId); } OnSaveUserAuth(authService, session); }
/// <summary> /// The on-authenticated event handler. /// </summary> /// <param name="authService">The authentication service.</param> /// <param name="session">The authentication session.</param> /// <param name="tokens">The authentication tokens.</param> /// <param name="authInfo">The authentication information.</param> public override void OnAuthenticated( IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo) { base.OnAuthenticated(authService, session, tokens, authInfo); }
public void LoadUserAuth(IAuthSession session, IAuthTokens tokens) { if (session == null) throw new ArgumentNullException(nameof(session)); var userAuth = GetUserAuth(session, tokens); LoadUserAuth(session, (UserAuth)userAuth); }
/// <summary> /// Método que se ejecuta cuando se ha autenticado con éxito /// </summary> /// <param name="authService">Servicio que solicita la autenticación</param> /// <param name="session">Información de sesión</param> /// <param name="tokens">Tokets</param> /// <param name="authInfo">Información de autenticación</param> /// <returns></returns> public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo) { session.FirstName = _fullName; authService.SaveSession(session); return null; }
public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) { if (request != null) { if (!LoginMatchesSession(session, request.UserName)) return false; } return tokens != null && !string.IsNullOrEmpty(tokens.AccessTokenSecret); }
private void LoadUserAuth(IAuthSession session, UserAuth userAuth) { if (userAuth == null) return; session.PopulateWith(userAuth); session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture); session.ProviderOAuthAccess = GetUserAuthDetails(session.UserAuthId) .ConvertAll(x => (IAuthTokens)x); }
public override void LoadUserOAuthProvider(IAuthSession authSession, IAuthTokens tokens) { var userSession = authSession as AuthUserSession; if (userSession == null) return; userSession.TwitterUserId = tokens.UserId ?? userSession.TwitterUserId; userSession.TwitterScreenName = tokens.UserName ?? userSession.TwitterScreenName; userSession.DisplayName = tokens.DisplayName ?? userSession.DisplayName; }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { //Fill the IAuthSession with data which you want to retrieve in the app eg: //session.FirstName = "some_firstname_from_db"; //... //Important: You need to save the session! authService.SaveSession(session, SessionExpiry); }
public static bool IsAuthorizedSafe(this IAuthProvider authProvider, IAuthSession session, IOAuthTokens tokens) { return(authProvider != null && authProvider.IsAuthorized(session, tokens)); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { throw new NotImplementedException(); }
public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) { return(session != null && session.IsAuthenticated && !session.UserAuthName.IsNullOrEmpty()); }
public abstract object Authenticate(IServiceBase authService, IAuthSession session, Auth request);
public static JsonObject CreateJwtPayload( IAuthSession session, string issuer, TimeSpan expireIn, IEnumerable <string> audiences = null, IEnumerable <string> roles = null, IEnumerable <string> permissions = null) { var now = DateTime.UtcNow; var jwtPayload = new JsonObject { { "iss", issuer }, { "sub", session.UserAuthId }, { "iat", now.ToUnixTime().ToString() }, { "exp", now.Add(expireIn).ToUnixTime().ToString() }, }; jwtPayload.SetAudience(audiences?.ToList()); if (!string.IsNullOrEmpty(session.Email)) { jwtPayload["email"] = session.Email; } if (!string.IsNullOrEmpty(session.FirstName)) { jwtPayload["given_name"] = session.FirstName; } if (!string.IsNullOrEmpty(session.LastName)) { jwtPayload["family_name"] = session.LastName; } if (!string.IsNullOrEmpty(session.DisplayName)) { jwtPayload["name"] = session.DisplayName; } if (!string.IsNullOrEmpty(session.UserName)) { jwtPayload["preferred_username"] = session.UserName; } else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@")) { jwtPayload["preferred_username"] = session.UserAuthName; } var profileUrl = session.GetProfileUrl(); if (profileUrl != null && profileUrl != Svg.GetDataUri(Svg.Icons.DefaultProfile)) { jwtPayload["picture"] = profileUrl; } var combinedRoles = new List <string>(session.Roles.Safe()); var combinedPerms = new List <string>(session.Permissions.Safe()); roles.Each(x => combinedRoles.AddIfNotExists(x)); permissions.Each(x => combinedPerms.AddIfNotExists(x)); if (combinedRoles.Count > 0) { jwtPayload["roles"] = combinedRoles.ToJson(); } if (combinedPerms.Count > 0) { jwtPayload["perms"] = combinedPerms.ToJson(); } return(jwtPayload); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { IAuthTokens tokens = Init(authService, ref session, request); IRequest httpRequest = authService.Request; string error = httpRequest.QueryString["error"] ?? httpRequest.QueryString["error_reason"] ?? httpRequest.QueryString["error_description"]; bool hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error("VK error callback. {0}".Fmt(httpRequest.QueryString)); return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", (httpRequest.QueryString["error_reason"] ?? httpRequest.QueryString["error_description"] ?? "Unknown").UrlEncode()))); } string code = httpRequest.QueryString["code"]; bool isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { string url = PreAuthUrl + "?client_id={0}&scope={1}&redirect_uri={2}&response_type=code&v={3}" .Fmt(ApplicationId, Scope, CallbackUrl.UrlEncode(), ApiVersion); authService.SaveSession(session, SessionExpiry); return(authService.Redirect(url)); } try { code = EnsureLatestCode(code); string accessTokeUrl = AccessTokenUrl + "?client_id={0}&client_secret={1}&code={2}&redirect_uri={3}" .Fmt(ApplicationId, SecureKey, code, CallbackUrl.UrlEncode()); string contents = accessTokeUrl.GetStringFromUrl("*/*", RequestFilter); var authInfo = JsonObject.Parse(contents); //VK does not throw exception, but returns error property in JSON response string accessTokenError = authInfo.Get("error") ?? authInfo.Get("error_description"); if (!accessTokenError.IsNullOrEmpty()) { Log.Error("VK access_token error callback. {0}".Fmt(authInfo.ToString())); return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"))); } tokens.AccessTokenSecret = authInfo.Get("access_token"); tokens.UserId = authInfo.Get("user_id"); session.IsAuthenticated = true; authService.SaveSession(session, SessionExpiry); OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()); return(authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"))); } catch (WebException webException) { //just in case VK will start throwing exceptions HttpStatusCode statusCode = ((HttpWebResponse)webException.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"))); } } return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"))); }
public virtual IHttpResult Validate(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) => null;
public override Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default) { //new CredentialsAuthValidator().ValidateAndThrow(request); return(AuthenticateAsync(authService, session, request.UserName, request.Password, token)); }
public override async Task <IHttpResult> OnAuthenticatedAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default) { session.AuthProvider = Name; if (session is AuthUserSession userSession) { await LoadUserAuthInfoAsync(userSession, tokens, authInfo, token).ConfigAwait(); HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo); LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo); if (LoadUserAuthInfoFilterAsync != null) { await LoadUserAuthInfoFilterAsync(userSession, tokens, authInfo, token); } } if (session is IAuthSessionExtended authSession) { // ReSharper disable once MethodHasAsyncOverloadWithCancellation var failed = authSession.Validate(authService, session, tokens, authInfo) ?? await authSession.ValidateAsync(authService, session, tokens, authInfo, token) ?? AuthEvents.Validate(authService, session, tokens, authInfo) ?? (AuthEvents is IAuthEventsAsync asyncEvents ? await asyncEvents.ValidateAsync(authService, session, tokens, authInfo, token) : null); if (failed != null) { await authService.RemoveSessionAsync(token).ConfigAwait(); return(failed); } } var authRepo = GetUserAuthRepositoryAsync(authService.Request); await using (authRepo as IAsyncDisposable) { if (authRepo != null) { if (tokens != null) { authInfo.ForEach((x, y) => tokens.Items[x] = y); session.UserAuthId = (await authRepo.CreateOrMergeAuthSessionAsync(session, tokens, token)).UserAuthId.ToString(); } foreach (var oAuthToken in session.GetAuthTokens()) { var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider); var userAuthProvider = authProvider as OAuthProvider; userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken); } var failed = await ValidateAccountAsync(authService, authRepo, session, tokens, token).ConfigAwait(); if (failed != null) { return(failed); } } } try { session.IsAuthenticated = true; session.OnAuthenticated(authService, session, tokens, authInfo); if (session is IAuthSessionExtended sessionExt) { await sessionExt.OnAuthenticatedAsync(authService, session, tokens, authInfo, token).ConfigAwait(); } AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo); if (AuthEvents is IAuthEventsAsync asyncEvents) { await asyncEvents.OnAuthenticatedAsync(authService.Request, session, authService, tokens, authInfo, token).ConfigAwait(); } } finally { await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait(); authService.Request.Items[Keywords.DidAuthenticate] = true; } return(null); }
public virtual void OnSaveUserAuth(IServiceBase authService, IAuthSession session) { }
public abstract bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null);
private void LoadUserAuth(IAuthSession session, IUserAuth userAuth) { session.PopulateSession(userAuth, GetUserAuthDetails(session.UserAuthId).ConvertAll(x => (IAuthTokens)x)); }
public static List <IAuthTokens> GetAuthTokens(this IAuthSession session) { return(session.ProviderOAuthAccess ?? TypeConstants <IAuthTokens> .EmptyList); }
public virtual Task OnAuthenticatedAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default) => TypeConstants.EmptyTask;
public virtual Task <IHttpResult> ValidateAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default) => ((IHttpResult)null).InTask();
public virtual Task OnRegisteredAsync(IRequest httpReq, IAuthSession session, IServiceBase service, CancellationToken token = default) => TypeConstants.EmptyTask;
public bool HasAllRoles(IAuthSession session) { return(this.RequiredRoles .All(requiredRole => session != null && session.HasRole(requiredRole))); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { // TODO: WARN: Property 'redirect' does not exist on type 'ServiceStack.Authenticate' // TODO: WARN: Property 'code' does not exist on type 'ServiceStack.Authenticate' // TODO: WARN: Property 'session_state' does not exist on type 'ServiceStack.Authenticate' // TODO: The base Init() should strip the query string from the request URL if (CallbackUrl.IsNullOrEmpty()) { CallbackUrl = new Uri(authService.Request.AbsoluteUri).GetLeftPart(UriPartial.Path); } var tokens = Init(authService, ref session, request); var httpRequest = authService.Request; var query = httpRequest.QueryString; if (HasError(query.ToNameValueCollection())) { return(RedirectDueToFailure(authService, session, query.ToNameValueCollection())); } // 1. The client application starts the flow by redirecting the user agent // to the Azure AD authorization endpoint. The user authenticates and // consents, if consent is required. // TODO: Can State property be added to IAuthSession to avoid this cast var userSession = session as AuthUserSession; if (userSession == null) { throw new NotSupportedException("Concrete dependence on AuthUserSession because of State property"); } //var code = query["code"]; //if (code.IsNullOrEmpty()) // return RequestCode(authService, session, userSession, tokens); string code = httpRequest.FormData["access_token"]; if (code.IsNullOrEmpty()) { return(RequestCode(authService, session, userSession, tokens)); } var state = httpRequest.FormData["state"]; if (state != userSession.State) { session.IsAuthenticated = false; throw new UnauthorizedAccessException("Mismatched state in code response."); } // 2. The Azure AD authorization endpoint redirects the user agent back // to the client application with an authorization code. The user // agent returns authorization code to the client application’s redirect URI. // 3. The client application requests an access token from the // Azure AD token issuance endpoint. It presents the authorization code // to prove that the user has consented. // return RequestAccessToken(authService, session, code, tokens); // var authInfo = JsonObject.Parse(responseJson); // var authInfoNvc = authInfo.ToNameValueCollection(); //if (HasError(authInfoNvc)) // return RedirectDueToFailure(authService, session, authInfoNvc); tokens.AccessTokenSecret = code; // tokens.RefreshToken = authInfo["refresh_token"]; tokens.AccessToken = code; session.ReferrerUrl = AppSettings.Get <string>($"oauth.{Provider}.RedirectUrl", session.ReferrerUrl); if (state.Contains("?")) { session.ReferrerUrl = session.ReferrerUrl + state.Substring(state.IndexOf("?")); } return(OnAuthenticated(authService, session, tokens, httpRequest.FormData.ToDictionary()) ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access! }
public virtual void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { }
public override async Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default) { IAuthTokens tokens = Init(authService, ref session, request); IRequest httpRequest = authService.Request; if (request?.AccessToken != null && request?.AccessTokenSecret != null) { var authInfo = await GetUserInfoAsync(request.AccessToken, request.AccessTokenSecret).ConfigAwait(); if (authInfo == null || !(authInfo.Get("error") ?? authInfo.Get("error_description")).IsNullOrEmpty()) { Log.Error($"VK access_token error callback. {authInfo}"); return(HttpError.Unauthorized("AccessToken is not for App: " + ApplicationId)); } tokens.AccessToken = request.AccessToken; tokens.AccessTokenSecret = request.AccessTokenSecret; var isHtml = authService.Request.IsHtml(); var failedResult = await AuthenticateWithAccessTokenAsync(authService, session, tokens, request.AccessToken).ConfigAwait(); if (failedResult != null) { return(ConvertToClientError(failedResult, isHtml)); } return(isHtml ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))) : null); //return default AuthenticateResponse } string error = httpRequest.QueryString["error_reason"] ?? httpRequest.QueryString["error_description"] ?? httpRequest.QueryString["error"]; bool hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error($"VK error callback. {httpRequest.QueryString}"); return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error)))); } string code = httpRequest.QueryString["code"]; bool isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { string preAuthUrl = $"{PreAuthUrl}?client_id={ApplicationId}&scope={Scope}&redirect_uri={CallbackUrl.UrlEncode()}&response_type=code&v={ApiVersion}"; await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait(); return(authService.Redirect(PreAuthUrlFilter(this, preAuthUrl))); } try { code = EnsureLatestCode(code); string accessTokeUrl = $"{AccessTokenUrl}?client_id={ApplicationId}&client_secret={SecureKey}&code={code}&redirect_uri={CallbackUrl.UrlEncode()}"; string contents = await AccessTokenUrlFilter(this, accessTokeUrl).GetStringFromUrlAsync("*/*", RequestFilter).ConfigAwait(); var authInfo = JsonObject.Parse(contents); //VK does not throw exception, but returns error property in JSON response string accessTokenError = authInfo.Get("error") ?? authInfo.Get("error_description"); if (!accessTokenError.IsNullOrEmpty()) { Log.Error($"VK access_token error callback. {authInfo}"); return(authService.Redirect(session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))); } tokens.AccessTokenSecret = authInfo.Get("access_token"); tokens.UserId = authInfo.Get("user_id"); session.IsAuthenticated = true; var accessToken = authInfo["access_token"]; return(await OnAuthenticatedAsync(authService, session, tokens, authInfo.ToDictionary(), token).ConfigAwait() ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); } catch (WebException webException) { //just in case VK will start throwing exceptions HttpStatusCode statusCode = ((HttpWebResponse)webException.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed")))); } } return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown")))); }
public virtual void OnRegistered(IRequest httpReq, IAuthSession session, IServiceBase service) { }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { var tokens = this.Init(authService, ref session, request); var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl) }; if (AuthServerFilter != null) { AuthServerFilter(authServer); } var authClient = new WebServerClient(authServer, this.ConsumerKey) { ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret), AuthorizationTracker = new DotNetOpenAuthTokenManager(), }; if (AuthClientFilter != null) { AuthClientFilter(authClient); } var authState = ProcessUserAuthorization(authClient, authServer, authService); if (authState == null) { try { var authReq = authClient.PrepareRequestUserAuthorization(this.Scopes, new Uri(this.CallbackUrl)); var authContentType = authReq.Headers[HttpHeaders.ContentType]; var httpResult = new HttpResult(authReq.ResponseStream, authContentType) { StatusCode = authReq.Status, StatusDescription = "Moved Temporarily" }; foreach (string header in authReq.Headers) { httpResult.Headers[header] = authReq.Headers[header]; } foreach (string name in authReq.Cookies) { var cookie = authReq.Cookies[name]; if (cookie != null) { httpResult.SetSessionCookie(name, cookie.Value, cookie.Path); } } authService.SaveSession(session, this.SessionExpiry); return(httpResult); } catch (ProtocolException ex) { Log.Error("Failed to login to {0}".Fmt(this.Provider), ex); return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown")))); } } var accessToken = authState.AccessToken; if (accessToken != null) { try { tokens.AccessToken = accessToken; tokens.RefreshToken = authState.RefreshToken; tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc; var authInfo = this.CreateAuthInfo(accessToken); session.IsAuthenticated = true; return(OnAuthenticated(authService, session, tokens, authInfo) ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed")))); } } } return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed")))); }
public string CreateJwtBearerToken(IAuthSession session, IEnumerable <string> roles = null, IEnumerable <string> perms = null) => CreateJwtBearerToken(null, session, roles, perms);
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null) { return(false); }
protected virtual async Task <object> AuthenticateWithAccessTokenAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, string accessToken) { var authInfo = await GetUserInfoAsync(tokens.AccessToken, tokens.AccessTokenSecret).ConfigAwait(); session.IsAuthenticated = true; return(await OnAuthenticatedAsync(authService, session, tokens, authInfo).ConfigAwait()); }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, System.Collections.Generic.Dictionary <string, string> authInfo) { //if (session.UserAuthName == AuthTests.UserNameWithSessionRedirect) // session.ReferrerUrl = AuthTests.SessionRedirectUrl; }
public static Task SaveSessionAsync(this IRequest httpReq, IAuthSession session, TimeSpan?expiresIn = null, CancellationToken token = default) { return(HostContext.AppHost.OnSaveSessionAsync(httpReq, session, expiresIn, token)); }
public static void SaveSession(this IRequest httpReq, IAuthSession session, TimeSpan?expiresIn = null) { HostContext.AppHost.OnSaveSession(httpReq, session, expiresIn); }
private IHttpResult RequestAccessToken(IServiceBase authService, IAuthSession session, string code, IAuthTokens tokens) { try { //JsonObject json = new JsonObject(); //json["grant_type"] = "authorization_code"; //json["client_id"] = ClientId; //json["scope"] = Scopes.Join(" ").UrlEncode(); //json["code"] = code; //json["redirect_uri"] = CallbackUrl.UrlEncode(); //json["client_secret"] = ClientSecret; // using (var handler = new HttpClientHandler { Proxy = new WebProxy("127.0.0.1:8888", false) }) // { var content = new System.Net.Http.MultipartFormDataContent(); content.Add(new System.Net.Http.StringContent("authorization_code"), "grant_type"); content.Add(new System.Net.Http.StringContent(ClientId), "client_id"); content.Add(new System.Net.Http.StringContent("openid"), "scope"); content.Add(new System.Net.Http.StringContent(code), "id_token"); content.Add(new System.Net.Http.StringContent(CallbackUrl), "redirect_uri"); content.Add(new System.Net.Http.StringContent(ClientSecret), "client_secret"); HttpClient httpClient = new HttpClient(); HttpResponseMessage response = null; string responseJson = null; // run some async code inside a non-async method Task.Run(async() => { response = await httpClient.PostAsync(AccessTokenUrl, content); responseJson = await response.Content.ReadAsStringAsync(); }).GetAwaiter().GetResult(); // tokens. = authInfo["access_token"]; // var formData = "client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code&resource={4}&scope={5}" // .Fmt(ClientId.UrlEncode(), CallbackUrl.UrlEncode(), ClientSecret.UrlEncode(), code, ResourceId.UrlEncode(), Scopes.Join(" ")); // Endpoint only accepts posts requests // var contents = AccessTokenUrl.PostToUrl(formData); // var contents = AccessTokenUrl.PostJsonToUrl(json.ToString()); // 4. The Azure AD token issuance endpoint returns an access token // and a refresh token. The refresh token can be used to request // additional access tokens. // Response is JSON var authInfo = JsonObject.Parse(responseJson); var authInfoNvc = authInfo.ToNameValueCollection(); if (HasError(authInfoNvc)) { return(RedirectDueToFailure(authService, session, authInfoNvc)); } tokens.AccessTokenSecret = authInfo["access_token"]; tokens.RefreshToken = authInfo["refresh_token"]; tokens.AccessToken = authInfo["id_token"]; return(OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()) ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access! //} } catch (WebException webException) { if (webException.Response == null) { // This could happen e.g. due to a timeout return(RedirectDueToFailure(authService, session, new NameValueCollection { { "error", webException.GetType().ToString() }, { "error_description", webException.Message } })); } Log.Error("Auth Failure", webException); var response = ((HttpWebResponse)webException.Response); var responseText = Encoding.UTF8.GetString( response.GetResponseStream().ReadFully()); var errorInfo = JsonObject.Parse(responseText).ToNameValueCollection(); return(RedirectDueToFailure(authService, session, errorInfo)); } //return RedirectDueToFailure(authService, session, new NameValueCollection()); }
public virtual void OnFailedAuthentication(IAuthSession session, IHttpRequest httpReq, IHttpResponse httpRes) { httpRes.StatusCode = (int)HttpStatusCode.Unauthorized; httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\"".Fmt(this.Provider, this.AuthRealm)); httpRes.EndRequest(); }