Auto Login for Website Username and Password Updated FREE

Auto Login for Website Username and Password

This mail is part of the serial 'Countersign management'. Be sure to bank check out the rest of the blog posts of the serial!

  • How to store a password in a web application?
  • How to implement Countersign reset characteristic in a web application?
  • How to shop a password on Windows?
  • How to prompt for a password on Windows?
  • Helping users to create skillful passwords
  • Automatically log in a user on a website using the Credential Management API? (this post)
  • How to avoid storing secrets in the source code?

Many websites require users to log in to access their resources. From a user point of view, the login process can exist complicated, and it'south fifty-fifty more circuitous when there are multiple ways to authenticate: login/password or using a social provider (Microsoft, Google, Facebook, etc.). For instance, some users enter their Google credentials in the Username/Countersign form instead of clicking the Google button, or they don't remember which provider they have used to create their account.

Sample login page Sample login page

To assist users, major web browsers let saving credentials and auto-fill forms. This allows users to quickly log into the web site. This is slap-up but this doesn't work with social providers and you still need to navigate to the login folio. Thanks to the new Credential Direction API you lot can go farther. Indeed, the browser knows your credentials, then why not automatically log you in every bit presently equally you access the web site without even navigating to the login page? To be clear, users may see the login page only the kickoff time. Then, they can log in without typing their credentials and without navigating to the login page.

#Can I apply the Credential Direction API?

This API is clearly not well supported. Indeed, only Google Chrome and Opera support it. Still, this doesn't mean you should non consider using it. First, Chrome is the most used browser. If you expect at CanIUse, it represents about 67% of all users. Plus, using this API doesn't intermission default login menstruum on other browsers. Instead, this API just improves it when it is available.

Credential Management API - Support (source))

#How does it piece of work?

For the demo, I'll utilize ASP.Cyberspace Core and TypeScript. The code is very basic, so it's very like shooting fish in a barrel to adjust information technology to another server and client language/framework.

Beginning, you need to create a login form:

HTML

                      <form              method="post">            <input              type="electronic mail"              name="E-mail"              />            <input              type="password"              name="Password"              />            <button              type="submit">Log in</button>            </course>                  

Then, you must create a controller activeness. This code comes from the default template of ASP.NET with Individual User Accounts, zippo fancy here.

