نظرات اشتراک‌ها
روش امن نگهداری پسورد کاربران
پیاده سازی روش گفته شده در این سایت :
/* 
 * Password Hashing With PBKDF2 (http://crackstation.net/hashing-security.htm).
 * Copyright (c) 2013, Taylor Hornby
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, 
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation 
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Text;
using System.Security.Cryptography;

namespace PasswordHash
{
    /// <summary>
    /// Salted password hashing with PBKDF2-SHA1.
    /// Author: havoc AT defuse.ca
    /// www: http://crackstation.net/hashing-security.htm
    /// Compatibility: .NET 3.0 and later.
    /// </summary>
    public class PasswordHash
    {
        // The following constants may be changed without breaking existing hashes.
        public const int SALT_BYTE_SIZE = 24;
        public const int HASH_BYTE_SIZE = 24;
        public const int PBKDF2_ITERATIONS = 1000;

        public const int ITERATION_INDEX = 0;
        public const int SALT_INDEX = 1;
        public const int PBKDF2_INDEX = 2;

        /// <summary>
        /// Creates a salted PBKDF2 hash of the password.
        /// </summary>
        /// <param name="password">The password to hash.</param>
        /// <returns>The hash of the password.</returns>
        public static string CreateHash(string password)
        {
            // Generate a random salt
            RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
            byte[] salt = new byte[SALT_BYTE_SIZE];
            csprng.GetBytes(salt);

            // Hash the password and encode the parameters
            byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
            return PBKDF2_ITERATIONS + ":" +
                Convert.ToBase64String(salt) + ":" +
                Convert.ToBase64String(hash);
        }

        /// <summary>
        /// Validates a password given a hash of the correct one.
        /// </summary>
        /// <param name="password">The password to check.</param>
        /// <param name="correctHash">A hash of the correct password.</param>
        /// <returns>True if the password is correct. False otherwise.</returns>
        public static bool ValidatePassword(string password, string correctHash)
        {
            // Extract the parameters from the hash
            char[] delimiter = { ':' };
            string[] split = correctHash.Split(delimiter);
            int iterations = Int32.Parse(split[ITERATION_INDEX]);
            byte[] salt = Convert.FromBase64String(split[SALT_INDEX]);
            byte[] hash = Convert.FromBase64String(split[PBKDF2_INDEX]);

            byte[] testHash = PBKDF2(password, salt, iterations, hash.Length);
            return SlowEquals(hash, testHash);
        }

        /// <summary>
        /// Compares two byte arrays in length-constant time. This comparison
        /// method is used so that password hashes cannot be extracted from
        /// on-line systems using a timing attack and then attacked off-line.
        /// </summary>
        /// <param name="a">The first byte array.</param>
        /// <param name="b">The second byte array.</param>
        /// <returns>True if both byte arrays are equal. False otherwise.</returns>
        private static bool SlowEquals(byte[] a, byte[] b)
        {
            uint diff = (uint)a.Length ^ (uint)b.Length;
            for (int i = 0; i < a.Length && i < b.Length; i++)
                diff |= (uint)(a[i] ^ b[i]);
            return diff == 0;
        }

        /// <summary>
        /// Computes the PBKDF2-SHA1 hash of a password.
        /// </summary>
        /// <param name="password">The password to hash.</param>
        /// <param name="salt">The salt.</param>
        /// <param name="iterations">The PBKDF2 iteration count.</param>
        /// <param name="outputBytes">The length of the hash to generate, in bytes.</param>
        /// <returns>A hash of the password.</returns>
        private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes)
        {
            Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt);
            pbkdf2.IterationCount = iterations;
            return pbkdf2.GetBytes(outputBytes);
        }
    }
}
مطالب
مستندسازی خودکار API ها در برنامه‌های مبتنی بر ASP.NET Core بوسیله‌ی Swagger
پیشتر مطلبی در این زمینه در سایت منتشر شد که به خوبی نحوه‌ی پیاده سازی Swagger را در یک برنامه‌ی ASP.NET Web API نشان می‌دهد. حال در این مقاله‌ی کوتاه میخواهیم نحوه‌ی پیاده سازی آن را در یک برنامه‌ی مبتنی بر ASP.NET Core بررسی کنیم.

دریافت Swagger از نوگت

ابتدا باید این پکیج را از آدرسش در نیوگت بگیریم و در برنامه‌ی خود نصب کنیم:
pm> Install-Package Swashbuckle.AspNetCore

پیکربندی برنامه 

برای کانفیگ Swagger و تولید خودکار و پویای مستندات API‌ها توسط آن باید تنظیمات زیر را در کلاس Startup برنامه انجام دهیم :
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Swagger;

namespace MyProject.Web.Api
{
    public class Startup
    {
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {  
            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "MyProject API Documentation", Version = "v1" });
            });  
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceScopeFactory serviceScopeFactory)
        {
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });           
        }
    }
}

مشاهده خروجی مستند سازی API ها

بعد از اینکه کانفیگ‌های فوق را انجام دادیم کافی است تا برنامه را اجرا کرده و آدرس زیر را در مرورگر وارد کنیم:
http://localhost:port/swagger
 در این صورت خروجی به شکل زیر نمایش داده خواهد شد که حاوی اطلاعات بسیار مفیدی در مورد API‌ها می‌باشد. اطلاعاتی شامل http method ، آدرس API، پارامترهای ورودی، مدل خروجی و ...
در صورت استفاده از SWagger ، ذکر [HttpGet]  برای API‌های GET اجباری می‌شود و در صورتیکه این مورد را برای API ای مشخص نکرده باشیم با خطای Run Time مواجه شده و برنامه اجرا نخواهد شد. 

 

اشتراک‌ها
بررسی روش ساخت برنامه‌های چندمستاجری در ASP.NET Core

Jon P. Smith, author of Entity Framework Core in Action, explains what a multi-tenant app is and then digs into the things you need to do to make a multi-tenant app using ASP.NET Core with EF Core.

00:00 Countdown
02:19 Introduction and Community Links
18:25 What are multi-tenant web applications?
21:14 Single level multi-tenant demo
29:00 Partitioning tenants with EF Core QueryFilter
38:00 Admin features: creating users and tenants
43:00 Q&A
43:00 Hierarchical multi-tenant
59:00 How to get started
1:06:30 Database sharding and connection string management
1:16:30 Scaling with Azure SQL Elastic Pools
1:19:00 Conclusion
 

بررسی روش ساخت برنامه‌های چندمستاجری در ASP.NET Core
اشتراک‌ها
چرا SQL در حال شکست NoSQL است؟

SQL is back. Not just because writing glue code to kludge together NoSQL tools is annoying. Not just because retraining workforces to learn a myriad of new languages is hard. Not just because standards can be a good thing.

But also because the world is filled with data. It surrounds us, binds us. At first, we relied on our human senses and sensory nervous systems to process it. Now our software and hardware systems are also getting smart enough to help us. And as we collect more and more data to make better sense of our world, the complexity of our systems to store, process, analyze, and visualize that data will only continue to grow as well. 

چرا SQL در حال شکست NoSQL است؟
نظرات مطالب
احراز هویت و اعتبارسنجی کاربران در برنامه‌های Angular - قسمت دوم - سرویس اعتبارسنجی
با تغییر کلاس سرویس AppConfigService به شکل زیر :

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";

@Injectable()
export class AppConfigService {

    private config: IAppConfig;

    constructor(private http: HttpClient) { }

    loadClientConfig(): Promise<any> {
        return this.http.get<IAppConfig>("assets/client-config.json")
            .toPromise()
            .then(config => {
                this.config = config;
                console.log("Config", this.config);
            })
            .catch(err => {
                return Promise.reject(err);
            });
    }

    get configuration(): IAppConfig {
        if (!this.config) {
            throw new Error("Attempted to access configuration property before configuration data was loaded.");
        }
        return this.config;
    }
}

export interface IAppConfig {
    apiEndpoint: string;
    loginPath: string;
    logoutPath: string;
    refreshTokenPath: string;
    accessTokenObjectKey: string;
    refreshTokenObjectKey: string;
    adminRoleName: string;
}

و تغییر ماژول CoreModule به شکل زیر :

import { NgModule, Optional, SkipSelf, APP_INITIALIZER } from "@angular/core";
import { CommonModule } from "@angular/common";
import { RouterModule } from "@angular/router";
import { HTTP_INTERCEPTORS } from "@angular/common/http";

// import RxJs needed operators only once
import "./services/rxjs-operators";

import { HeaderComponent } from "./component/header/header.component";
import { AuthGuard } from "./services/auth.guard";
import { AuthInterceptor } from "./services/auth.interceptor";
import { AuthService } from "./services/auth.service";
import { AppConfigService } from "./services/app-config.service";
import { BrowserStorageService } from "./services/browser-storage.service";


@NgModule({
    imports: [CommonModule, RouterModule],
    exports: [
        // components that are used in app.component.ts will be listed here.
        HeaderComponent
    ],
    declarations: [
        // components that are used in app.component.ts will be listed here.
        HeaderComponent
    ],
    providers: [
        // global singleton services of the whole app will be listed here.
        BrowserStorageService,
        AppConfigService,
        AuthService,
        AuthGuard,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: AuthInterceptor,
            multi: true
        },
        {
            provide: APP_INITIALIZER,
            useFactory: (config: AppConfigService) => () => config.loadClientConfig(),
            deps: [AppConfigService ],
            multi: true
        }
    ]
})
export class CoreModule {
    constructor( @Optional() @SkipSelf() core: CoreModule) {
        if (core) {
            throw new Error("CoreModule should be imported ONLY in AppModule.");
        }
    }
}
با خطای زیر مواجه شدم لطفا راهنمایی بفرمائید :

Error: Provider parse errors:
Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1 
اشتراک‌ها
راهنمای ارتقاء به EF Core 3.0

The following API and behavior changes have the potential to break existing applications when upgrading them to 3.0.0. Changes that we expect to only impact database providers are documented under provider changes.  

راهنمای ارتقاء به EF Core 3.0