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); }
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 void Warning(IServiceBase @object, string data) { if (this.enabled == false) return; Debug.LogWarning(string.Format("[ <b>{0}</b> ] {1}", @object.GetServiceName(), data), @object as MonoBehaviour); }
public virtual bool TryAuthenticate(IServiceBase authService, string userName, string password) { var authRepo = authService.TryResolve<IAuthRepository>(); if (authRepo == null) { Log.WarnFormat("Tried to authenticate without a registered IUserAuthRepository"); return false; } var session = authService.GetSession(); var digestInfo = authService.Request.GetDigestAuth(); IUserAuth userAuth; if (authRepo.TryAuthenticate(digestInfo, PrivateKey, NonceTimeOut, session.Sequence, out userAuth)) { var holdSessionId = session.Id; session.PopulateWith(userAuth); //overwrites session.Id session.Id = holdSessionId; session.IsAuthenticated = true; session.Sequence = digestInfo["nc"]; session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture); session.ProviderOAuthAccess = authRepo.GetUserAuthDetails(session.UserAuthId) .ConvertAll(x => (IAuthTokens) x); return true; } return false; }
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 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"); }
/// <summary> /// Remove the Users Session /// </summary> /// <param name="service"></param> /// <param name="request"></param> /// <returns></returns> public virtual object Logout(IServiceBase service, Authenticate request) { var feature = HostContext.GetPlugin<AuthFeature>(); var session = service.GetSession(); var referrerUrl = (request != null ? request.Continue : null) ?? (feature.HtmlLogoutRedirect != null ? service.Request.ResolveAbsoluteUrl(feature.HtmlLogoutRedirect) : null) ?? session.ReferrerUrl ?? service.Request.GetHeader("Referer") ?? this.CallbackUrl; session.OnLogout(service); AuthEvents.OnLogout(service.Request, session, service); service.RemoveSession(); if (feature != null && feature.DeleteSessionCookiesOnLogout) { service.Request.Response.DeleteSessionCookies(); } if (service.Request.ResponseContentType == MimeTypes.Html && !string.IsNullOrEmpty(referrerUrl)) return service.Redirect(LogoutUrlFilter(this, referrerUrl.SetParam("s", "-1"))); return new AuthenticateResponse(); }
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 virtual bool TryAuthenticate(IServiceBase authService, string userName, string password) { var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request); using (authRepo as IDisposable) { var session = authService.GetSession(); var digestInfo = authService.Request.GetDigestAuth(); IUserAuth userAuth; if (authRepo.TryAuthenticate(digestInfo, PrivateKey, NonceTimeOut, session.Sequence, out userAuth)) { var holdSessionId = session.Id; session.PopulateWith(userAuth); //overwrites session.Id session.Id = holdSessionId; session.IsAuthenticated = true; session.Sequence = digestInfo["nc"]; session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture); session.ProviderOAuthAccess = authRepo.GetUserAuthDetails(session.UserAuthId) .ConvertAll(x => (IAuthTokens)x); return true; } return false; } }
public virtual IAuthorizationState ProcessUserAuthorization( WebServerClient authClient, AuthorizationServerDescription authServer, IServiceBase authService) { return HostContext.Config.StripApplicationVirtualPath ? authClient.ProcessUserAuthorization(authService.Request.ToHttpRequestBase()) : authClient.ProcessUserAuthorization(); }
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 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 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"))); }
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 bool TryAuthenticate(IServiceBase authService, string userName, string password) { var authRepo = authService.TryResolve<IAuthRepository>().AsUserAuthRepository(authService.GetResolver()); var session = authService.GetSession(); IUserAuth userAuth; if (authRepo.TryAuthenticate(userName, password, out userAuth)) { if (IsAccountLocked(authRepo, userAuth)) return false; // throw new AuthenticationException("This account has been locked"); var holdSessionId = session.Id; session.PopulateWith(userAuth); //overwrites session.Id session.Id = holdSessionId; session.IsAuthenticated = true; session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture); session.ProviderOAuthAccess = authRepo.GetUserAuthDetails(session.UserAuthId) .ConvertAll(x => (IAuthTokens)x); return true; } return false; }
/// <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 override bool TryAuthenticate(IServiceBase authService, string userName, string password) { if (userName == "tech" && password == "radar") { return true; } return SiouxExchangeServer.CheckLogin(userName, password); }
public override bool TryAuthenticate(IServiceBase authService, string userName, string password) { //Add here your custom auth logic (database calls etc) //Return true if credentials are valid, otherwise false sp = new ShibbolethPrincipal(); return sp.firstname!=null; }
/// <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 TryAuthenticate(IServiceBase authService, string userName, string password) { var user = Repository.RepoUsers.GetUserByUserNameOrEmail(userName, userName); if (user == null) return false; //Add here your custom auth logic (database calls etc) //Return true if credentials are valid, otherwise false return Auth.VerifyHashString(password, user.PasswordHash, user.Salt); }
public override void OnAuthenticated( IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { base.OnAuthenticated(authService, session, tokens, authInfo); //Populate all matching fields from this session to your own custom User table var user = session.TranslateTo<User>(); user.Id = int.Parse(session.UserAuthId); //user.GravatarImageUrl64 = !session.Email.IsNullOrEmpty() ? CreateGravatarUrl(session.Email, 64) : null; foreach (var authToken in session.ProviderOAuthAccess) { // //if (authToken.Provider == FacebookAuthProvider.Name) // //{ // // user.FacebookName = authToken.DisplayName; // // user.FacebookFirstName = authToken.FirstName; // // user.FacebookLastName = authToken.LastName; // // user.FacebookEmail = authToken.Email; // //} // //else if (authToken.Provider == GoogleOpenIdOAuthProvider.Name) { user.GoogleUserId = authToken.UserId; user.GoogleFullName = authToken.FullName; user.GoogleEmail = authToken.Email; if (user.Email == null) user.Email = user.GoogleEmail; if (user.UserName == null) user.UserName = user.GoogleUserId; } else if (authToken.Provider == YahooOpenIdOAuthProvider.Name) { user.YahooUserId = authToken.UserId; user.YahooFullName = authToken.FullName; user.YahooEmail = authToken.Email; } } var adminUserNames = AppHost.AppConfig.AdminUserNames; if (AppHost.AppConfig.AdminUserNames.Contains(session.UserAuthName) && !session.HasRole(RoleNames.Admin)) { using (var assignRoles = authService.ResolveService<AssignRolesService>()) { assignRoles.Post(new AssignRoles { UserName = session.UserAuthName, Roles = { RoleNames.Admin } }); //authService.TryResolve<IDbConnectionFactory>().Run(db => db.Save(user)); } } //Resolve the DbFactory from the IOC and persist the user info }
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 override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { //Fill IAuthSession with data you want to retrieve in the app eg: //Load the Session Object session.FirstName = "some_firstname_from_db"; session.LastName = "some_last_name_from_db"; authService.SaveSession(session, SessionExpiry); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { var tokens = Init(authService, ref session, request); var httpRequest = authService.Request; var error = httpRequest.QueryString["error_reason"] ?? httpRequest.QueryString["error"] ?? httpRequest.QueryString["error_code"] ?? httpRequest.QueryString["error_description"]; var hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error("Facebook error callback. {0}".Fmt(httpRequest.QueryString)); return authService.Redirect(session.ReferrerUrl); } var code = httpRequest.QueryString["code"]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = PreAuthUrl + "?client_id={0}&redirect_uri={1}&scope={2}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), string.Join(",", Permissions)); authService.SaveSession(session, SessionExpiry); return authService.Redirect(preAuthUrl); } var accessTokenUrl = this.AccessTokenUrl + "?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), AppSecret, code); try { var contents = accessTokenUrl.GetStringFromUrl(); var authInfo = HttpUtility.ParseQueryString(contents); tokens.AccessTokenSecret = authInfo["access_token"]; session.IsAuthenticated = true; authService.SaveSession(session, SessionExpiry); OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()); //Haz access! return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1")); } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed")); } } //Shouldn't get here return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")); }
public override bool TryAuthenticate(IServiceBase authService, string userName, string password) { Log.Debug("Authenticating {0}...".F(userName)); User user; if (!AuthenticateUser(userName, password, out user)) return false; if (user == null) return false; Log.Debug("Obtaining team for {0}".F(userName)); var team = TeamDbProvider.Instance[user]; if (team == null) return false; Log.Debug("Obtaining game for {0}".F(userName)); var game = GameDbProvider.Instance[team]; if (game == null) return false; var session = authService.GetSession(); // PopulateWith() is really great, but it replaces the default // session ID with the user ID from the database, so save it here var sessionId = session.Id; session.PopulateWith(user); session.Id = sessionId; session.IsAuthenticated = true; // These roles will be used later to check what team the user is on, etc. session.Roles = new List<string> { User.F(user.Id), Team.F(team.Id), Game.F(game.Id) }; session.UserAuthName = userName; session.UserAuthId = user.Id.ToString(CultureInfo.InvariantCulture); var userKey = "User {0}".F(user.Id); var gameKey = "Game {0}".F(game.Id); // Cache the user and game objects so they will be easier to // obtain again later in other service classes (i.e., check-in) if (Global.Cache.Get<User>(userKey) == null) { // This cache entry will remain cached for one day // OR until the user logs out, whichever comes first Global.Cache.Add(userKey, user, TimeSpan.FromDays(1)); } if (Global.Cache.Get<Game>(gameKey) == null) { // This cache entry will stay cached until the // game ends OR if it is invalidated elsewhere Global.Cache.Add(gameKey, game, game.Finish); } return true; }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { // Note: // `session.UserAuthName` is already set to the user's user name. // we use `session.UserName` for the user's secret unique id. var usersRepo = authService.TryResolve<IUsersRepository>(); var user = usersRepo.GetOrCreateUser(session.UserAuthName); session.UserName = user.UserId; authService.SaveSession(session); }
public override bool TryAuthenticate(IServiceBase authService, string userName, string password) { var Roles = new List<string>(); var Permissions = new List<string>(); var dbConnectionFactory = new OrmLiteConnectionFactory("Server = localhost; Database = auth; Uid = root; Pwd = 123", MySqlDialect.Provider); using (var db = dbConnectionFactory.Open()) { LoginModels user = db.Query<LoginModels>("Select * from loginmodels where User=@userName",new{userName = userName}).SingleOrDefault(); if (user==null) { return false; } if (password!=user.Pass) { return false; } //Get All the roles per user List<Roles> roleses = db.Query<Roles>("SELECT `Join1`.`ROLE_ID1` AS `role_Id`, `Join1`.`Name` FROM `LoginModels` AS `Extent1` INNER JOIN (SELECT `Extent2`.`lm_Id`, `Extent2`.`role_Id`, `Extent3`.`role_Id` AS `ROLE_ID1`, `Extent3`.`Name` FROM `login_roles` AS `Extent2` INNER JOIN `Roles` AS `Extent3` ON `Extent3`.`role_Id` = `Extent2`.`role_Id`) AS `Join1` ON `Extent1`.`lm_Id` = `Join1`.`lm_Id` WHERE `Extent1`.`User`=@userName",new { userName = userName }); foreach (var role in roleses) { Roles.Add(role.Name); List<Permissions> permis = db.Query<Permissions>("SELECT `Join1`.`permi_Id`, `Join1`.`Name` FROM `Roles` AS `Extent1` INNER JOIN (SELECT `Extent2`.`role_id`, `Extent2`.`per_id`, `Extent3`.`permi_Id`, `Extent3`.`Name` FROM `roles_permissions` AS `Extent2` INNER JOIN `Permissions` AS `Extent3` ON `Extent3`.`permi_Id` = `Extent2`.`per_id`) AS `Join1` ON `Extent1`.`role_Id` = `Join1`.`role_id` WHERE `Extent1`.`Name` =@role_name ", new { role_name = role.Name }); foreach (var permi in permis) { Permissions.Add(permi.Name); } } } var session = authService.GetSession(false); //Add Repository Method for Validate User if there's one. //if (!Membership.ValidateUser(userName, password)) return false; session.IsAuthenticated = true; session.Id = authService.GetSessionId(); if (session.UserAuthId == null) session.UserAuthId = userName; session.Roles = Roles; //loaded from db session.Permissions = Permissions; //loaded from db if (session.HasRole("admin")) { session.ReferrerUrl = "/api"; //Redirect to Admin Role to the api page } return true; }
private void SaveOrUpdateRegistration(UserLoginType loginType, IServiceBase resolver, IOAuthTokens authToken, Dictionary<string, string> authInfo) { ViewContext context = resolver.ResolveService<ViewContext>(); CommandBus commandBus = resolver.ResolveService<CommandBus>(); IEntityIdGenerator entityIdGenerator = resolver.ResolveService<IEntityIdGenerator>(); Logger.Debug("Login type: {0}", loginType); UserDocument existingUser = context.Users .AsQueryable() .FirstOrDefault(user => user.ThirdPartyId == authToken.UserId && user.LoginType == loginType); if (existingUser != null) { UpdateUserRegistration command = new UpdateUserRegistration() { AggregateId = existingUser.Id, FirstName = authInfo["first_name"], LastName = authInfo["last_name"], AccessToken = authToken.AccessToken, PhotoSmallUri = authInfo["photo"], PhotoBigUri = authInfo["photo_big"], }; Logger.Info("Existing user: {0}", command.Dump()); UserId = existingUser.Id; commandBus.Send(command, UserId); } else { RegisterUser command = new RegisterUser { AggregateId = entityIdGenerator.Generate(), FirstName = authInfo["first_name"], LastName = authInfo["last_name"], LoginType = loginType, ThirdPartyId = authToken.UserId, AccessToken = authToken.AccessToken, PhotoSmallUri = authInfo["photo"], PhotoBigUri = authInfo["photo_big"] }; Logger.Info("New user: {0}", command.Dump()); UserId = command.AggregateId; commandBus.Send(command, UserId); } ICacheClient cacheClient = resolver.ResolveService<ICacheClient>(); UpdateSession(cacheClient); }
public Task <object> LogoutAsync(IServiceBase service, Authenticate request, CancellationToken token = default) { return(Logout(service, request).InTask()); }
public Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default) { var response = Authenticate(authService, session, request); return(response.InTask()); }
public virtual void OnSaveUserAuth(IServiceBase authService, IAuthSession session) { }
protected object Authenticate(IServiceBase authService, IAuthSession session, string userName, string password) { return(Authenticate(authService, session, userName, password, string.Empty)); }
public VehicleModelAppService(IServiceBase <VehicleModel> servicebase) : base(servicebase) { }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { throw new NotImplementedException("JWT Authenticate() should not be called directly"); }
public override ServiceStack.Web.IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { return(base.OnAuthenticated(authService, session, tokens, authInfo)); }
public CategoriesController(IServiceBase <Category> categoryService, IMapper mapper) { _categoryService = categoryService; _mapper = mapper; }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { throw new NotImplementedException(); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { var tokens = this.Init(authService, ref session, request); //Transferring AccessToken/Secret from Mobile/Desktop App to Server if (request?.AccessToken != null) { if (VerifyAccessToken == null) { throw new NotImplementedException($"VerifyAccessToken is not implemented by {Provider}"); } if (!VerifyAccessToken(request.AccessToken)) { return(HttpError.Unauthorized($"AccessToken is not for the configured {Provider} App")); } var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken); var isHtml = authService.Request.IsHtml(); if (failedResult != null) { return(ConvertToClientError(failedResult, isHtml)); } return(isHtml ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))) : null); //return default AuthenticateResponse } var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl) }; AuthServerFilter?.Invoke(authServer); var authClient = new WebServerClient(authServer, this.ConsumerKey) { ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret), }; AuthClientFilter?.Invoke(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.Cookies.Add(cookie.ToCookie()); } } this.SaveSession(authService, session, 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) { tokens.RefreshToken = authState.RefreshToken; tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc; } if (accessToken != null) { try { return(AuthenticateWithAccessToken(authService, session, tokens, accessToken) ?? 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 override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { //new CredentialsAuthValidator().ValidateAndThrow(request); return(Authenticate(authService, session, request.UserName, request.Password)); }
public static IAuthSession GetSession(this IServiceBase service, bool reload = false) { return(service.Request.GetSession(reload)); }
public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { session.AuthProvider = Provider; if (session is AuthUserSession userSession) { LoadUserAuthInfo(userSession, tokens, authInfo); HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo); LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo); } var hasTokens = tokens != null && authInfo != null; if (hasTokens && SaveExtendedUserInfo) { if (tokens.Items == null) { tokens.Items = new Dictionary <string, string>(); } foreach (var entry in authInfo) { if (ExcludeAuthInfoItems.Contains(entry.Key)) { continue; } tokens.Items[entry.Key] = entry.Value; } } if (session is IAuthSessionExtended authSession) { var failed = authSession.Validate(authService, session, tokens, authInfo) ?? AuthEvents.Validate(authService, session, tokens, authInfo); if (failed != null) { authService.RemoveSession(); return(failed); } } var authRepo = GetAuthRepository(authService.Request); using (authRepo as IDisposable) { if (CustomValidationFilter != null) { var ctx = new AuthContext { Request = authService.Request, Service = authService, AuthProviderSync = this, Session = session, AuthTokens = tokens, AuthInfo = authInfo, AuthRepository = authRepo, }; var response = CustomValidationFilter(ctx); if (response != null) { authService.RemoveSession(); return(response); } } if (authRepo != null) { var failed = ValidateAccount(authService, authRepo, session, tokens); if (failed != null) { authService.RemoveSession(); return(failed); } if (hasTokens) { var authDetails = authRepo.CreateOrMergeAuthSession(session, tokens); session.UserAuthId = authDetails.UserAuthId.ToString(); var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate; if (firstTimeAuthenticated) { session.OnRegistered(authService.Request, session, authService); AuthEvents.OnRegistered(authService.Request, session, authService); } } authRepo.LoadUserAuth(session, tokens); foreach (var oAuthToken in session.GetAuthTokens()) { var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider); var userAuthProvider = authProvider as OAuthProvider; userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken); } var httpRes = authService.Request.Response as IHttpResponse; if (session.UserAuthId != null) { httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId); } } else { if (hasTokens) { session.UserAuthId = CreateOrMergeAuthSession(session, tokens); } } } try { session.IsAuthenticated = true; session.OnAuthenticated(authService, session, tokens, authInfo); AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo); } finally { #pragma warning disable 618 this.SaveSession(authService, session, SessionExpiry); #pragma warning restore 618 authService.Request.Items[Keywords.DidAuthenticate] = true; } return(null); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { var tokens = Init(authService, ref session, request); //Transferring AccessToken/Secret from Mobile/Desktop App to Server if (request?.AccessToken != null) { if (!AuthHttpGateway.VerifyFacebookAccessToken(AppId, request.AccessToken)) { return(HttpError.Unauthorized("AccessToken is not for App: " + AppId)); } var isHtml = authService.Request.IsHtml(); var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken); if (failedResult != null) { return(ConvertToClientError(failedResult, isHtml)); } return(isHtml ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))) : null); //return default AuthenticateResponse } var httpRequest = authService.Request; var error = httpRequest.QueryString["error_reason"] ?? httpRequest.QueryString["error"] ?? httpRequest.QueryString["error_code"] ?? httpRequest.QueryString["error_description"]; var hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error($"Facebook error callback. {httpRequest.QueryString}"); return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error)))); } var code = httpRequest.QueryString[Keywords.Code]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = $"{PreAuthUrl}?client_id={AppId}&redirect_uri={this.CallbackUrl.UrlEncode()}&scope={string.Join(",", Permissions)}&{Keywords.State}={session.Id}"; this.SaveSession(authService, session, SessionExpiry); return(authService.Redirect(PreAuthUrlFilter(this, preAuthUrl))); } try { var accessTokenUrl = $"{AccessTokenUrl}?client_id={AppId}&redirect_uri={this.CallbackUrl.UrlEncode()}&client_secret={AppSecret}&code={code}"; var contents = AccessTokenUrlFilter(this, accessTokenUrl).GetJsonFromUrl(); var authInfo = JsonObject.Parse(contents); var accessToken = authInfo["access_token"]; return(AuthenticateWithAccessToken(authService, session, tokens, accessToken) ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access! } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed")))); } } //Shouldn't get here return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown")))); }
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; 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"; await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait(); 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 = await AccessTokenUrlFilter(this, AccessTokenUrl).PostToUrlAsync(payload, "*/*", RequestFilter).ConfigAwait(); 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(await OnAuthenticatedAsync(authService, session, tokens, authInfo.ToDictionary(), token).ConfigAwait() ?? 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")))); }
public override bool TryAuthenticate(IServiceBase authService, string userName, string password) { return(userName == "john" && password == "test"); }
/// <summary> /// The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally. /// Overridable so you can provide your own Auth implementation. /// </summary> /// <param name="authService"></param> /// <param name="session"></param> /// <param name="request"></param> /// <returns></returns> public abstract override Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default);
protected virtual string GetAuthRedirectUrl(IServiceBase authService, IAuthSession session) { return(session.ReferrerUrl); }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary <string, string> authInfo) { base.OnAuthenticated(authService, session, tokens, authInfo); }
/// <summary> /// Authenticate against Yammer OAuth endpoint. /// </summary> /// <param name="authService"> /// The auth service. /// </param> /// <param name="session"> /// The session. /// </param> /// <param name="request"> /// The request. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var tokens = this.Init(authService, ref session, request); // Check if this is a callback from Yammer OAuth, // if not, get the code. var code = authService.RequestContext.Get <IHttpRequest>().QueryString["code"]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}", this.PreAuthUrl, this.ClientId, this.RedirectUrl.UrlEncode()); authService.SaveSession(session, this.SessionExpiry); return(authService.Redirect(preAuthUrl)); } // If access code exists, get access token to be able to call APIs. var accessTokenUrl = string.Format( "{0}?client_id={1}&client_secret={2}&code={3}", this.AccessTokenUrl, this.ClientId, this.ClientSecret, code); try { // Get access response object var contents = accessTokenUrl.GetStringFromUrl(); var authInfo = HttpUtility.ParseQueryString(contents); var authObj = JsonObject.Parse(contents); var accessToken = authObj.Object("access_token"); var userInfo = authObj.Object("user"); // Save info into user session tokens.AccessToken = accessToken.Get("token"); tokens.UserId = accessToken.Get("user_id"); tokens.UserName = userInfo.Get("name"); tokens.DisplayName = userInfo.Get("full_name"); tokens.FullName = userInfo.Get("full_name"); tokens.FirstName = userInfo.Get("first_name"); tokens.LastName = userInfo.Get("last_name"); var emails = userInfo.Object("contact").ArrayObjects("email_addresses").ConvertAll(x => new EmailAddresses { Type = x.Get("type"), Address = x.Get("address") }); var email = emails.FirstOrDefault(q => q.Type == "primary"); if (email != null) { tokens.Email = email.Address; } // Save session info incl. login state session.UserName = tokens.UserName; session.Email = tokens.Email; session.FirstName = tokens.FirstName; session.LastName = tokens.LastName; session.IsAuthenticated = true; authService.SaveSession(session, this.SessionExpiry); // Pass along this.OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()); this.LoadUserAuthInfo((AuthUserSession)session, tokens, authInfo.ToDictionary()); // Has access! return(authService.Redirect(this.CallbackUrl.AddHashParam("s", "1"))); } catch (WebException webEx) { var statusCode = ((HttpWebResponse)webEx.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(this.CallbackUrl.AddHashParam("f", "AccessTokenFailed"))); } } // Unknown error, shouldn't get here. return(authService.Redirect(this.CallbackUrl.AddHashParam("f", "Unknown"))); }
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { session.AuthProvider = Provider; if (session is AuthUserSession userSession) { LoadUserAuthInfo(userSession, tokens, authInfo); HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo); LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo); } if (session is IAuthSessionExtended authSession) { var failed = authSession.Validate(authService, session, tokens, authInfo) ?? AuthEvents.Validate(authService, session, tokens, authInfo); if (failed != null) { authService.RemoveSession(); return(failed); } } var authRepo = GetAuthRepository(authService.Request); using (authRepo as IDisposable) { if (CustomValidationFilter != null) { var ctx = new AuthContext { Request = authService.Request, Service = authService, AuthProvider = this, Session = session, AuthTokens = tokens, AuthInfo = authInfo, AuthRepository = authRepo, }; var response = CustomValidationFilter(ctx); if (response != null) { authService.RemoveSession(); return(response); } } if (authRepo != null) { if (tokens != null) { authInfo.ForEach((x, y) => tokens.Items[x] = y); session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString(); } foreach (var oAuthToken in session.GetAuthTokens()) { var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider); var userAuthProvider = authProvider as OAuthProvider; userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken); } var httpRes = authService.Request.Response as IHttpResponse; httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId); var failed = ValidateAccount(authService, authRepo, session, tokens); if (failed != null) { return(failed); } } } try { session.IsAuthenticated = true; session.OnAuthenticated(authService, session, tokens, authInfo); AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo); } finally { this.SaveSession(authService, session, SessionExpiry); authService.Request.Items[Keywords.DidAuthenticate] = true; } return(null); }
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { session.FirstName = "Ryan"; return(base.OnAuthenticated(authService, session, tokens, authInfo)); }
public static IHttpResult Redirect(this IServiceBase service, string url) { return(service.Redirect(url, "Moved Temporarily")); }
public AppServiceBase(IServiceBase <TEntity> serviceBase) { _serviceBase = serviceBase; }
public static void RemoveSession(this IServiceBase service) { service?.Request.RemoveSession(); }
public abstract object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request);
public AppServiceBase(IServiceBase <TEntity> service) { this.service = service; }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, System.Collections.Generic.Dictionary <string, string> authInfo) { "OnAuthenticated()".Print(); }
public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo) { var userSession = session as AuthUserSession; if (userSession != null) { LoadUserAuthInfo(userSession, tokens, authInfo); HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo); LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo); } var hasTokens = tokens != null && authInfo != null; if (hasTokens) { authInfo.ForEach((x, y) => tokens.Items[x] = y); } var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request); using (authRepo as IDisposable) { if (CustomValidationFilter != null) { var ctx = new AuthContext { Request = authService.Request, Service = authService, AuthProvider = this, Session = session, AuthTokens = tokens, AuthInfo = authInfo, AuthRepository = authRepo, }; var response = CustomValidationFilter(ctx); if (response != null) { authService.RemoveSession(); return(response); } } if (authRepo != null) { var failed = ValidateAccount(authService, authRepo, session, tokens); if (failed != null) { authService.RemoveSession(); return(failed); } if (hasTokens) { var authDetails = authRepo.CreateOrMergeAuthSession(session, tokens); session.UserAuthId = authDetails.UserAuthId.ToString(); var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate; if (firstTimeAuthenticated) { session.OnRegistered(authService.Request, session, authService); AuthEvents.OnRegistered(authService.Request, session, authService); } } authRepo.LoadUserAuth(session, tokens); foreach (var oAuthToken in session.GetAuthTokens()) { var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider); var userAuthProvider = authProvider as OAuthProvider; userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken); } var httpRes = authService.Request.Response as IHttpResponse; if (session.UserAuthId != null) { httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId); } } else { if (hasTokens) { session.UserAuthId = CreateOrMergeAuthSession(session, tokens); } } } try { session.IsAuthenticated = true; session.OnAuthenticated(authService, session, tokens, authInfo); AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo); } finally { this.SaveSession(authService, session, SessionExpiry); } return(null); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { var tokens = Init(authService, ref session, request); //Transferring AccessToken/Secret from Mobile/Desktop App to Server if (request?.AccessToken != null && VerifyAccessToken != null) { if (!VerifyAccessToken(request.AccessToken)) { return(HttpError.Unauthorized("AccessToken is not for client_id: " + ConsumerKey)); } var isHtml = authService.Request.IsHtml(); var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken); if (failedResult != null) { return(ConvertToClientError(failedResult, isHtml)); } return(isHtml ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))) : null); //return default AuthenticateResponse } var httpRequest = authService.Request; var error = httpRequest.QueryString["error_reason"] ?? httpRequest.QueryString["error"] ?? httpRequest.QueryString["error_code"] ?? httpRequest.QueryString["error_description"]; var hasError = !error.IsNullOrEmpty(); if (hasError) { Log.Error($"OAuth2 Error callback. {httpRequest.QueryString}"); return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error)))); } var code = httpRequest.QueryString[Keywords.Code]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var oauthstate = session.Id; var preAuthUrl = AuthorizeUrl .AddQueryParam("response_type", "code") .AddQueryParam("client_id", ConsumerKey) .AddQueryParam("redirect_uri", this.CallbackUrl) .AddQueryParam("scope", string.Join(" ", Scopes)) .AddQueryParam(Keywords.State, oauthstate); if (session is AuthUserSession authSession) { (authSession.Meta ?? (authSession.Meta = new Dictionary <string, string>()))["oauthstate"] = oauthstate; } this.SaveSession(authService, session, SessionExpiry); return(authService.Redirect(PreAuthUrlFilter(this, preAuthUrl))); } try { var state = httpRequest.QueryString[Keywords.State]; if (state != null && session is AuthUserSession authSession) { if (authSession.Meta == null) { authSession.Meta = new Dictionary <string, string>(); } if (authSession.Meta.TryGetValue("oauthstate", out var oauthState) && state != oauthState) { return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "InvalidState")))); } authSession.Meta.Remove("oauthstate"); } var contents = GetAccessTokenJson(code); var authInfo = JsonObject.Parse(contents); var accessToken = authInfo["access_token"]; var redirectUrl = SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")); var errorResult = AuthenticateWithAccessToken(authService, session, tokens, accessToken); if (errorResult != null) { return(errorResult); } //Haz Access! if (HostContext.Config?.UseSameSiteCookies == true) { // Workaround Set-Cookie HTTP Header not being honoured in 302 Redirects var redirectHtml = HtmlTemplates.GetHtmlRedirectTemplate(redirectUrl); return(new HttpResult(redirectHtml, MimeTypes.Html)); } return(authService.Redirect(redirectUrl)); } catch (WebException we) { string errorBody = we.GetResponseBody(); var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed")))); } } //Shouldn't get here return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown")))); }