Skip to main content

快速开始/常规WEB应用/ASP.NET Core MVC/

ASP.NET Core MVC

配置Authok

获取应用密钥

你需要如下信息

  • Domain
  • Client ID
  • Client Secret

配置回调URL

配置 Logout URL

集成 Authok

安装依赖

Install-Package Authok.AspNetCore.Authentication

安装并配置SDK

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Cookie configuration for HTTP to support cookies with SameSite=None
services.ConfigureSameSiteNoneCookies();

// Cookie configuration for HTTPS
// services.Configure<CookiePolicyOptions>(options =>
// {
// options.MinimumSameSitePolicy = SameSiteMode.None
// });

services
.AddAuthokWebAppAuthentication(options => {
options.Domain = Configuration["Authok:Domain"];
options.ClientId = Configuration["Authok:ClientId"];
});

services.AddControllersWithViews();
}

Startup.Configure 方法中开启认证和授权:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseAuthorization();
}

登录

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Authok.AspNetCore.Authentication;

public class AccountController : Controller
{
public async Task Login(string returnUrl = "/")
{
var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
// Indicate here where Authok should redirect the user after a login.
// Note that the resulting absolute Uri must be added to the
// **Allowed Callback URLs** settings for the app.
.WithRedirectUri(returnUrl)
.Build();

await HttpContext.ChallengeAsync(AuthokConstants.AuthenticationScheme, authenticationProperties);
}
}

显示用户信息

public class AccountController : Controller
{
[Authorize]
public IActionResult Profile()
{
return View(new
{
Name = User.Identity.Name,
EmailAddress = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value,
ProfileImage = User.Claims.FirstOrDefault(c => c.Type == "picture")?.Value
});
}
}

注销

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Authok.AspNetCore.Authentication;

public class AccountController : Controller
{
[Authorize]
public async Task Logout()
{
var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
// Indicate here where Authok should redirect the user after a logout.
// Note that the resulting absolute Uri must be added to the
// **Allowed Logout URLs** settings for the app.
.WithRedirectUri(Url.Action("Index", "Home"))
.Build();

await HttpContext.SignOutAsync(AuthokConstants.AuthenticationScheme, authenticationProperties);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}