课程代码课件45-webapi专题3登陆验证四种方式_第1页
课程代码课件45-webapi专题3登陆验证四种方式_第2页
课程代码课件45-webapi专题3登陆验证四种方式_第3页
课程代码课件45-webapi专题3登陆验证四种方式_第4页
课程代码课件45-webapi专题3登陆验证四种方式_第5页
已阅读5页,还剩21页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第一种:FORM验证(若在ASP.NET应用程序使用,则该验证方式不支持跨域,因为 定义一个FormAuthenticationFil ttribute,该类继承自AuthorizationFil 1using2using3using4using5using6using7using8using9usingusingusingusingusingusingnamespace{publicclassFormAuthenticationFilttribute:AuthorizationFil{privateconststringUnauthorizedMessage="请求未,。publicoverridevoid{if>{}if(HttpContext.Current.User!=null&&{}vars=actionContext.Request.Headers.Getif(s==null||s.Count<{actionContext.Response=new{Content=newStringContent(UnauthorizedMessage,Encoding.UTF8)}FormsAuthenticationTicketticket=GetTicket(if(ticket=={actionContext.Response=new{Content=newStringContent(UnauthorizedMessage,Encoding.UTF8)}varprincipal=newGenericPrincipal(newFormsIdentity(ticket),HttpContext.Current.User=Thread.CurrentPrincipal=}privateFormsAuthenticationTicketGetTicket(Collection<HeaderValue>{FormsAuthenticationTicketticket=foreach(varitemin{var=item.s.SingleOrDefault(c=>c.Nameif(!={ticket=FormsAuthentication.Decrypt(}}return}}}在需要认证后才能的Controller中类或ACTION方法上添加上述过滤器 1using2using3using4using5using6using7using8using9using10namespace11{12publicclassTestController:{13publicHttpResponseMessageLogin(stringuname,string{if parison.OrdinalIgnoreCase)&&{FormsAuthenticationTicketticket=newFormsAuthenticationTicket(1,uname,DateTime.Now.AddMinutes(30),false,stringauthTicket=9//为Http=newHttp(FormsAuthentication.FormsName,20.Path=FormsAuthentication.FormsPath; 2122//FormsAuthentication.SetAuth(uname,false,23returnRequest.CreateResponse(HttpStatusCode.OK,}24{25ame){Expires=DateTime.Now.AddDays(-10)});//测试用:当登录失败时,清除可能存在的验证26returnRequest.CreateErrorResponse(HttpStatusCode.NotFound,"登录失败,无效的用户名或27}28}29//GETpublicIEnumerable<string>30{returnnewstring[]{"value1","value2"31}3//GET233publicstringGetValue(int{return34}}35}363738394044748495055758若成功调用Login方法后(),再 来调用Api的相关方法,示例代码如下1publicasyncstaticvoid2{3HttpHandlerhandler=newHttp4handler.Uses=true;//因为采用Form验证,所以需要使用记录登录信56 =newHttp789varresponse=awaitvarr=await ine("StatusCode:{0}",if{Console.Wriine("Msg:{1}",response.StatusCode,} ine("Msg:{1}",response.StatusCode,vargetshandler.Container.Gets(newUri("Console.Wriine("获取到的数量:"+get for(inti=0;i<gets.Count;{Console.Wriine(gets[i].Name+":"}response=varr2=awaitforeach(stringitemin{Console.Wriine("GetValues-ItemValue:{0}",}response=varr3=awaitConsole.Wriine("GetValue-ItemValue:{0}",}如果WebApi作为ASP.NET或MVC的一部份使用,那么完全可以采用基于默认的FORM验证特ASP.NETMVC的FORM验证1<authentication2然后在需要认证后才能的Controller中类或ACTION方法上添加Authorize特性,Controller与上文相同WEB.CONFIG中配置:12<deny3最后将WEBAPI寄宿到(或者说发布到)IIS,且需要在IIS中启用WINDOWS验证,如下图示这样就完成了该验证模式(理论上WEB服务、WCF若都以IIS为宿主,都可以采用集成WINDOWS验证 来调用WEBAPI,示例代码如下1publicasyncstaticvoid2{3HttpHandler=new45handler.Options67=newNetworkCredential("admin", 89Http=newHttpvarresponse=varr2=foreach(stringitemin{Console.Wriine("GetValues-Value:{0}",}response=varr3=awaitConsole.Wriine("GetValue-Item}定义一个继承自AuthorizationFil 1using2using3using4using5using6using7using8using9using10usingusing11namespace12{publicclassHttpBasicAuthenticationFilter:AuthorizationFil{publicoverridevoidOnAuthorization(System.Web.Http.Controllers.HttpActionContext{{}if(Thread.CurrentPrincipal!=null&&8{}stringauthParameter=varauthValue=actionContext.Request.Headers.Authorization;if(authValue!=null&&authValue.Scheme=="Basic"){authParameterauthValue.Parameter;//authparameter:Base64编码的(码}425if{2627}28authParameter=29varauthToken=if(authToken.Length<30{3}if(!ValidateUser(authToken[0],{}varprincipal=newGenericPrincipal(newGenericIdentity(authToken[0]),Thread.CurrentPrincipal=if(HttpContext.Current!=3{7HttpContext.Current.User=38}39}40privatevoidChallenge(HttpActionContext4{varhost=actionContext.Response=actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,请求未,。//actionContext.Response.Headers.Add("WWW-Authenticatestring.Format("Basicrealm=\"{0}\"",ing.Format("realm=\"{0}\"",}protectedvirtualboolValidateUser(stringuserName,string474{if(userName.Equals("admin", parison.OrdinalIgnoreCase)&&password.Equals("api.admin"))//判断用户名及,实际可从数据库查询验证,可重写{8return4}9return50}5}1}5253545556575859606676869707172737475767778798088788在需要认证后才能的Controller中类或ACTION方法上添加上述定义的 来调用WEBAPI,示例代码如下1publicasyncstaticvoid2{3 =newHttp4.DefaultRequestHeaders.Authorization=CreateBasicHeader("admin",56varresponse=await7varr2=await8foreach(stringitemin9{Console.Wriine("GetValues-ItemValue:{0}",}response=awaitvarr3=awaitConsole.Wriine("GetValue-ItemValue:{0}",}publicstaticAuthenticationHeaderValueCreateBasicHeader(stringusername,string{returnnewusername,}实现Basic基础认证,除了通过继承自AuthorizationFil ttribute来实现自定义的验证过滤器外,还可以通过继承自DelegatingHandler来实现自定义的消息处理管道类,具体的实现方式可参见园子里的这篇文章: 1using2using3using4using5using6using7using8using9usingusingusingnamespace{publicclassHttpDigestAuthenticationHandler:{protectedasyncoverrideTask<HttpResponseMessage>SendAsync(HttpRequestMessageCancellationToken{{HttpRequestHeadersheaders=if(headers.Authorization!={Headerheader=newif(Nonce.IsValid(header.Nonce,{stringpassword if {password"api.admin";//}#region计算正确的可的Hashstringha1=String.Format("{0}:{1}:{2}",header.UserName,stringha2=String.Format("{0}:{1}",stringcomputedResponse=ha1,header.Nonce,once,"auth",if pareOrdinal(header.Response,computedResponse0较请求的Hash值与正确的可的Hash值是否相同,相则则表示验证通过,否则失{//digestcomputedmatchesthevaluesentbyinthe//Lookslikeanauthentic!Createa varclaims=new newClaim(ClaimTypes.Name, new ClaimsPrincipalprincipal=newClaimsPrincipal(new[]{ClaimsIdentity(claims,"Digest") Thread.CurrentPrincipal= if(HttpContext.Current!= HttpContext.Current.User=var=newGenericPrincipal(newGenericIdentity(header.UserName),Thread.CurrentPrincipal=if(HttpContext.Current!={HttpContext.Current.User=}}}}HttpResponseMessageresponse=awaitbase.SendAsync(request,if(response.StatusCode=={response.Headers.WwwAuthenticate.Add(new}return}catch{varresponse=return}}}publicclass{publicHeader(){publicHeader(stringheader,string{stringkeyValuePairs=header.Rece("\"",foreach(stringkeyValuePairin{intindex= stringkey=keyValuePair.Substring(0,stringvalue=keyValuePair.Substring(index+switch{case"username":this.UserName=value;case"realm":this.Realm=value;case"nonce":this.Nonce=value;case"uri":this.Uri=value;case"nc":this.NounceCounter=value;case once=value;case"response":this.Response=value;case"method":this.Method=value;}}ifthis.Method=}publicstringCnonce{get;privateset;publicstringNonce{get;privateset;publicstringRealm{get;privateset;publicstringUserName{get;privateset;publicstringUri{get;privateset;publicstringResponse{get;privateset;publicstringMethod{get;privateset;publicstringNounceCounter{get;privateset;//Thispropertyisusedbythehandlertogenerate//nonceandgetitreadytobepackagedin//WWW-Authenticateheader,aspartof401publicstaticHeaderGetUnauthorizedResponseHeader(HttpRequestMessage{varhost=returnnew{Realm=Nonce=}publicoverridestring{StringBuilderheader=newheader.AppendFormat(",qop=\"{0}\"",return}}publicclass{privatestaticConcurrentDictionary<string,Tuple<int,nonces=newConcurrentDictionary<string,Tuple<int,publicstaticstring{byte[]bytes=newusing(varrngProvider=new{}stringnonce=nonces.TryAdd(nonce,newTuple<int,DateTime>(0,return}publicstaticboolIsValid(stringnonce,string{Tuple<int,DateTime>cachedNonce=//nonces.TryGetValue(nonce,outnonces.TryRemove(nonceoutcachedNonce);//nonceif(cachedNonce!=null)//nonceis{//noncecountisgreaterthantheoneinif(Int32.Parse(nonceCount)>{//noncehasnotexpiredif(cachedNonce.Item2>{//updatethedictionarytoreflectthenoncecountjustreceivedthis//nonces[nonce]=newTuple<int,//Everythinglooksok-servernonceisfreshandnoncecountseems//incremented.Doesnotlooklikerereturn}}}return}}}1using2using3using45namespace6{7publicstaticclass8{9publicstaticstringToMD5Ha

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论