![](/img/trans.png)
[英]ASP.NET Core MVC Authenticate User to Azure AD then create JWT Bearer Token to call Web API
[英]Web API – authenticate with bearer token
我创建了一个 MVC 应用程序,用于允许外部身份验证/注册。 它已经创建了所有必要的组件(Owin、EF、注册、登录、注销),我能够在应用程序中执行所有基本活动。
现在,我想将 Web 应用程序与我的移动应用程序也将使用的 Web API 集成。 我坚持在 Web API 调用中进行身份验证(使用我从 Web 应用程序收到的不记名令牌)。
我看到了在启用 OWIN 中间件的情况下创建 WEB API 项目的示例。 但我不知道如何集中外部身份验证过程并为我的 Web 应用程序和移动应用程序使用令牌而且我不想使用 ANGULAR或单页应用程序。 任何人都可以建议我解决此问题的正确技术途径。 谢谢你。
第1步:
我在 Visual Studio 2015 中创建了一个启用个人登录的 MVC 项目。 并配置了我在谷歌开发者控制台中配置所有内容的密钥。 我的Startup.cs会有以下代码
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);
// 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))
}
});
第2步:
更改了 webconfig 文件以指向我的本地数据库并运行该应用程序,我能够使用我的 gmail 帐户通过 google 成功登录,并且用户详细信息已成功添加到数据库中的 ASPUSerTables
第 3 步:
现在我想创建一个 WEB API 项目,它将连接到数据库并将一些数据检索到 MVC Web 应用程序和移动应用程序(我在这里卡在身份验证部分)。 我也需要对我的移动应用程序使用第三方身份验证 (Xamarin) 并使用我的移动应用程序和 MVC 网站中的通用 API
第 4 步所以我想,我应该创建 WEB API 项目,而不是 WEB 应用程序(第 1 步),它如下所示,在Startup.cs 中返回身份验证令牌,并将该 cookie 存储在网站中以传递后续请求。
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// 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
};
我不想使用 ANGULAR,我需要我的 WebApplication(MVC) 和 WEB API 项目正确验证所有请求。 请告诉我正确的道路。 谢谢
您需要做的是按照以下步骤操作
这将是我们的架构
这是 API 控制器
[Authorize]
public class ValuesController : ApiController
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "values1", "values2" };
}
}
这是你的 MVC 控制器
public class MVCValuesController : Controller
{
HttpClient client;
// web api Url
string url = string.Format("http://localhost:60143/api/Values");
string bearerToken = string.Format("bearer token from web api");
public MVCValuesController()
{
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearerToken);
}
public ActionResult GetValues()
{
HttpResponseMessage responseMessage = client.Get(url);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
var jsonResponse = JsonConvert.DeserializeObject<List<string>>(responseData);
return View(jsonResponse);
}
return View("Error");
}
}
我没有在这里使用异步,但你可以做到。 并且您还需要在运行时启动您的两个项目。 右键单击解决方案并单击Set Start Up projects
然后您可以选择多个项目并将操作设置为Start
。
public class MVCAccountController : Controller
{
HttpClient client;
// web api Url
string url = string.Format("http://localhost:60143/");
//string bearerToken = string.Format("bearer token from web api");
public MVCValuesController()
{
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// just adding a JObject you can create a class
JObject tokenJobject = new JObject(
new JProperty("Email", "someone@example.com"),
new JProperty("Password", "Pass123"));
new JProperty("ConfirmPassword", "Pass123"));
HttpContent baseContent = new StringContent(tokenJobject.ToString(), Encoding.UTF8, "application/json");
//client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearerToken);
}
public async Task<ActionResult> GetValues()
{
string requestUri = string.Format("api/Account/Register");
HttpResponseMessage responseMessage = await client.PostAsync(requestUri, baseContent);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync();
var jsonResponse = JsonConvert.DeserializeObject<string>(responseData);
return View(jsonResponse);
}
return View("Error");
}
}
public class MVCValuesController : Controller
{
HttpClient client;
// web api Url
string url = string.Format("http://localhost:60143/api/Values");
string bearerToken = string.Format("bearer token from web api");
public MVCValuesController()
{
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
}
public ActionResult GetValues()
{
HttpResponseMessage responseMessage = client.Get(url);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
var jsonResponse = JsonConvert.DeserializeObject<List<string>>(responseData);
return View(jsonResponse);
}
return View("Error");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.