2016-01-01 127 views

回答

1

您可以实现承载令牌认证使用OAuthBearerAuthentication的

using Microsoft.Owin; 
using Microsoft.Owin.Security.OAuth; 
using Owin; 
using System; 
using System.Net; 
using System.Security.Claims; 
using System.Threading.Tasks; 
using System.Web.Http; 

[assembly: OwinStartup(typeof(ns.Startup))] 

namespace ns 
{ 
    public class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 
      HttpConfiguration config = new HttpConfiguration(); 

      ConfigureOAuth(app); 

      WebApiConfig.Register(config); 
      app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); 
      app.UseWebApi(config); 

      config.MessageHandlers.Add(new LogRequestAndResponseHandler()); 
     } 

配置:

 public void ConfigureOAuth(IAppBuilder app) 
     { 
      OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() 
      { 
       AllowInsecureHttp = true, 
       TokenEndpointPath = new PathString("/TokenService"), 
       AccessTokenExpireTimeSpan = TimeSpan.FromHours(3), 
       Provider = new SimpleAuthorizationServerProvider() 
      }; 

      // Token Generation 
      app.UseOAuthAuthorizationServer(OAuthServerOptions); 
      app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); 

     } 

最后设置标识声称

 public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider 
     { 
      public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) 
      { 
       context.Validated(); 
      } 

      public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
      { 
       context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); 

       try 
       { 
        var identity = new ClaimsIdentity(context.Options.AuthenticationType); 
        identity.AddClaim(new Claim(ClaimTypes.Name, "Name")); 
        identity.AddClaim(new Claim(ClaimTypes.Sid, "Sid")); 
        identity.AddClaim(new Claim(ClaimTypes.Role, "Role")); 

        context.Validated(identity); 
       } 
       catch (System.Exception ex) 
       { 
        context.SetError("Error...."); 
        context.Response.Headers.Add("X-Challenge", new[] { ((int)HttpStatusCode.InternalServerError).ToString() }); 
       } 
      } 
     } 
    } 
} 

这是最简单的解决方案,就像一个魅力!

+1

WCF还不支持OWIN。 – ARUNRAJ

相关问题