DotNetOpenAuth
Environment:
. Net4.5.1, DotNetOpenAuth v5.0.0-alpha3, MVC5
I. Environment construction
1. Create an empty VS solution
2. Add a verification server project and select MVC for the project. Do not bring your own authentication.
3. Use Nuget to add DotNetOpenAuth v5.0.0-alpha3
Enter DotNetOpenAuth to install DotNetOpenAuth v5.0.0-alpha3
After adding
2. Write DotNetOpenAuth to verify the key code of the server and implement the function
1. Add AuthorizationServerConfiguration. cs
The configuration here is to facilitate management, but this class is not used.
Using System; using System. collections. generic; using System. linq; using System. security. cryptography. x509Certificates; using System. web; namespace IdefavAuthorizationServer. code {// <summary> /// verify the server configuration /// </summary> public class AuthorizationServerConfiguration {/// <summary> /// constructor // </summary> public AuthorizationServerConfiguration () {TokenLifetime = TimeSpan. fromMinutes (5);} // <summary> // signature certificate // </summary> public X509Certificate2 SigningCertificate {get; set ;} /// <summary> /// encryption certificate /// </summary> public X509Certificate2 EncryptionCertificate {get; set ;} /// <summary> /// Token validity period /// </summary> public TimeSpan TokenLifetime {get; set ;}}}
2. Implement the IClientDescription interface
Using System; using System. collections. generic; using System. linq; using System. web; using DotNetOpenAuth. messaging; using DotNetOpenAuth. oau22. namespace IdefavAuthorizationServer. code {public class Client: IClientDescription {// <summary> // Client Name client_id /// </summary> public string Name {get; set ;} /// <summary> // client type // </summary> public int ClientType {get; set ;}/// <summary> // callback URL /// </summary> public string Callback {get; set;} public string ClientSecret {get; set;} Uri IClientDescription. defaultCallback {get {return string. isNullOrEmpty (this. callback )? Null: new Uri (this. Callback) ;}} ClientType IClientDescription. ClientType {get {return (ClientType) this. ClientType ;}} bool IClientDescription. HasNonEmptySecret {get {return! String. isNullOrEmpty (this. clientSecret) ;}} bool IClientDescription. isCallbackAllowed (Uri callback) {if (string. isNullOrEmpty (this. callback) {// No callback rules have been set up for this client. return true;} // In this sample, it's enough of a callback URL match if the scheme and host match. // In a production app, it is advisable to require a match on the path as well. uri acceptableCallbackPattern = new Uri (this. callback); if (string. equals (acceptableCallbackPattern. getLeftPart (UriPartial. authority), callback. getLeftPart (UriPartial. authority), StringComparison. ordinal) {return true;} return false;} bool IClientDescription. isValidClientSecret (string secret) {return MessagingUtilities. equalsConstantTime (secret, this. clientSecret );}}}
3. Implement the IAuthorizationServerHost interface
Using System; using System. collections. generic; using System. linq; using System. security. cryptography; using System. web; using DotNetOpenAuth. messaging. bindings; using DotNetOpenAuth. oau22. using DotNetOpenAuth. OAuth2.ChannelElements; using DotNetOpenAuth. OAuth2.Messages; namespace IdefavAuthorizationServer. code {public class IdefavAuthorizationServerHost: IAuthorizationServerHost {// <summary> // Configure/ // </Summary> private readonly AuthorizationServerConfiguration _ configuration; /// <summary> /// constructor /// </summary> /// <param name = "config"> </param> public IdefavAuthorizationServerHost (AuthorizationServerConfiguration config) {if (config! = Null) _ configuration = config ;} /// <summary> /// Token creation /// </summary> /// <param name = "accessTokenRequestMessage"> </param> /// <returns> </returns> public AccessTokenResult CreateAccessToken (IAccessTokenRequest accessTokenRequestMessage) {var accessToken = new AuthorizationServerAccessToken (); accessToken. lifetime = _ configuration. tokenLifetime; // Set the Token validity period // set the public key accessToken. resourceServerEncryptionKey = (RSACryptoServiceProvider) _ configuration. encryptionCertificate. publicKey. key; // Set the signature private Key accessToken. accessTokenSigningKey = (RSACryptoServiceProvider) _ configuration. signingCertificate. privateKey; var result = new AccessTokenResult (accessToken); return result;} public IClientDescription GetClient (string clientIdentifier) {// verify the client_id if (string. equals (clientIdentifier, "idefav", StringComparison. currentCulture) // The database {var client = new Client {Name = "idefav", ClientSecret = "1", ClientType = 1}; return client;} is not used for the sake of conciseness ;} throw new authorization ("clientIdentifier");} public bool IsAuthorizationValid (IAuthorizationDescription authorization) {return true;} public AutomatedUserAuthorizationCheckResponse authorization (string userName, string password, IAccessTokenRequest accessRequest) {throw new NotImplementedException ();} public AutomatedAuthorizationCheckResponse response (IAccessTokenRequest accessRequest) {AutomatedUserAuthorizationCheckResponse response = new response (accessRequest, true, "test"); return response ;} public ICryptoKeyStore CryptoKeyStore {get;} public INonceStore NonceStore {get ;}}}
4. Implement OAuthController
Using System; using System. collections. generic; using System. linq; using System. threading. tasks; using System. web; using System. web. mvc; using DotNetOpenAuth. messaging; using DotNetOpenAuth. oau22. using IdefavAuthorizationServer. code; namespace IdefavAuthorizationServer. controllers {public class OAuthController: Controller {private readonly AuthorizationServer authorizationServer = new AuthorizationServer (new IdefavAuthorizationServerHost (Common. configuration); public async Task <ActionResult> Token () {var response = await authorizationServer. handleTokenRequestAsync (Request); return response. asActionResult ();}}}
5. Initialize AuthorizationServerConfiguration
Windows signature certificate is used here
Put in project
Note: Add-a sha1-sky exchange
At this point, the basic code has been written. Now let's take note that the default request set by oau2requires SSL, that is, the request must be https // localhost: 1111/OAuth/Token, now we do not need to use SSL encryption requests. Change the WebConfig file.
Set it in WebConfig as shown in the figure, so you don't need https access.
6. Run project F5
Use the Post tool to send Post requests to access http: // localhost: 53022/OAuth/token
Body parameters:
1 client_id: idefav
2 client_secret: 1
3 grant_type: client_credentials
Request result:
In this way, we get the access_token. With this access_token, we can access the resource server.
Update:
Add content type in OAuthController code
Using System. collections. generic; using System. linq; using System. threading. tasks; using System. web; using System. web. mvc; using System. web. script. services; using DotNetOpenAuth. messaging; using DotNetOpenAuth. oau22. using IdefavAuthorizationServer. code; namespace IdefavAuthorizationServer. controllers {public class OAuthController: Controller {private readonly AuthorizationServer authorizationServer = new AuthorizationServer (new IdefavAuthorizationServerHost (Common. configuration); public async Task <ActionResult> Token () {var response = await authorizationServer. handleTokenRequestAsync (Request); Response. contentType = response. content. headers. contentType. toString (); return response. asActionResult ();}}}
Create a Windows signature using DotNetOpenAuth
I. Tools
Makecert.exe,cert2spc.exe,pvk2pfx.exe
Baidu network disk address:
Link: http://pan.baidu.com/s/1ntOq3Cd password: j2rn
II. Production
1. Create a self-signed certificate and a private key file using the makecert tool
Command:
Makecert-a sha1-sky exchange-n "CN = issuer name"-B 10/18/2015-e 01/01/2018-sv your name. pvk your name. cer
Open the command line and navigate to the directory where makecert.exe is located.
Enter the command
Example: makecert-a sha1-sky exchange-n "CN = idefav"-B 10/18/2015-e 01/01/2018-sv test. pvk test. cer
Press enter to bring up the private key encryption password.
After the password is entered, the cer and pvk files are generated in the directory.
2. Use the certificate. cer to create the issuer certificate. spc and use the cert2spc tool.
Command:
Cert2spc your name. cer your name. spc
Enter the command to generate the spc file
3. Convert from. pvk and. spc to. pfx. pvk2pfx is used.
Command:
Pvk2pfx-pvk your name. pvk-pi pvk password-spc your name. spc
Note: The pvk password is the password entered in the previous pop-up.
Enter the command and press enter to bring up the certificate export wizard.
In this way, the cer and pfx are created. Next we will put these two files into the project created in the previous article.
Modify the initialization code in Global. axax.
Use the post tool to access the running project
Access_token Retrieved