經過與朋友的一些交談,更合適的解決方案(在我看來)如下。 (該代碼可以清理)
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
// Do a rest call to the API
Uri _baseUri = new Uri("http://localhost:8000/");
var client = new RestClient(_baseUri + "api/Account/login");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "7ee2a21b-70d5-8a68-f0dd-518b8a61ddbf");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "Email=blah%40gmail.com&password=a1Aa1Aa1A!&=", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
// Check the response
if (response.StatusCode == HttpStatusCode.OK) {
// Grab the cookie for the Identity
// this can be replaced by a token in the future
String cookie = response.Cookies.Where(c => c.Name == ".AspNetCore.Identity.Application").First().Value;
// Store the cookie value to use it in sub-sequent requests
HttpContext.Session.SetString("IdentityCookieId", cookie);
// Add claims to our new user, an example Name and an example Role
const string Issuer = "http://blah.com";
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "AnonymUser", ClaimValueTypes.String, Issuer));
claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
var userIdentity = new ClaimsIdentity("SecuredLoggedIn");
userIdentity.AddClaims(claims);
var userPrincipal = new ClaimsPrincipal(userIdentity);
// Sign in the user creating a cookie with X ammount of Expiry
await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(1),
IsPersistent = false,
AllowRefresh = false
});
// Move back to the ReturnUrl or for me always to the dashboard
return RedirectToLocal("/dashboard");
}
}
return View(model);
}
Ofcourse,你必須編輯Startup.cs
文件ConfigureServices
下您AddMvc()
之前添加services.AddAuthorization();
。
而下Configure
添加
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookie",
LoginPath = new PathString("/account/login/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
稍微題外話:我建議'HttpClient'超過RestSharp。它完全建立在異步調用的基礎上,對單元測試有很大的支持,而RestSharp依賴於舊的'WebClient'和同步調用;至少它直到最近才這樣做。 – thoean
@thoean謝謝你的提示,我會看看HttpClient,我剛剛發現RestSharp更易於使用。此外PostMan已自動翻譯成RestSharp :) – Drakoumel