[ASP. net mvc] ASP. NET Identity login technology application, mvcidentity

Source: Internet
Author: User

[ASP. net mvc] ASP. NET Identity login technology application, mvcidentity
[ASP. net mvc] ASP. NET Identity login Technology Application Scenario

ASP. NET Identity is an open-source project contributed by Microsoft to provide ASP. NET authentication and authorization mechanisms. In ASP. in addition to providing basic functions such as user registration, password resetting, and password verification, NET Identity also provides advanced functions: cookies, Facebook, and Google. Using these functional modules allows developers to quickly provide authentication, authorization, and other mechanisms on the ASP. NET platform.


However, in an enterprise, developers often encounter a development scenario: An enterprise already has an existing identity system, which provides: user Registration, password resetting, password verification, and other functions, newly developed ASP.. NET platform, must be connected to the existing identity system to provide authentication, authorization, and other mechanisms. This identity system may be a member management system of a hypermarket or a bank account management system. Their registration and review mechanisms have a set of rigorous and fixed processes.

In such a development scenario, developers may choose to integrate the existing Identity system into the authentication provider of ASP. NET Identity through program interfaces and OAuth mechanisms. In this way, the integration between the two systems excludes some technical barriers. After integration, the functional modules of the two systems overlap with each other. How to Deal with operational conflicts is also a complicated issue that requires additional consideration.


The good news is that ASP. NET Identity has a highly modular software architecture. In ASP. NET Identity, functional modules such as Cookie login, Facebook login, and Google login are cut into independent ASP. NET Security suites. Developers can apply the ASP. NET Security Suite directly to quickly integrate the existing identity system and provide the authentication and authorization mechanisms required for the ASP. NET platform. This article describes how to apply ASP. NET Security to integrate existing identity systems and provide authentication and authorization mechanisms required for ASP. NET platforms. I mainly keep a record for myself and hope to help developers who need it.

ASP. NET Security-GitHub


Example

Sample Code:

Development

Before applying ASP. NET Security, create a blank MVC project to provide a new ASP. NET platform. The preset Web Server URL is "http: // localhost: 41532/" to facilitate subsequent development steps.



Add three NuGet suites for ASP. NET Security to the MVC project. For details, refer to Microsoft. AspNet. Authentication, Microsoft. AspNet. Authentication. Cookies, Microsoft. AspNet. Authentication. Facebook.


Create an AccountController and related views to provide the logon page, so that users can choose which mode to log on to the system.

public class AccountController: Controller
{
    // Methods
    public IActionResult Login (string returnUrl = null)
    {
        // ViewData
        this.ViewData ["ReturnUrl"] = returnUrl;

        // Return
        return View ();
    }
}
Then add the following program code in the MVC project to mount and set the two CookieAuthenticationMiddleware to be used later. (For the relevant background knowledge of the program code, please refer to the technical analysis description: ASP.NET Identity login technology analysis)

public class Startup
{
    public void ConfigureServices (IServiceCollection services)
    {
        // Authentication
        services.AddAuthentication (options =>
        {
            options.SignInScheme = IdentityOptions.Current.ExternalCookieAuthenticationScheme;
        });
    }

    public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // Authentication
        app.UseCookieAuthentication (options =>
        {
            options.AuthenticationScheme = IdentityOptions.Current.ApplicationCookieAuthenticationScheme;
            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;
            options.LoginPath = new PathString ("/ Account / login");
        });

        app.UseCookieAuthentication (options =>
        {
            options.AuthenticationScheme = IdentityOptions.Current.ExternalCookieAuthenticationScheme;
            options.AutomaticAuthenticate = false;
            options.AutomaticChallenge = false;
            options.LoginPath = null;
        });
    }
}
Finally, in the MVC project, create the ExistingIdentitySystem category to simulate the existing identity system. In order to facilitate understanding of the system, the PasswordSignIn (password login), ExternalSignIn (third-party login ex: FB login) and other methods in the ExistingIdentitySystem all directly return the success message, and the GetUserById (acquire user) method directly returns the fixed user information. (In the development of a formal environment, the above method can be implemented through WebAPI, or directly connected to the database, etc., to obtain relevant information with the existing identity system.)

public class ExistingIdentitySystem
{
    // Methods
    public ExistingUser GetUserById (string userId)
    {
        // Result
        var user = new ExistingUser ();
        user.Id = "Clark.Lab@hotmail.com";
        user.Name = "Clark";
        user.Birthday = DateTime.Now;

        // Return
        return user;
    }

    public bool PasswordSignIn (string userId, string password)
    {
        // Return
        return true;
    }

    public bool ExternalSignIn (string userId, string externalProvider)
    {
        switch (externalProvider)
        {
            case "Facebook": return true;

            default:
                return true;
        }
    }
}

public class ExistingUser
{
    // Properties
    public string Id {get; set;}

    public string Name {get; set;}

    public DateTime Birthday {get; set;}
}
Development-Facebook Authentication
After completing the above steps, proceed to develop Facebook verification. First of all, developers can go to the Facebook Developer Center (https://developers.facebook.com/) and register a new APP account. (The Site URL for testing is defined in the previous step: "http: // localhost: 41532 /")

Then add the following program code in the MVC project to mount and set FacebookAuthenticationMiddleware. Among them, AppId and AppSecret are APP account data provided by Facebook Developer Center, and the two parameters Scope and UserInformationEndpoint are used to define the user's E-Mail information.

public class Startup
{
    public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // Authentication
        app.UseFacebookAuthentication (options =>
        {
            options.AppId = "770764239696406";
            options.AppSecret = "2eecc0b9ef785e43bcd4779e2803ba0f";
            options.Scope.Add ("email");
            options.UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email";
        });
    }
}
Then open AccountController and add the following program code and corresponding View to provide ASP.NET platform to handle third-party login (ExternalLogin) like Facebook. Among them, ExternalLogin is used to initiate a verification challenge (Challenge), the system will determine whether to verify with Facebook or other third-party systems according to the externalProvider parameters.