C#

          [HttpPost] [AllowAnonymous]                          public              async              Job<IActionResult>              Login(LoginViewModel model)            {            if            (ModelState.IsValid)     {            var            result =            await            _signInManager.PasswordSignInAsync(model.Email, model.Countersign, isPersistent:            false);            // Create the authentication cookie if the email and password are valid            if            (consequence.Succeeded)         {            return            RedirectToLocal(returnUrl);         }            else            {             ModelState.AddModelError(cord.Empty,            "Invalid login attempt.");            render            View(model);         }     }            return            View(model); }        

At present, when the user logs in, the browser should brandish a "Save credential" button:

Google Chrome - Save credential Google Chrome - Salve credential

Once the user has saved the countersign, you'll be able to access its credentials from JavaScript. For security reasons, you lot volition only have admission to the credentials of the current domain. If yous use TypeScript, you need to add together the type declarations before using the new API:

Crush

          npm install @types/webappsec-credential-management        

The basic code to get a saved credential for the electric current website is:

TypeScript

                      async            function            signIn(unmediated:              boolean            ) {            // Test if the Credential Manager API exists            if            (navigator.credentials) {            // Become the saved credential            // unmediated: if true, the user amanuensis will only attempt to provide a Credential without user interaction            const            cred =            await            navigator.credentials.get({            password:            true,            unmediated: unmediated         });            if            (cred) {            // Exercise something with the creds            }     } }        

The API allows managing username/password credentials and federated credentials (log in using an external provider such every bit Microsoft, Google, Facebook, etc.). You lot can determine the blazon using the type property. In this post, we'll merely handle username/password credentials so nosotros demand to test if the blazon is password. As nosotros apply TypeScript we can create a type guard function and so nosotros can avoid casting explicitly the variable cred:

TypeScript

                      part            isPasswordCredential(credential: Credential) : credential is            PasswordCredential            {            render            credential.type            ===            "password"; }        

Once you have the credential object, you can access the id (username) and password properties. So, you can create a FormData and transport it to the server.

TypeScript

                      async            function            signIn(unmediated:              boolean            ) {            // Test if the Credential Manager API exists            if            (navigator.credentials) {            // Prompt for credential            // unmediated: if truthful, the user agent volition only endeavour to provide a Credential without any user interaction            const            cred =            await            navigator.credentials.go({            countersign:            true,            unmediated: unmediated         });            if            (cred) {            if            (isPasswordCredential(cred)) {            let            form =            new            FormData();                 form.append('email', cred.id);                 course.append('password', cred.password);            const            response =            expect            fetch('/Business relationship/AutoLogin', {            method:            'POST',            credentials:            'include',            torso: form                 });            if            (response.ok) {            window.location.reload();            // reload the page with the authentication cookie            }             }         }     } }        

If needed yous can add additional information to the request. For instance, you tin can add the CSRF token:

TypeScript

                      if            (cred) {            if            (isPasswordCredential(cred)) {            allow            form =            new            FormData();                 form.append('email', cred.id);                 form.append('password', cred.password);            // Get the value of the anti CSRF field generated past ASP.NET Core            const            csrfInput = <HTMLInputElement>document.querySelector("input[proper name='__RequestVerificationToken']");                 additionalData.suspend("__RequestVerificationToken", csrfInput.value);            const            response =            wait            fetch('/Account/AutoLogin', {            method:            'POST',            credentials:            'include',            body: grade                 });            if            (response.ok) {            window.location.reload();            // reload the folio with the authentication cookie            }             }         }        

The AutoLogin action is the aforementioned as the Login action except it only returns a status code instead of an HTML content:

C#

          [HttpPost] [AllowAnonymous]                          public              async              Task<IActionResult>              AutoLogin(LoginViewModel model)            {            if            (ModelState.IsValid)     {            var            consequence =            await            _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent:            fake);            if            (consequence.Succeeded)            return            Ok();            return            BadRequest("Invalid login attempt.");     }            render            BadRequest(); }        

Now the login code is written, y'all can call the signIn function on page load (if the user is not authenticated).

TypeScript

                      signIn(false);        

Authentication using Credential Management API Authentication using Credential Management API

Later on the user logs off, yous don't want to be able to log the user in automatically without their consent. To instruct the browser to crave the mediation after the user logs off, you must call the preventSilentAccess function. This does non delete the saved credential. It just forces the browser to bear witness the UI the next time you phone call navigator.credentials.get. This means the user will find you want to authenticate them and they can cancel the hallmark if they want to.

TypeScript

                      if            (navigator.credentials) {            const            logOutElement =            document.getElementById("LogOut");            if            (logOutElement) {         logOutElement.addEventListener("click",                          due east              =>            navigator.credentials.preventSilentAccess());     } }        

#Conclusion

This new API is a great improvement for the user equally information technology simplifies the login process. You can now automatically log the user in without they observe it. While this new API is not well supported (currently Chrome and Opera), you can already utilise it to progressively replace the onetime login form. This mail service does not cover all the methods of this API. For instance, nosotros exercise not use the store method which may be required for a SPA awarding. If yous desire to get further, here're some additional resource:

  • Specification: https://w3c.github.io/webappsec-credential-management/
  • Sample from Google Chrome: demo and code
  • Boosted information: Latest Updates to the Credential Management API

Practice you have a question or a proposition well-nigh this mail service? Contact me!

Auto Login for Website Username and Password

DOWNLOAD HERE

Source: https://www.meziantou.net/automatically-log-in-a-user-on-a-website-using-the-credential-manageme.htm

Posted by: carlsontreff1938.blogspot.com

Comments