Identity Service, identityservice

Source: Internet
Author: User
Tags sql 2008 mssql server

Identity Service, identityservice

In the previous article, we all know that user logon to a website is very important, and one-stop login (SSO) has become a hot topic for discussion. In this Demo, Microsoft pulled the logon separately to form a Service in which user registration, logon, and password retrieval are all performed.

This service is developed based on IdentityServer4. It is a. Net Core-based oau2and OpenID framework. This framework is well-developed and can be used in any project.

Let's first look at the directory structure:

From the directory structure, we can see that it is a website with MVC Architecture. We can run and debug it separately. Of course, we can also put it into our own project.

Starting from. Net Core, we can see that the code sequence is transferred from Web. config to Program. cs. Let's look at the Program of IdentityService:

Public class Program {public static void Main (string [] args) {var host = new WebHostBuilder (). useKestrel (). useHealthChecks ("/hc") // a health check is added. useContentRoot (Directory. getCurrentDirectory ()). useIISIntegration (). useStartup <Startup> (). build (); host. run ();}}
It is similar to a common. Net Core project, but with another UseHealthChecks, we can see from the name that this is a health check for the project. If you are interested in it, we will introduce it at the beginning. After reading the Program, let's take a look at Startup.

During initialization, we can see that the code is basically the same as the system, and an additional builder is added. addUserSecrets () is a method to encrypt user information. This prevents us from disclosing some important information when submitting shared projects. If you are interested, you can check Secret Manager Tools.

In ConfigureServices, we can see a piece of code:

services.AddDataProtection(opts =>{    opts.ApplicationDiscriminator = "eshop.identity";});

This Code adds a unique identifier to the application, which is necessary in the cluster environment, we can use this unique identifier to determine whether an application is the same (the same application may be distributed on different servers). For details, see Asp.. Net Core data protection

Going Down:

services.AddHealthChecks(checks =>{    var minutes = 1;    if (int.TryParse(Configuration["HealthCheck:Timeout"], out var minutesParsed))    {        minutes = minutesParsed;    }    checks.AddSqlCheck("Identity_Db", Configuration.GetConnectionString("DefaultConnection"), TimeSpan.FromMinutes(minutes));});

Health Check again. This check shows the connection status to the database.

Services. addTransient <IEmailSender, AuthMessageSender> (); // mail sending service. addTransient <ISmsSender, AuthMessageSender> (); // SMS sending service. addTransient <ILoginService <ApplicationUser>, EFLoginService> (); // EF Logon Service. addTransient <IRedirectService, RedirectService> (); // redirect service // callbacks urls from config: Dictionary <string, string> clientUrls = new Dictionary <string, string> (); clientUrls. add ("Mvc", Configuration. getValue <string> ("MvcClient"); clientUrls. add ("Spa", Configuration. getValue <string> ("SpaClient"); clientUrls. add ("Xamarin", Configuration. getValue <string> ("XamarinCallback"); // Adds IdentityServerservices. addIdentityServer (x => x. issuerUri = "null "). addSigningCredential (Certificate. get ()). addInMemoryApiResources (Config. getApis ()). addInMemoryIdentityResources (Config. getResources ()). addInMemoryClients (Config. getClients (clientUrls )). addAspNetIdentity <ApplicationUser> (). services. addTransient <IProfileService, ProfileService> ();

Configure identityserver4. Configure in Startup is nothing special.

After a simple look at the Identity Project, it seems that it is to teach you how to use IdentityServer4 and So. You can find a lot of relevant information in the blog, So I will not repeat it here.

In this service, many unused classes and attributes are found. It is estimated that they will be used for future extension.

For example:

var user = await _loginService.FindByUsername(model.Email);if (await _loginService.ValidateCredentials(user, model.Password)){    AuthenticationProperties props = null;    if (model.RememberMe)    {        props = new AuthenticationProperties        {            IsPersistent = true,            ExpiresUtc = DateTimeOffset.UtcNow.AddYears(10)        };    };    await _loginService.SignIn(user);    // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint    if (_interaction.IsValidReturnUrl(model.ReturnUrl))    {        return Redirect(model.ReturnUrl);    }    return Redirect("~/");}

This is a piece of code for AccountController user login. The props attribute is set, but it is not used later, because it is a preparation for supporting continuous login in the future. ProfileService in the Services Directory is not called in the project. I believe it will be added in later versions. Run deployment

After learning about the project, let's start running and deploying it.

First, we need an MSSQL Server. Because we need to save user data, we recommend that you use SQL 2008 update3 or above. Why do you use update3 or above? Of course, you can also use other types of databases, for example, MySql and Sqlite.

Second, set the Identity project as the startup project, And Try Ctrl + F5 to check whether the operation is successful.

When you can see this page in the browser, it indicates that the program runs normally and the configuration is correct. Next, let's take a look at how to run it in docker.

1. Right-click Project-release and compile and publish the project to a folder.

2. Open your Terminal. If it is a system earlier than win10, open Docker Quickstart Terminal.

I use win7 and Quickstart terminals. Other systems use the same linux iner. Otherwise, how can they be called "build once, run anywhere.

3. first cd to your release directory on the terminal. If not on the same drive, use/(driver)/instead of driver:. For example, my project is released on D: \ Projects \ publish

    cd /d/projects/publish

On your terminal, you can see that this directory is on the top of the input line, indicating that you have already entered this directory, for example:

4. Use ls to view the directory. You will see all the compiled files in this directory (release). In the folder, you will see the dockerfile file, this is equivalent to docker's batch processing file. Let's take a look at the content and how to write it. You can refer to the tutorials of other great gods in the blog:

FROM microsoft/aspnetcore:1.1ARG sourceWORKDIR /appEXPOSE 80COPY ${source:-obj/Docker/publish} .ENTRYPOINT ["dotnet", "Identity.API.dll"]

5. Run the docker build command on the terminal to create your image (note the last ".", which indicates the current directory ):

docker build -t identity:01 .

6. After successful creation, we can use docker images to view the results. If there is an identity in the list, the creation is successful.

7. run

docker run -p 8888:80 --name identity -d identity:01

OK. After all the operations are completed, open it in our browser and enter http: // localhost: 8888.

No. no !!!!

After checking, we finally learned the cause. We use docker-toolbox, so it will create a linux runtime environment using VritualBox, so we must map the ports in the virtual machine to my local machine!

I thought it would always be okay. Who knows ..... Still inaccessible. In quickstart, I entered docker logs identity to see the following log:

Time out !! But I am running iis normally. There is no problem that the database cannot be connected! This problem plagued me for two days. I had a hard time sleeping at night. On the morning of the seventh day, I suddenly thought about the relationship between linux containers? Google used to have error messages, so they were not found at all. I changed the keyword linux containers connection sqlserver, and I found the answer in an issue:

Https://github.com/aspnet/EntityFramework/issues/4702#issuecomment-193382793

In the past, our sql2008 did not support such login requests. We had to upgrade to update3 to solve this problem. In order to continue the tutorial, I purchased the azure 1 yuan trial and changed the connection, I re-build and run and finally saw the familiar page:


Conclusion

In Identity Service, we see some new things, such as secret manager tool and healthcheck. Although it is built based on identityServer4, it at least taught us how to use identityServer4, in addition, we can pull it out as our own user server. I am also the first to contact IdentityServer4. Later, you can study and discuss it together, and it feels very powerful. Finally, we learned how to build and deploy the identity service separately and enable it to run normally in docker.

PS: my recent work is not very busy, so I have some time to study this. If you break the archive, please forgive me!

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.