用幽默的语言来形容网站开发,重庆app开发,网站互联网设计图风格,千锋教育西安校区接下来我们介绍新内容,OAuth2.0叫做授权码(authorization code)#xff0c;在OpenID Connect中则属于OpenId Connect Flow#xff0c;称为授权码流程(Authorization Code Flow),这种方式主要场景#xff1a;保密客户端#xff0c;服务器端的web应用“例如asp.net core mvc,… 接下来我们介绍新内容,OAuth2.0叫做授权码(authorization code)在OpenID Connect中则属于OpenId Connect Flow称为授权码流程(Authorization Code Flow),这种方式主要场景保密客户端服务器端的web应用“例如asp.net core mvc,这种由后端处理逻辑后模板渲染的web框架”另外这种方式主要是需要先去IdentityServer申请一个授权码然后再用授权码获取token。这种方式广泛用于大厂的开放平台如微信、华为等等。这种方式的安全性最高因为它是server-server即web应用的后端与IdentityServer交互通信token都是存储在后端。基本流程如下1.请求IdentityServer的oauth/authorize? response_typecodeclient_idCLIENT_IDredirect_uriCALLBACK_URLscoperead“redirect_uri为需要授权的应用的url”2.callback?codeAUTHORIZATION_CODE“重定向至redirect_uri且会在uri后增加授权码”3.后端请求oauth/token?client_idCLIENT_IDclient_secretCLIENT_SECRET grant_typeauthorization_codecodeAUTHORIZATION_CODEredirect_uriCALLBACK_URL“再携带code去token端点获取token”在IdentityServer4中大致也是这个流程但是其中会有一些变化为了安全IdentityServer4是带有PKCE支持的授权码模式后续我们会讲到先让我们实践一下感受一下。1.IdentityServer增加UI上两篇文章主要针对的是客户端凭证和密码凭证我们继续在IdentityServer项目中进行增量开发。1.1 增加MVC UI模板代码cd .\src\IdentityServer
dotnet new is4ui
1.2 MVC生效在依赖注入和管道中使mvc生效Startup.ConfigureServices// uncomment, if you want to add an MVC-based UI
services.AddControllersWithViews();
Startup.Configure// uncomment if you want to add MVC
app.UseStaticFiles();
app.UseRouting();app.UseIdentityServer();// uncomment, if you want to add MVC
app.UseAuthorization();
app.UseEndpoints(endpoints
{endpoints.MapDefaultControllerRoute();
});
“ps:is4inmem模板包含了基本的IdentityServer同时也包含了标准UI界面也就是上面添加的模板代码”1.3 修改launchSettings.json{profiles: {MVCClient: {commandName: Project,launchBrowser: true,applicationUrl: http://localhost:6002,environmentVariables: {ASPNETCORE_ENVIRONMENT: Development}}}
}
1.4 增加客户端配置new Client{ClientIdmvc,ClientSecrets{ new Secret(secret-mvc.Sha256())},AllowedGrantTypes GrantTypes.Code,RequireConsenttrue,// where to redirect to after loginRedirectUris { http://localhost:6002/signin-oidc },// where to redirect to after logoutPostLogoutRedirectUris { http://localhost:6002/signout-callback-oidc },AllowedScopes new Liststring{api1,IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile}}
2.创建新的asp.net core mvc客户端2.1 新建项目cd .\src\
dotnet new mvc -n MVCClient
dotnet sln add .\MVCClient\MVCClient.csproj
2.2 添加nuget引用ASP.NET Core middleware that enables an application to support the OpenID Connect authentication workflow.cd .\MVCClient\
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
2.3 注册OpenId Connectusing System.IdentityModel.Tokens.Jwt;// ...JwtSecurityTokenHandler.DefaultMapInboundClaims false;services.AddAuthentication(options {options.DefaultScheme Cookies;options.DefaultChallengeScheme oidc;}).AddCookie(Cookies).AddOpenIdConnect(oidc, options {options.Authority http://localhost:5001;options.ClientId mvc;options.ClientSecret secret;options.ResponseType code;options.SaveTokens true;//scopeoptions.Scope.Add(api1);});
AddAuthentication:添加身份认证服务options.DefaultSchemeCookies:我们使用cookie记录本地登录用户options.DefaultChallengeSchemeoidc:需要用户登录将使用OpenID Connect协议AddCookie:添加cookies的处理器AddOpenIdConnect:配置执行OpenID Connect协议的处理器相关参数options.Authority:标识所信赖的token服务地址options.ClientId和options.ClientSecret:标识MVC客户端options.SaveTokens:保存从IdentityServer获取的token至cookie,ture标识ASP.NETCore将会自动存储身份认证session的access和refresh token2.4 添加身份认证 app.UseStaticFiles();app.UseRouting();app.UseAuthentication();app.UseAuthorization();app.UseEndpoints(endpoints {endpoints.MapControllerRoute(name: default,pattern: {controllerHome}/{actionIndex}/{id?}).RequireAuthorization();});
2.5 增加用户退出最后一步是增加用户退出操作。对于像IdentityServer这样的身份认证服务清除本地应用程序cookie是不够的。还需要往返于IdentityServer以清除中央单点登录的session。在控制器中增加退出操作代码public IActionResult Logout()
{return SignOut(Cookies, oidc);
}
在视图层_Layout.cshtml增加退出按钮 div classnavbar-collapse collapse d-sm-inline-flex flex-sm-row-reverseul classnavbar-nav flex-grow-1li classnav-itema classnav-link text-dark asp-area asp-controllerHome asp-actionIndexHome/a/lili classnav-itema classnav-link text-dark asp-area asp-controllerHome asp-actionPrivacyPrivacy/a/lili classnav-itema classnav-link text-dark asp-area asp-controllerHome asp-actionLogoutLoginOut/a/li/ul/div
2.6 修改Home/Index.cshtml为了测试效果修改小标题所示的视图让其展示认证授权后的User.Claimsusing Microsoft.AspNetCore.Authenticationh2Claims/h2dlforeach (var claim in User.Claims){dtclaim.Type/dtddclaim.Value/dd}
/dlh2Properties/h2dlforeach (var prop in (await Context.AuthenticateAsync()).Properties.Items){dtprop.Key/dtddprop.Value/dd}
/dl
2.测试启动IdentityServercd .\IdentityServer\
dotnet run
用vs启动MVCClient首先页面进入MVCClient起始页http://localhost:6002由于没有登录将会跳转至登录页http://localhost:5001/Account/Login键入正确的用户名和密码又会重定向至http://localhost:6002测试访问api就不演示效果了只给出相关代码controller代码public async TaskIActionResult CallApi()
{var accessToken await HttpContext.GetTokenAsync(access_token);var client new HttpClient();client.DefaultRequestHeaders.Authorization new AuthenticationHeaderValue(Bearer, accessToken);var content await client.GetStringAsync(https://localhost:6001/api/identity);ViewBag.Json JArray.Parse(content).ToString();return View(json);
}