当MVC和Web API在不同的项目中时如何存储持票人令牌

时间:2016-01-08 10:26:14

标签: asp.net-mvc cookies asp.net-web-api oauth-2.0 bearer-token

情况: 我有一个Web API 2项目,它充当授权服务器(/ token endpoint)和资源服务器。我正在使用ASP.Net Web API开箱即用的模板减去任何MVC参考。 Start.Auth配置如下:

public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId = ConfigurationManager.AppSettings["Test_Facebook_AppId"],
                AppSecret = ConfigurationManager.AppSettings["Test_Facebook_AppSecret"],
                //SendAppSecretProof = true,
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = (context) =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        return Task.FromResult(0);
                    }
                }
            };

            facebookAuthenticationOptions.Scope.Add("email user_about_me user_location");
            app.UseFacebookAuthentication(facebookAuthenticationOptions);

        }

MVC 5客户端(不同的项目)使用Web API应用程序进行授权和数据。以下是在用户名/密码存储的情况下检索Bearer令牌的代码:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            model.ExternalProviders = await GetExternalLogins(returnUrl);
            return View(model);
        }

        var client = Client.GetClient();

        var response = await client.PostAsync("Token", 
            new StringContent(string.Format("grant_type=password&username={0}&password={1}", model.Email, model.Password), Encoding.UTF8));

        if (response.IsSuccessStatusCode)
        {
            return RedirectToLocal(returnUrl);
        }
        return View();
    }

问题

我可以检索Bearer令牌,然后将其添加到授权标头以进行后续调用。我认为如果是Angular App或SPA,那就没关系了。但我认为MVC中应该有一些东西可以为我处理它,比如自动将它存储在cookie中并在后续请求中发送cookie。我已经搜索了很多,并且有一些帖子暗示了这一点(Registering Web API 2 external logins from multiple API clients with OWIN Identity),但是在得到令牌之后我还没弄清楚要做什么。

我是否需要在MVC应用程序Startup.Auth中添加一些内容?

理想情况下,我需要ASP.Net模板(MVC + Web API)中的AccountController提供的功能(登录,注册,外部登录,忘记密码等等),但需要MVC和Web API在不同的项目中。

是否有模板或git仓库有这个锅炉板代码?

提前致谢!

更新 结合@FrancisDucharme建议,下面是GrantResourceOwnerCredentials()的代码。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            //Add a response cookie...
            context.Response.Cookies.Append("Token", context.Options.AccessTokenFormat.Protect(ticket));


            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }

但我似乎仍然无法获得Cookie,或想出下一步该做什么。

重述问题:

  1. 从MVC客户端验证,授权和调用Web API方法(Auth和资源服务器)的正确方法是什么?
  2. 是否有针对AccountController的样板代码或模板进行基本的管道工作(登录,注册 - 内部/外部,忘记密码等)?

2 个答案:

答案 0 :(得分:1)

您可以让您的Startup类返回一个响应cookie,然后客户端将在所有后续请求中返回,这是一个示例。我会在GrantResourceOwnerCredentials中完成。

public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{

    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {                          

        //your authentication logic here, if it fails, do this...
        //context.SetError("invalid_grant", "The user name or password is incorrect.");
        //return;

         var identity = new ClaimsIdentity(context.Options.AuthenticationType);
         identity.AddClaim(new Claim("sub", context.UserName));
         identity.AddClaim(new Claim("role", "user"));

         AuthenticationTicket ticket = new AuthenticationTicket(identity);

        //Add a response cookie...
        context.Response.Cookies.Append("Token", context.Options.AccessTokenFormat.Protect(ticket));

        context.Validated(ticket);

}

Startup类:

public partial class Startup
{

    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }

    public Startup()
    {
        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
    }

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        ConfigureOAuth(app);
        //I use CORS in my projects....
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);

        WebApiConfig.Register(config);

    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true, //I have this here for testing purpose, production should always only accept HTTPS encrypted traffic.
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new AuthorizationServerProvider()
        };

        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(OAuthBearerOptions);

    }
}

这假设客户端已启用cookie。

然后,modify your MVC headers将Authorization标头添加到所有请求中。

ActionFilterAttribute中,获取您的Cookie值(Token)并添加标题。

答案 1 :(得分:0)

如下所示,我将其添加到 DefaultRequestHeaders 中,而不是在会话中进行存储,因此无需在每次对Web API的调用中都添加它。

    public async Task AuthenticateUser(string username, string password)
    {
        var data = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", username),
            new KeyValuePair<string, string>("password", password)
        });

        using (HttpResponseMessage response = await APIClient.PostAsync("/Token", data))
        {
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<AuthenticatedUser>();
                APIClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Access_Token);
            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
    }