Self-developed and implemented OAuth for webapi authentication and oauthwebapi

Source: Internet
Author: User
Tags oauth tojson

Self-developed and implemented OAuth for webapi authentication and oauthwebapi

When I see the OAuth written by someone in the garden, I want to share my own OAuth. I will not go into details about the OAuth protocol here.

1. As an authentication server, you first need to provide an interface that can obtain tokens through appid/appsecret, so you have the following code.

Public class AuthController: ApiController {[HttpGet] public HttpResponseMessage Token (string appid = "", string appsecret = "") {ApiResponseEntity rep; var isv = AppManage. instance. getAppISV (appid, appsecret); if (isv! = Null) {string token = TokenManage. instance. createToken (appid); rep = new apireeclipseentity {Status = InterfaceStatus. success, BizData = new {AccessToken = token };} else {rep = new apireeclipseentity () {Status = InterfaceStatus. parm_Missing, Message = "param error"};} return rep. toHttpResponseMessage ();}}View Code

The algorithm for creating token can be implemented by myself. I perform md5 processing on the newly generated Guid, and the code is as follows:

Public string CreateToken (string appid) {string token = Guid. NewGuid (). ToString (). ToMd5 (); Set (token, appid); return token ;}View Code

As you can see above, after the token is generated, A SetToken is stored in the cache and a lifecycle is set. The Code is as follows:

Public void Set (string token, string appid) {var config = ServerConfigManage. instance. getServerConfig (); string key = string. format (RedisCacheKey. app_Token, token); RedisNetHelper. set <string> (key, appid, DateTime. now. addSeconds (config. token=valtime ));}View Code

The reason why token is used as the key is because the change of token will lead to the failure of isv token verification. However, if token is used as the key, this key can be used within the lifecycle, the token cannot be obtained by multiple threads or is invalid due to other reasons. As an authentication server, you also need to provide an interface such as RefreshToken to refresh the token's lifecycle. If the code is similar, we will not repeat it here.

 

2. When performing Api verification, you need to start Token verification. The Code is as follows:

Public class OAuthHandler: DelegatingHandler {protected override Task <HttpResponseMessage> SendAsync (HttpRequestMessage request, System. threading. cancellationToken cancellationToken) {apireeclipseentity repEntity = null; string appid = ""; string ip = RequestHelper. getWebClientIp (); if (! OAuthValidate. ipValidate (ip) {repEntity = new apireeclipseentity {Status = InterfaceStatus. illegalIp, Message = "ip access limit" };} else {string token = ""; string url = request. requestUri. absoluteUri; var routeData = request. getRouteData (); string controller = routeData. values ["controller"]. toString (). toLower (); string action = routeData. values ["action"]. toString (). toLower (); if (controller. Equals ("auth") & action. equals ("token") {return base. sendAsync (request, cancellationToken);} if (request. method = HttpMethod. get) {var query = request. requestUri. parseQueryString (); token = query ["token"];} if (token = null | token. length = 0) {repEntity = new apireeclipseentity {Status = InterfaceStatus. token_Faild, Message = "token invalid" };} else {appid = TokenManage. instance. get (Token); if (appid = null | appid. length = 0) {repEntity = new apireeclipseentity {Status = InterfaceStatus. token_Faild, Message = "token invalid" };} else {if (! OAuthValidate. apiValidate (string. format ("{0}/{1}", controller, action), appid) {repEntity = new apireeclipseentity {Status = InterfaceStatus. no_Access, Message = "api access limit" };}}} if (repEntity! = Null) {var tsc = new TaskCompletionSource <HttpResponseMessage> (); tsc. setResult (repEntity. toHttpResponseMessage (); return tsc. task;} else {return base. sendAsync (request, cancellationToken );}}}View Code

The traditional method is inherited from DelegatingHandler and then processed. The first method is to verify the IP address, then verify the token validity, and finally verify the Api permission call. The verification code is as follows:

Public static bool IpValidate (string ip) {var config = ServerConfigManage. instance. getServerConfig (); bool isPass = true; if (isPass & config. isStartIpWhiteList) {isPass = config. ipWhiteList. contains (ip);} if (isPass & config. isStartIpBlackList) {isPass =! Config. ipBlackList. contains (ip) ;}return isPass;} public static bool ApiValidate (string api, string appid) {var config = ServerConfigManage. instance. getServerConfig (); if (config. isStartApiControl) {var apis = AppManage. instance. getAppApiResource (appid); return apis! = Null & apis. Contains (api);} return true ;}View Code

GetServerConfig () is to get the server's custom configuration from the DB/Cache, and then check whether the ip whitelist/blacklist is enabled. The following code shows whether to enable permission verification.

The authentication server is actually over here. For details about how isv applies for appid/appsecret. After the user agrees to the authorization, the relationship between the appid and the user is stored, and the visitor needs to implement it on his own.

 

There is also an extension Code mentioned here, that is, processing the returned values of apireeclipseentity. The Code is as follows:

Public static HttpResponseMessage ToHttpResponseMessage (this ResponseEntity rep, bool isEncrypt = false) {return new HttpResponseMessage (HttpStatusCode. OK) {Content = new StringContent (isEncrypt? EncryptHelper. base64Replace (EncryptHelper. AESEncryptBase64 (JsonHelper. toJson (rep), Config. apiEncryptKey): JsonHelper. toJson (rep), System. text. encoding. UTF8, "application/json ")};}View Code

 

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.