我正在开发一个平行使用MVC和API控制器的项目。是否可以在MVC控制器上使用基于cookie的auth,在API控制器中使用基于令牌的auth?如何实现呢?
问题是 - 当我以这种方式(下面)构建我的Startup.auth并使用[Authorize]属性时 - 它没有按预期工作,因为在调用Web API时 - 它会检查cookie并允许执行没有令牌的方法。
public partial class Startup
{
private string PublicClientId { get; set; }
private OAuthAuthorizationServerOptions OAuthOptions { get; set; }
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(DatabaseContext.Create);
app.CreatePerOwinContext<MobileUserManager>(MobileUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/AuthServices/SignIn"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MobileUserManager, UserEntity, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (id) => (id.GetUserId<int>()))
}
});
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(180),
Provider = new ApplicationOAuthProvider(PublicClientId),
RefreshTokenProvider = new ApplicationRefreshTokenProvider()
};
app.UseOAuthBearerTokens(OAuthOptions);
}
}
答案 0 :(得分:0)
您可以尝试覆盖Authorize属性并检查当前的auth类型以及所需的内容(仅限伪代码):
public class AuthorizeAttribute : AuthorizeAttribute
{
private bool IsCookieAuthAllowed { get; }
public ApolloAuthorizeAttribute(bool isCookieAuthAllowed = false)
{
IsCookieAuthAllowed = isCookieAuthAllowed;
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var identity = actionContext.ControllerContext.RequestContext.Principal?.Identity;
if (identity == null)
return false;
if (identity.IsCookie())
return IsCookieAuthAllowed && identity.IsAuthenticated;
return base.IsAuthorized(actionContext);
}
}