private void HandleError(ITransport sender, int statusCode) { switch (statusCode) { case 401: Unauthorized?.Invoke(null, new EventArgs()); break; } }
protected override async Task HandleForbiddenAsync(AuthenticationProperties properties) { Context.Response.StatusCode = StatusCodes.Status403Forbidden; Context.Response.ContentType = "application/json; charset=utf-8"; var errorResponse = new Unauthorized(nameof(ErrorMessage.Forbidden), ErrorMessage.Forbidden); var response = JsonConvert.SerializeObject(errorResponse); await Context.Response.WriteAsync(response); }
private Task HandleExceptionAsync(HttpContext context, Exception exception) { // Response Error errorResponse; switch (exception) { case UnauthorizedException _: // 401 var unauthorizedException = (UnauthorizedException)exception; errorResponse = new Unauthorized(nameof(ErrorMessage.Unauthorized), unauthorizedException.Message); break; case ForbiddenException _: // 403 var forbiddenException = (ForbiddenException)exception; errorResponse = new Forbidden(nameof(ErrorMessage.Forbidden), forbiddenException.Message); break; case NotFoundException _: // 404 var notFoundException = (NotFoundException)exception; errorResponse = new NotFound(nameof(ErrorMessage.NotFound), notFoundException.Message); break; case ConflictException _: // 409 var conflictException = (ConflictException)exception; errorResponse = new Conflict(nameof(ErrorMessage.Conflict), conflictException.Message); break; default: // 500 errorResponse = new InternalServerError(nameof(ErrorMessage.InternalServerError), ErrorMessage.InternalServerError); // Log error _logger.LogSplunkError(exception); break; } var response = JsonConvert.SerializeObject(errorResponse, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new List <JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter() } }); context.Response.ContentType = "application/json"; context.Response.StatusCode = errorResponse.Status; return(context.Response.WriteAsync(response)); }
/// <inheritdoc /> public bool TryAuthenticate(RESTableContext context, ref string uri, Headers headers, out Unauthorized error) { var accessRights = GetAccessRights(ref uri, headers); if (accessRights == null) { error = new Unauthorized(); error.SetContext(context); if (headers?.Metadata == "full") { error.Headers.Metadata = error.Metadata; } return(false); } context.Client.AccessRights = accessRights; error = null; return(true); }
/// <summary> /// Signed in user may perform all basic operations related with his/her accounts. /// </summary> private bool SignedIn(object message) { return(base.ReceiveCommand(message) || message.Match() .With <UserCommands.ChangePassword>(change => { if (ValidatePassword(State, change.OldPassword)) { var passwordHash = HashPassword(change.NewPassword); Persist(new UserEvents.PasswordChanged(_id, passwordHash)); } else { Log.Error("Unauthorized user sign in. User id: {0}", _id); Sender.Tell(Unauthorized.Message(change)); } }) .WasHandled); }
/// <summary> /// Initialized state represents actor which has entity already initialized, /// but following user has not logged in to his/her personal account. /// /// At this state allowed actions are sign in, resetting user password. User sign out is ignored. /// </summary> private bool Initialized(object message) { return(base.ReceiveCommand(message) || message.Match() .With <UserCommands.SignInUser>(signIn => { if (string.Equals(State.Email, signIn.Email, StringComparison.InvariantCultureIgnoreCase) && ValidatePassword(State, signIn.Password)) { Persist(new UserEvents.UserSignedIn(_id), Sender); } else { Log.Error("Unauthorized user sign in. User id: {0}, email: {1}", _id, signIn.Email); Sender.Tell(Unauthorized.Message(signIn)); } }) .With <UserCommands.ResetPassword>(reset => { //TODO: user reset password and mail sent }) .With <UserCommands.SignOutUser>(_ => { /* ignore */ }) .WasHandled); }
protected virtual void OnUnauthorized(UnauthorizedResponse e) { Unauthorized?.Invoke(this, e); }
public async Task TracksSuggestionPresentedEventWhenCalendarUnauthorized() { PermissionsChecker.CalendarPermissionGranted.Returns(Observable.Return(false)); var suggestions = prepareSuggestionsForSuggestionsPresentedEvent(); var observer = TestScheduler.CreateObserver <IImmutableList <Suggestion> >(); await ViewModel.Initialize(); ViewModel.Suggestions.Subscribe(observer); TestScheduler.Start(); AnalyticsService.Received().Track(Arg.Is <SuggestionsPresentedEvent>(e => e.ToDictionary()[CalendarProviderStateName] == Unauthorized.ToString() )); }
protected virtual void OnUnauthorized(HttpConnection p, string auth) { Unauthorized?.Invoke(this, p, auth); }
protected virtual void OnUnauthorized(UnauthorizedResponse e) { Logger.Info("OnUnauthorized"); Unauthorized?.Invoke(this, e); }
public static IServiceCollection UseSharedAuthentication(this IServiceCollection services, IConfiguration configuration) { // Grab AuthenticationSettings var authenticationSettings = new AuthenticationSettings(); configuration.GetSection("AuthenticationSettings").Bind(authenticationSettings); // Configure JWT authentication var key = Encoding.ASCII.GetBytes(authenticationSettings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { NameClaimType = ClaimTypes.NameIdentifier, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidIssuer = authenticationSettings.Issuer, ValidateIssuer = true, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; x.Events = new JwtBearerEvents() { OnMessageReceived = context => { // First, get the value from the cookie. If no cookie present, then use the authorization header context.Token = context.Request.Cookies["AccessToken"] ?? context.Request.Headers["Authorization"]; return(Task.CompletedTask); }, // Add body to 401/403 OnChallenge = context => { context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json; charset=utf-8"; var errorResponse = new Unauthorized(nameof(ErrorMessage.Unauthorized), ErrorMessage.Unauthorized); var result = JsonConvert.SerializeObject(errorResponse); return(context.Response.WriteAsync(result)); }, OnForbidden = context => { context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.ContentType = "application/json; charset=utf-8"; var errorResponse = new Unauthorized(nameof(ErrorMessage.Forbidden), ErrorMessage.Forbidden); var result = JsonConvert.SerializeObject(errorResponse); return(context.Response.WriteAsync(result)); } }; }); return(services); }
public bool TryAuthenticate(RESTableContext context, ref string uri, Headers headers, out Unauthorized error) { context.Client.AccessRights = RootAccess; error = null; return(true); }
public override void Configure(IApplicationBuilder app) { // Global error handler for API app.UseWhen(http => http.Request.Path.StartsWithSegments("/api"), appApi => { var routeController = new RouteController(appApi.ApplicationServices); // Native error appApi.UseExceptionHandler(appB => { appB.Run(async http => { var exf = http.Features.Get <IExceptionHandlerFeature>(); System.Exception error = (exf != null) ? exf.Error : new ErrorException(); http.Response.ContentType = "application/json"; http.Response.Headers.Add("x-api-standard", "1"); await http.Response.WriteAsync( JsonConvert.SerializeObject( routeController.WrapError(error, error.Message) ) ); // Will log on file on production and console on development }); }); // Custom error appApi.UseStatusCodePages(async context => { context.HttpContext.Response.ContentType = "application/json"; Error error; switch (context.HttpContext.Response.StatusCode) { case 401: error = new Unauthorized(); break; case 404: error = new RouteNotFound(); break; case 403: error = new Forbidden(); break; default: error = new Error(); break; } context.HttpContext.Response.Headers.Add("x-api-standard", "1"); await context.HttpContext.Response.WriteAsync( JsonConvert.SerializeObject( routeController.WrapError(error, null) ) ); }); // Use MVC appApi.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); // At this point status code must be already set by MVC // If not, respond with 404 Not Found appApi.Use(async(context, next) => { context.Response.ContentType = "application/json"; await context.Response.WriteAsync( JsonConvert.SerializeObject( routeController.WrapError(new RouteNotFound(), null) ) ); }); }); }