我正在使用web 2和MVC 5开发一个Web应用程序。
我的应用程序有api : api/ account /login,它用于检查已发布的信息,并在授予访问应用程序帐户时抛出状态200。
另外,我有一个视图: /Home/Index,它只对经过身份验证的客户端可用。
现在,我的方法是:
我的问题是:
-我的方法可能吗?
-如何像MVC 5对其cookie那样在Web 2中加密我的cookie ?
谢谢,
发布于 2016-07-18 04:01:51
实现这一点的最佳方法是在MVC project.IdentityServer https://github.com/IdentityServer/IdentityServer3中使用授权服务器(生成令牌的project.IdentityServer)和令牌消费中间件。然而,我已经这样做了如下
使用带有WEB和ASP.Net标识的JWT构建一个授权服务器,如下面所解释的那样
一旦您这样做,webAPIs的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);}
您可以在这里找到CustomOAuthProvider,CustomJwtFormat类,https://github.com/tjoudeh/AspNetIdentity.WebApi/tree/master/AspNetIdentity.WebApi/Providers
在我希望使用相同令牌保护的所有其他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);生成一个机器密钥,并将其添加到web.config的webAPI和ASP.Net MVC站点中。
这样就可以在MVC站点中创建cookie并授权属性,WebAPI将尊重此cookie。
P.S. -我使用了一个发布JWT (授权服务器或Auth & resource )的web API,并且能够成功地使用ASP.Net MVC网站、内置于python (资源服务器)、spring (资源服务器)、Android中的SPA站点。
发布于 2016-07-17 18:31:03
一旦用户对帐户控制器进行了身份验证,就可以设置饼干。
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]
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;
}
}https://stackoverflow.com/questions/38424518
复制相似问题