Open Source Sample code: Https://github.com/linezero/NancyDemo
The advanced section of Nancy is now in front of you to learn about Nancy's identity certification.
This article mainly explains the Basic authentication, the fundamental authentication .
In HTTP, Basic authentication is a form of login authentication that allows a Web browser or other client program to provide credentials in the form of a user name and password when requested.
Description: This example is based on Nancy 1.4.3. The release of the Nancy 2.0 preview has been released and the version has been changed to a larger size.
Prepare
Installing Nancy.Authentication.Basic
1.4. 1
I'm not going to create a new project here, just add it in the previous project.
1. Implement the Iuservalidator interface
Create a new class that implements the Iuservalidator interface.
Public classBasicuservalidator:iuservalidator { PublicIuseridentity Validate (stringUsernamestringpassword) { if(Username = ="Linezero"&& Password = ="Demo") { return NewBasicuser () {UserName =username}; } return NULL; } }
Here I have fixed the user judgment, you can also use a variety of ways to judge.
2. Implement the Iuseridentity interface
Public class basicuser:iuseridentity { publicstringgetset;} Public ienumerable<stringgetset;} }
3. Add authentication to the Nancy pipeline
In the Bootstrapper that inherits Defaultnancybootstrapper , add the following code Applicationstartup:
protected override void Applicationstartup (Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base . Applicationstartup (container, pipelines); Pipelines. Enablebasicauthentication ( new Basicauthenticationconfiguration (container. Resolve <iuservalidator> (), " myrealm " ); // Error; }
Main code:
Pipelines. Enablebasicauthentication (new basicauthenticationconfiguration ( container. Resolve<IUserValidator>(), "myrealm"));
When added, start the program.
Visit: http://localhost:9000
Enter Linezero demo to successfully authenticate.
4. Get authorized Users
We need to get authorized users in module to use context.currentuser to obtain user information.
Add a Get user name in Homemodule:
Context.CurrentUser.UserName
The implementation is as follows:
5. Cross-platform
Upload the program to Linux execution to access the corresponding address:
Sample code Download: Https://github.com/linezero/NancyDemo
The sample code contains previous examples and will be updated continuously, welcome to star.
If you think this article is helpful to you, please click " recommend ", thank you.
Nancy Learning-Identity verification (Basic authentication) continues across platforms