我正在使用Web API 2和MVC 5创建Web应用程序。
我的应用有api: api / account / login,用于在授予访问应用程序的帐户时检查发布的信息并抛出状态200.
另外,我有一个视图:/ Home / Index只适用于经过身份验证的客户端。
现在,我的方法是:
我的问题是:
- 我的方法可行吗?
- 如何在Web API 2中加密我的cookie,就像MVC 5对其cookie一样?
谢谢,
答案 0 :(得分:2)
一旦用户针对帐户控制器进行了身份验证,您就可以设置cookie。
public class AccountController
{
public HttpResponseMessage Login()
{
// Your authentication logic
var responseMessage = new HttpResponseMessage();
var cookie = new CookieHeaderValue("session-id", "12345");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
responseMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return responseMessage;
}
}
要进行身份验证,您可以将[Authenticate]
属性放在Home
控制器上。
public class HomeController
{
[Authenticate]
public ActionResult Index()
{
return View();
}
}
如果需要,还可以在Controller级别应用Authenticate属性。
[Authenticate]
public class HomeController
{
}
如果需要,您还可以通过覆盖AuthorizeCore并检查有效的Cookie来创建自己的授权属性:
public class CustomAuth : AuthenticationAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
HttpCookie authCookie = httpContext.Request.Cookies["CookieName"];
// Your logic
return true;
}
}
答案 1 :(得分:2)
实现此目的的最佳方法是在MVC项目中拥有授权服务器(生成令牌的webAPI)和令牌消费中间件.IdentityServer https://github.com/IdentityServer/IdentityServer3应该有所帮助。但是我已经完成了以下
使用带有WEB API和ASP.Net Identity的JWT构建授权服务器,如下所述http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/
一旦你这样做,你的webAPI startup.cs将如下所示
/// Configures cookie auth for web apps and JWT for SPA,Mobile apps
private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
// Configure the db context, user manager and role manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
//Cookie for old school MVC application
var cookieOptions = new CookieAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
CookieHttpOnly = true, // JavaScript should use the Bearer
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/api/Account/Login"),
CookieName = "AuthCookie"
};
// Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here
app.UseCookieAuthentication(new CookieAuthenticationOptions());
OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat(ConfigurationManager.AppSettings["JWTPath"])
};
// OAuth 2.0 Bearer Access Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
}
您可以在https://github.com/tjoudeh/AspNetIdentity.WebApi/tree/master/AspNetIdentity.WebApi/Providers
找到CustomOAuthProvider,CustomJwtFormat类在我想要使用相同令牌保护的所有其他API(资源服务器)中编写消费逻辑(即中间件)。由于您希望在MVC项目中使用webAPI生成的令牌,因此在实现授权服务器之后,您需要执行以下操作
在你的MVC应用程序中,在startup.cs中添加以下内容
public void Configuration(IAppBuilder app)
{
ConfigureOAuthTokenConsumption(app);
}
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings["AuthIssuer"];
string audienceid = ConfigurationManager.AppSettings["AudienceId"];
byte[] audiencesecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["AudienceSecret"]);
app.UseCookieAuthentication(new CookieAuthenticationOptions { CookieName = "AuthCookie" , AuthenticationType=DefaultAuthenticationTypes.ApplicationCookie });
//// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Passive,
AuthenticationType = "JWT",
AllowedAudiences = new[] { audienceid },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audiencesecret)
}
});
}
当您收到令牌时,在MVC控制器中对其进行反序列化并从访问令牌生成cookie
AccessClaims claimsToken = new AccessClaims();
claimsToken = JsonConvert.DeserializeObject<AccessClaims>(response.Content);
claimsToken.Cookie = response.Cookies[0].Value;
Request.Headers.Add("Authorization", "bearer " + claimsToken.access_token);
var ctx = Request.GetOwinContext();
var authenticateResult = await ctx.Authentication.AuthenticateAsync("JWT");
ctx.Authentication.SignOut("JWT");
var applicationCookieIdentity = new ClaimsIdentity(authenticateResult.Identity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
ctx.Authentication.SignIn(applicationCookieIdentity);
生成计算机密钥并将其添加到webAPI和ASP.Net MVC站点的web.config中。
这样就可以创建一个cookie,并且MVC Site和WebAPI中的[Authorize]属性将尊重这个cookie。
P.S。 - 我使用发布JWT(授权服务器或Auth&amp;资源服务器)的Web API完成了这项工作,并且成功地能够在ASP.Net MVC网站中使用,在Angular中构建的SPA站点,使用python(资源服务器)构建的安全API, spring(资源服务器),Android App。