identityserver4隐式许可模式
继上一篇的自定义授权模式,这篇会继续实现简化模式授权
首先修改Config.cs 添加Client
new Client
{
ClientId = "Implicit_client",
ClientName = "Implicit Auth",
AllowedGrantTypes = GrantTypes.Implicit,
RedirectUris ={
"https://localhost:7000/signin-oidc", //跳转登录到的客户端的地址
"https://localhost:7000/redirect-silentrenew", //刷新AccessToken
},
PostLogoutRedirectUris ={
"https://localhost:7000/signout-callback-oidc",
},
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Phone,
IdentityServerConstants.StandardScopes.Address,
IdentityServerConstants.StandardScopes.Email,
"invoice_read"
},
//允许将token通过浏览器传递
AllowAccessTokensViaBrowser=true,
// 是否需要同意授权 (默认是false)
RequireConsent=false,
AccessTokenLifetime=60*5
},
添加mvc客户端ImplicitClient
启动端口设置为7000
安装Nuget包
dotnet add pacakage IdentityServer4
注册服务
在startup.cs中ConfigureServices方法添加如下代码:
services.AddAuthentication(options =>
{
options.DefaultScheme =CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme =OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Authority = "https://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "Implicit_client";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
});
配置管道
修改startup.cs中Configure方法:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
HomeController的Privacy添加授权 [Authorize]
修改Privacy.cshtml
@using Microsoft.AspNetCore.Authentication
<h2>Claims</h2>
<dl>
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>}
</dl>
<h2>Properties</h2>
<dl>
@foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
{
<dt>@prop.Key</dt>
<dd>@prop.Value</dd>}
</dl>
启动并且登录

退出登录
修改_Layout.cshtml 添加以下代码
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Logout">Logout</a>
</li>
修改HomeController
public IActionResult Logout()
{
return SignOut(CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);
}
修改授权服务器的AccountOptions.cs
public static bool AutomaticRedirectAfterSignOut = true;//退出登录直接跳转到首页
可以单点登录登出

浙公网安备 33010602011771号