我们先新增一个网站,名为“ClientMvc",也是asp.net core Web应用程序(模型视图控制器)
使用nuget安装以下引用
Microsoft.AspNetCore.Authentication.Cookies
Microsoft.AspNetCore.Authentication.OpenIdConnect
打开Properties\launchSettings.json,修改端口为44302
我们修改该网站的Home页,打开View/Home/Index.cshtml,使用以下内容替换
@using Microsoft.AspNetCore.AuthenticationClaims
-
@foreach (var claim in User.Claims)
{
- @claim.Type
- @claim.Value }
Properties
-
@foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
{
- @prop.Key
- @prop.Value }
修改控制器,加上Authorize属性
同样需要调整startup.cs的两个方法
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); IdentityModelEventSource.ShowPII = true; services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect("oidc", options => { options.SignInScheme = "Cookies"; options.Authority = "https://localhost:44300"; options.RequireHttpsMetadata = true; options.ClientId = "mvc"; options.SaveTokens = true; }); }
Configure方法,增加app.UseAuthentication();
MVC的网站调整好了,现在如果运行该网站的话,会提示错误
好了,现在需要去为我们的认证服务器加上Implicit模式的支持
在Config.cs上需修改两处
1.加上相应的Client。
2.添加IdentityResource
以下是整个文件代码
using IdentityServer4; using IdentityServer4.Models; using System.Collections.Generic; namespace IdentityMvc { public static class Config { public static IEnumerableGetIdentityResources() { return new IdentityResource[] { new IdentityResources.OpenId(), //Implicit need it. new IdentityResources.Profile() }; } public static IEnumerable GetApiResources() { return new List { new ApiResource("api1", "My API") }; } public static IEnumerable GetClients() { return new List { new Client { ClientId = "client", // no interactive user, use the clientid/secret for authentication AllowedGrantTypes = GrantTypes.ClientCredentials, // secret for authentication ClientSecrets = { new Secret("secret".Sha256()) }, // scopes that client has access to AllowedScopes = { "api1" } }, new Client { ClientId = "mvc", ClientName = "MVC Client", AllowedGrantTypes = GrantTypes.Implicit, RequireConsent=false,//不需要显示否同意授权 页面 这里就设置为false RedirectUris = { "https://localhost:44302/signin-oidc" },//登录成功后返回的客户端地址 PostLogoutRedirectUris = { "https://localhost:44302/signout-callback-oidc" },//注销登录后返回的客户端地址 AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, "api1", "api2.read_only" }, } }; } } }
修改项目为多启动项目
鼠标右键点击”解决方案”,选择属性
按上图启动后,你会发现IE打开两个page,且都访问了44300端口
至此,44302的首页处于认证保护之下了。下一步就是回到44300去实现Account控制器的Login方法,完成整个认证过程。因为要读取数据库,内容比较多,另起一篇来说明过程。