Лучший способ для достижения этой цели, чтобы сервер авторизации (генерируя WebAPI токен) и средний уровень потребления токенов в вашем проекте MVC. ИдентификаторServer https://github.com/IdentityServer/IdentityServer3 должен помочь. Однако я сделал это, как показано ниже
Встроенный сервер авторизации с помощью JWT с WEB API и ASP.Net идентичности, как описано здесь http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/
как только вы, что ваши 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 (серверах ресурсов), которые вы хотите защитить, используя тот же токен.Так как вы хотите, чтобы потреблять маркер, порожденную WebAPI в проекте MVC, после реализации сервера авторизации вам нужно сделать ниже
В приложении 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 когда это вы получаете жетон де-сериализовать и генерировать печенье из маркера доступа
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.
С этим будет создан файл cookie и атрибут [Авторизоваться] на сайте MVC и WebAPI будут отмечать этот файл cookie.
P.S. - Я сделал это с веб-API, выдающим JWT (сервер авторизации или сервер ресурсов Auth &) и успешно смог потреблять на веб-сайте ASP.Net MVC, сайт SPA, построенный на основе угловых, защищенных API, встроенных в python (ресурсный сервер), весной (ресурсный сервер), приложение для Android.
Можете ли вы проверить мой ответ. Я что-то пропустил? –