コード例 #1
0
        public static IServiceCollection AddSecurity(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ClockSkew        = TimeSpan.Zero,
                    ValidIssuer      = configuration["JWT:Issuer"],
                    ValidAudience    = configuration["JWT:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(configuration["JWT:Secret"]))
                };

                options.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception is SecurityTokenExpiredException)
                        {
                            context.Response.Headers.Add("RefreshToken", "true");
                        }
                        var response = new UnauthorizedApiResponse("Token has expired.");
                        var body     = ObjectToJson.ToByteArray(response);
                        context.Response.StatusCode  = response.Status;
                        context.Response.ContentType = "application/json";
                        context.Response.Body.Write(body, 0, body.Length);
                        return(Task.CompletedTask);
                    },

                    OnForbidden = context =>
                    {
                        var response = new ForbiddenApiResponse();
                        var body     = ObjectToJson.ToByteArray(response);
                        context.Response.StatusCode  = response.Status;
                        context.Response.ContentType = "application/json";
                        context.Response.Body.Write(body, 0, body.Length);
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthorization();

            // Solution wide DI
            services.AddScoped <IIdentityService, IdentityService>();

            // Project wide DI
            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddScoped <ITokenGenerator, TokenGenerator>();
            services.AddScoped <IUserService, UserService>();

            return(services);
        }
コード例 #2
0
        public async Task <IActionResult> GetLandlordsForUserAsync(
            [FromRoute] string userId,
            [FromBody] GetLandlordsRequest request)
        {
            if (userId != request.UserId)
            {
                var forbiddenResult = new ForbiddenApiResponse();
                return(StatusCode(forbiddenResult.Status, forbiddenResult));
            }

            if (ModelState.IsValid)
            {
                var result = await _landlordService.GetLandlordsForUserAsync(request);

                return(StatusCode(result.Status, result.Payload));
            }
            return(GetBadRequestResult());
        }
コード例 #3
0
        protected ResponseMessage ForbiddenResponse(string title = null)
        {
            var response = new ForbiddenApiResponse(title);

            return(new ResponseMessage(response.Status, response));
        }