When the user passes the verification, the system will call ExternalLoginCallback to process the verification result. In ExternalLoginCallback, the UserId of the FBUser in the verification result will be obtained for verification with ExistingIdentitySystem. If the verification is successful, then the corresponding ExistingUser will be obtained from ExistingIdentitySystem, and then converted to APPUser to actually log in to the system. (For the relevant background knowledge of the program code, please refer to the technical analysis description: ASP.NET Identity login technology analysis)

public class AccountController: Controller
{
    public IActionResult ExternalLogin (string externalProvider, string returnUrl = null)
    {
        // AuthenticationProperties
        var authenticationProperties = new AuthenticationProperties ();
        authenticationProperties.Items.Add ("ExternalProvider", externalProvider);
        authenticationProperties.RedirectUri = Url.Action ("ExternalLoginCallback", "Account", new {ReturnUrl = returnUrl});

        // Return
        return new ChallengeResult (externalProvider, authenticationProperties);
    }

    public async Task <IActionResult> ExternalLoginCallback (string returnUrl = null)
    {
        // AuthenticateContext
        var authenticateContext = new AuthenticateContext (IdentityOptions.Current.ExternalCookieAuthenticationScheme);
        await this.HttpContext.Authentication.AuthenticateAsync (authenticateContext);

        // AuthenticateInfo
        string userId = authenticateContext.Principal.FindFirst (ClaimTypes.Email) .Value;
        string externalProvider = authenticateContext.Properties ["ExternalProvider"] as string;

        // Login
        var existingIdentitySystem = new ExistingIdentitySystem ();
        if (existingIdentitySystem.ExternalSignIn (userId, externalProvider) == false)
        {
            throw new InvalidOperationException ();
        }

        // ExistingUser
        var existingUser = existingIdentitySystem.GetUserById (userId);
        if (existingUser == null) throw new InvalidOperationException ();

        // ApplicationUser
        var applicationIdentity = new ClaimsIdentity (IdentityOptions.Current.ApplicationCookieAuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
        applicationIdentity.AddClaim (new Claim (ClaimTypes.NameIdentifier, existingUser.Id));
        applicationIdentity.AddClaim (new Claim (ClaimTypes.Name, existingUser.Name));

        var applicationUser = new ClaimsPrincipal (applicationIdentity);

        // Cookie
        await this.HttpContext.Authentication.SignInAsync (IdentityOptions.Current.ApplicationCookieAuthenticationScheme, applicationUser);
        await this.HttpContext.Authentication.SignOutAsync (IdentityOptions.Current.ExternalCookieAuthenticationScheme);

        // Return
        return Redirect (returnUrl);
    }
}
Development-Password Authentication
After completing the above steps, proceed to develop Password verification. Open AccountController and add the following program code and corresponding View to provide ASP.NET platform to handle Password verification. In this, PasswordLogin will receive the account password entered by the user, which is used to verify with ExistingIdentitySystem. If the verification is successful, then the ExistingUser will be obtained from the ExistingIdentitySystem and then converted to APPUser to actually log in to the system. (For the relevant background knowledge of the program code, please refer to the technical analysis description: ASP.NET Identity login technology analysis)

public class AccountController: Controller
{
    public async Task <IActionResult> PasswordLogin (string userId, string password, string returnUrl = null)
    {
        // Login
        var existingIdentitySystem = new ExistingIdentitySystem ();
        if (existingIdentitySystem.PasswordSignIn (userId, password) == false)
        {
            throw new InvalidOperationException ();
        }

        // ExistingUser
        var existingUser = existingIdentitySystem.GetUserById (userId);
        if (existingUser == null) throw new InvalidOperationException ();

        // ApplicationUser
        var applicationIdentity = new ClaimsIdentity (IdentityOptions.Current.ApplicationCookieAuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
        applicationIdentity.AddClaim (new Claim (ClaimTypes.NameIdentifier, existingUser.Id));
        applicationIdentity.AddClaim (new Claim (ClaimTypes.Name, existingUser.Name));

        var applicationUser = new ClaimsPrincipal (applicationIdentity);

        // Cookie
        await this.HttpContext.Authentication.SignInAsync (IdentityOptions.Current.ApplicationCookieAuthenticationScheme, applicationUser);
        await this.HttpContext.Authentication.SignOutAsync (IdentityOptions.Current.ExternalCookieAuthenticationScheme);

        // Return
        return Redirect (returnUrl);
    }
}
use
After completing the development steps, when the system executes the Controller or Action labeled [Authorize], it will jump to the Login page.

public class HomeController: Controller
{
    [Authorize]
    public IActionResult Contact ()
    {
        ViewData ["Message"] = "Hello" + User.Identity.Name + "!";

        return View ();
    }
}
Use-Facebook Authentication
On the Login page, when the user chooses to use Facebook authentication, the system will jump to the Facebook page for authentication and authorization. After completing the relevant steps of authentication and authorization, the user can enter the Controller or Action marked with the [Authorize] tag.

Use-Password Authentication
On the Login page, when the user chooses to use Password authentication, the system will use the account password entered on the Login page for authentication and authorization. After completing the relevant steps of authentication and authorization, the user can enter the Controller or Action marked with the [Authorize] tag.

example
Sample program code:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.