問題描述
我有一個 .net core 2.2 api,它生成(在成功登錄時)一個 JWT 令牌,其中包含一個聲明身份,該身份傳遞信息,例如經過身份驗證的用戶的用戶名、權限和角色.
I have an .net core 2.2 api which generates (on a successful login) a JWT token which contains a claims identity that passes along information such as the username, permissions and roles of the authenticated user.
在我的 .net 核心 2.2 中.Web 應用程序我有一個登錄機制,它通過控制器的用戶檢索 JWT 令牌.
In my .net core 2.2. web app I have a login mechanism which retrieves the JWT token via the user of a controller.
我的問題是.
如何從我的登錄控制器中擴展令牌并設置我的網絡應用程序以包括使用身份驗證機制,如 User.Identity.IsAuthenticated
、User.IsInRole("Admin")
和控制器操作,例如 [Authorize]
和 [Authorize(Roles="Admin")]
How can I expand the token from within my login controller and set up my web app to include the use of the authentication mechanisms like User.Identity.IsAuthenticated
, User.IsInRole("Admin")
and controller actions like [Authorize]
and [Authorize(Roles="Admin")]
我一直致力于查看 facebook/google 等外部身份驗證提供程序背后的源代碼,但無濟于事.
I've been directed towards looking at the source code behind external authentication providers such as facebook/google but to no avail.
提前致謝.
推薦答案
第一步是在Startup.cs
中使用cookie認證
:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
在 Configure
方法中,使用 UseAuthentication
方法調用設置 HttpContext.User 屬性的身份驗證中間件.在調用 UseMvcWithDefaultRoute
或 UseMvc
之前調用 UseAuthentication 方法:
In the Configure
method, use the UseAuthentication
method to invoke the Authentication Middleware that sets the HttpContext.User property. Call the UseAuthentication method before calling UseMvcWithDefaultRoute
or UseMvc
:
app.UseAuthentication();
然后在您的身份驗證控制器中,獲取令牌并解碼以獲取聲明后,您應該創建新的 ClaimsIdentity
,添加您的聲明并登錄用戶:
Then in your auth controller , after getting token and decode to get the claims , you should create new ClaimsIdentity
, add your claims and sign-in user :
if (!User.Identity.IsAuthenticated)
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, YourName));
identity.AddClaim(new Claim(ClaimTypes.Name, YourName));
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
//Add your custom claims
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
}
之后,您可以使用User.Identity.IsAuthenticated
、User.IsInRole("Admin")
和[Authorize(Roles="Admin")]
:
After that , you can useUser.Identity.IsAuthenticated
, User.IsInRole("Admin")
and [Authorize(Roles="Admin")]
:
[Authorize(Roles = "Admin")]
public IActionResult About()
{
var result = User.IsInRole("Admin");
return View();
}
這篇關于ASP .NET CORE 2.2 JWT &聲明網站身份認證的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!