对不起,如果这个问题的措辞不佳,我是身份验证的新手。
我有一个为我的Web前端服务的ASP.NET MVC项目,并且使用OWIN和基于身份Cookie的身份验证对此进行身份验证。这似乎与我的Web API无关。
i也有一个ASP.NET Web API项目,该项目也使用OWIN和基于身份令牌的身份验证进行身份验证,例如向/令牌端点提出请求,并获取可用于向API端点提出请求的承载令牌。当使用/令牌端点生成的携带者令牌在通过邮递员通过postman调用时,这正常工作,但是由于我想从MVC应用程序调用API时,我无法使用令牌端点来生成一个令牌。
我的问题是我希望能够从我身份验证的ASP.NET MVC应用程序中向ASP.NET Web API提出请求,我该如何生成我可以称呼Web API的令牌?鉴于我有一个已经过认证的索赔。
我的MVC项目的启动。
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.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
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
}
}
我的Web API项目的启动。
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
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);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/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);
}
}
谢谢您,请告诉我是否有其他信息有用。
我以前实现的一个选项是从MVC应用程序成功登录后从API中检索一个令牌 - 使用在登录过程中传递的相同凭据。将令牌存储您的好处(即在ASP.NET会话状态(,然后在您的应用程序中使用它。
您的MVC应用程序登录控制器操作可能看起来像这样:
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
BearerToken token;
using (var httpClient = new HttpClient())
{
var tokenRequest =
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", model.Email),
new KeyValuePair<string, string>("password", model.Password)
};
HttpContent encodedRequest = new FormUrlEncodedContent(tokenRequest);
HttpResponseMessage response = httpClient.PostAsync("https://YourWebApiEndpoint/Token", encodedRequest).Result;
token = response.Content.ReadAsAsync<BearerToken>().Result;
// Store token in ASP.NET Session State for later use
Session["ApiAccessToken"] = token.AccessToken;
}
return RedirectToAction("SomeAction", "SomeController");
}
BearerToken只是完整API令牌结构的定制类表示:
public class BearerToken
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public string ExpiresIn { get; set; }
[JsonProperty("userName")]
public string UserName { get; set; }
[JsonProperty(".issued")]
public string Issued { get; set; }
[JsonProperty(".expires")]
public string Expires { get; set; }
}
MVC应用程序中的一个示例调用以检索某些数据,然后看起来像这样:
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Session["ApiAccessToken"].ToString());
var response = httpClient.GetAsync("https://YourWebApiEndpoint/SomeController/SomeGetAction").Result;
// Do something with response...
}