OAuth2.0 Information
Today saw a blogger wrote the series, the map and the process are more detailed, as the saying goes, practice is the only standard to test the truth (if it is copied and pasted according to the reference article, should not appear on the pit, but I like to do it manually), found a few pits, thus summing up the experience, so that other small white students less detours
Refer to the first article: https://www.cnblogs.com/cby-love/p/9281955.html
Refer to the second article: https://www.cnblogs.com/wyt007/p/8284482.html
Blog Park Xiao Chen's Chinese document about IDENTITYSERVER4 address: http://www.cnblogs.com/stulzq/p/8119928.html
Docker Chinese document https://yeasy.gitbooks.io/docker_practice/content/
OAuth2.0 (open Authorization) is an Open License agreement, third-party applications do not need to contact the user's account information (such as user name password), through the user's authorized access to user resources
The steps for OAuth are generally as follows:
1, the client requires the user to give authorization
2. User agrees to give authorization
3, according to the authorization obtained in the previous step, request tokens from the authentication server (token)
4, the authentication server to authorize the authentication, confirm the error after issuing the token
5. The client uses tokens to request resources from the resource server
6. The resource server uses the token to confirm the correctness of the token to the authentication server, and provides the resources after confirming the error.
Server-side code implementation The first step: Create a new WEBAPI empty project The second step: Add a NuGet Package: IdentityServer4 Step three: Create a new helper class (class name customization) for creating Identityserver4.model to generate authorization tokens
Public classConfig {/// <summary> ///All access to the resource/// </summary> /// <returns></returns> Public StaticIenumerable<apiresource>getresources () {return NewList<apiresource> {
The first parameter needs to be consistent with the following marked red font, optionally named, but note the case, the second argument I did, you're free. new Apiresource ("API", "My API ") }; } /// <summary> ///Client/// </summary> /// <returns></returns> Public StaticIenumerable<client>getclients () {return NewList<client> { NewClient () {ClientId="Client", ////mode: simplest modeallowedgranttypes=granttypes.clientcredentials, Clientsecrets= { NewSecret ("Secret". SHA256 ())}, allowedscopes ={"API"} } }; } }
The first pit explanation : Above Code Red Flag, please note case, if one uppercase, one lowercase. When you authorize, you will be prompted with an error
Fourth step: Modify the Startup.cs red font is required to add the method and middleware
Public classStartup { PublicStartup (iconfiguration configuration) {Configuration=configuration; } PublicIConfiguration Configuration {Get; } //This method gets called by the runtime. Use this method to add services to the container. Public voidconfigureservices (iservicecollection services) { services. Addidentityserver (). Adddevelopersigningcredential () //Add developer signing credentials. Addinmemoryapiresources (Config.getresources ())//Add memory Apiresource. Addinmemoryclients (Config.getclients ());//Add Memory clientServices. Addmvc (). Setcompatibilityversion (Compatibilityversion.version_2_1); } //This method gets called by the runtime. Use this method to configure the HTTP request pipeline. Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env) {if(env. Isdevelopment ()) {app. Usedeveloperexceptionpage (); } App. Useidentityserver (); //Use Identityserverapp. Usemvc (); } }
Fifth step: Modify Program.cs In fact this step can be omitted, because this will be the API is not hosted on IIS Express, through the console program to start. The custom path configuration is as follows
Public classProgram { Public Static voidMain (string[] args) {Createwebhostbuilder (args). Build (). Run (); } Public StaticIwebhostbuilder Createwebhostbuilder (string[] args) =Webhost.createdefaultbuilder (args). Usestartup<Startup>()
This port can be customized as long as it does not conflict with your other ports. Useurls ("http://localhost:5000"); }
Second Pit explanation: the server that generated the token has been fully set up, and if you start F5 as you used to, you will find that the custom port is not working---. You need to set it up.
Http://localhost:5000/.well-known/openid-configuration access; You can see that it's a restful API.
Then with the Postman Artifact server success, we started using the client
Client code Implementation First step: Create a new WEBAPI empty project Step two: Add a NuGet Package: Identityserver4.accesstokenvalidation Step three: Modify Startup.cs red font is the method and middleware that need to be added
Public classStartup { PublicStartup (iconfiguration configuration) {Configuration=configuration; } PublicIConfiguration Configuration {Get; } //This method gets called by the runtime. Use this method to add services to the container. Public voidconfigureservices (iservicecollection services) { services. Addauthentication ( "Bearer")//Add authorization mode. Addidentityserverauthentication (Options = {options.authority = "http://localhost:5000";//Authorization Server address Options.requirehttpsmetadata = false;//is HTTPS options.apiname = "API"; }); Services. Addmvc (). Setcompatibilityversion (Compatibilityversion.version_2_1); } //This method gets called by the runtime. Use this method to configure the HTTP request pipeline. Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env) {if(env. Isdevelopment ()) {app. Usedeveloperexceptionpage (); } App. Useauthentication (); //Use of authorized middlewareapp. Usemvc (); } }
Third Pit Explanation:
1. Authorized Service address port number, follow the port number configured on the server side, if using IIS Express, right-click Project Properties, Debug view.
2.options.apiname = "API"; Please look at the above pit one configuration name, case needs to be unified
Fourth step: Modify Program.cs In fact this step can be omitted, because this will be the API is not hosted on IIS Express, through the console program to start. Same as the service-side configuration described above. Remember to modify the port number
Four places to be aware of
You need to run the server and then run the client (the order is unimportant, it is important that all two programs start up.) You can publish the server to IIS, and the client runs through vs. I am lazy, open two respectively, a set to start the server, a set to start the client)
Fifth Step: Add authorization tags to add on action and controller
[HttpGet] [authorize] public actionresult<ienumerable<string> > Get () { returnnewstring'value1 " " value2 " }; }
Added to the action, indicating that this method requires authorization to access, otherwise it cannot be accessed
Added to the controller, indicating that all action methods under the entire controller need to be authorized before they can be accessed
is successful, if whitespace indicates that authorization failed (you can make a breakpoint).
Some error codes appear in HTML (<title>internal Server error</title>) inside because the server did not start successfully
Note: The authorization code must be preceded by a bearer and then a space
In the third step of the client configuration, services. Addauthentication ("Bearer")//Add authorization mode Some of your classmates might think that I should get rid of this and be consistent.
Congratulations to the student on the idea, but you can give it a try. This format is a fixed specification
ASP. NET Core IdentityServer4 Novice Road