标签:epo cal class ros uri entity index handler msf
继上一篇的授权码授权模式,这篇会继续实现混合授权模式
首先修改Config.cs 添加Client
new Client
{
ClientId = "hybrid_client",
ClientName = "hybrid Auth",
ClientSecrets = {
new Secret("hybridclientsecrets".Sha256())
},
AllowedGrantTypes = GrantTypes.Hybrid,
RequirePkce = false, //v4.x需要配置这个
RedirectUris = {
"https://localhost:7002/signin-oidc", //跳转登录到的客户端的地址
},
// RedirectUris = {"https://localhost:7002/auth.html" }, //跳转登出到的客户端的地址
PostLogoutRedirectUris = {
"https://localhost:7002/signout-callback-oidc",
},
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile, "invoice_read"
},
//允许将token通过浏览器传递
AllowAccessTokensViaBrowser = true,
// AllowOfflineAccess=true,
// 是否需要同意授权 (默认是false)
RequireConsent = true
}
添加mvc客户端HybridClient
启动端口设置为7002
安装Nuget包
dotnet add pacakage IdentityServer4
注册服务
在startup.cs中ConfigureServices方法添加如下代码:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; ;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) //使用Cookie作为验证用户的首选方式
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Authority = "https://localhost:5000"; //授权服务器地址
options.RequireHttpsMetadata = false; //暂时不用https
options.ClientId = "hybrid_client";
options.ClientSecret = "hybridclientsecrets";
options.ResponseType = "code id_token"; //代表
options.Scope.Add("invoice_read"); //添加授权资源
options.SaveTokens = true; //表示把获取的Token存到Cookie中
options.GetClaimsFromUserInfoEndpoint = true;
});
配置管道
修改startup.cs中Configure方法:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
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添加以下代码
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="GetAPI">掉用API</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Logout">退出登录</a>
</li>
}
修改HomeController.cs添加以下代码
public IActionResult Logout()
{
return SignOut(CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);
}
/// <summary>
/// 测试请求API资源(api1)
/// </summary>
/// <returns></returns>
public async Task<IActionResult> getApi()
{
var client = new HttpClient();
var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
if (string.IsNullOrEmpty(accessToken))
{
return Json(new { msg = "accesstoken 获取失败" });
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var content = await client.GetStringAsync("https://localhost:6000/WeatherForecast");
return Json(content);
}
启动并且登录并点击【掉用API】
标签:epo cal class ros uri entity index handler msf
原文地址:https://www.cnblogs.com/hyqq/p/14340196.html