前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ASP.NET Core分布式项目实战(oauth2 + oidc 实现 client部分)--学习笔记

ASP.NET Core分布式项目实战(oauth2 + oidc 实现 client部分)--学习笔记

作者头像
郑子铭
发布2021-01-13 15:37:25
7250
发布2021-01-13 15:37:25
举报

任务16:oauth2 + oidc 实现 client部分

实现 client 之前启动一下上一节的 server,启动之前需要清除一些代码

注释 Program 的 MigrateDbContext
代码语言:javascript
复制
public static void Main(string[] args)
{
    BuildWebHost(args)
        //.MigrateDbContext<ApplicationDbContext>((context, services) => {
        //    new ApplicationDbContextSeed().SeedAsync(context, services)
        //    .Wait();
        //})
        .Run();
}
RegisterViewModel
代码语言:javascript
复制
[Required]
//[DataType(DataType.EmailAddress)]
//public string Email{get;set;}
public string UserName { get; set; }

启动程序,使用 Config 中的 TestUser 登录

登录成功,不过现在是在本地,接下来需要把它放到客户端里面

新建一个 Asp.Net Core MVC 网站 MvcClient

在 startup 的 ConfigureServices 中添加 Authentication
代码语言:javascript
复制
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = "Cookies";
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;

        options.ClientId = "client";
        options.ClientSecret = "secret";
        options.SaveTokens = true;
    });
}
在 startup 的 Configure 中的 UseMvc 前添加 Authentication
代码语言:javascript
复制
app.UseAuthentication();
在 Program 的 CreateWebHostBuilder 中配置 Urls
代码语言:javascript
复制
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://localhost:5001")
            .UseStartup<Startup>();

客户端设置为5001来启动,然后服务端设置为5000

mvcCookieAuthSample 的 Program
代码语言:javascript
复制
public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseEnvironment("Development")
                .UseUrls("http://localhost:5000")
                .UseStartup<Startup>()
                .Build();
修改服务端的 Config 配置跳转地址
代码语言:javascript
复制
public static IEnumerable<Client> GetClients()
{
    return new List<Client>
    {
        new Client()
        {
            ClientId = "client",
            AllowedGrantTypes = GrantTypes.Implicit,// 隐式模式
            ClientSecrets =
            {
                new Secret("secret".Sha256())
            },

            RedirectUris = { "http://localhost:5001/signin-oidc" },
            PostLogoutRedirectUris = { "http://localhost:5001/signout-callback-oidc" },

            //AllowedScopes = {"api"},
            AllowedScopes =
            {
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.OpenId,
            }
        }
    };
}
客户端的 Controller 打上 Authorize 标签
代码语言:javascript
复制
[Authorize]
public class HomeController : Controller
修改客户端 launchSettings.json 中的 applicationUrl
代码语言:javascript
复制
"applicationUrl": "http://localhost:5001",
"sslPort": 0

启动服务端,客户端,可以看到跳转到登录界面

登录之后会跳转到 http://localhost:5001/

在客户端 About.cshtml 页面显示 identity 的 claims
代码语言:javascript
复制
@{
    ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

@*<p>Use this area to provide additional information.</p>*@

<dl>
    @foreach (var claim in User.Claims)
    {
        <dt>@claim.Type</dt>
        <dt>@claim.Value</dt>
    }
</dl>

启动程序,跳转之后,点击 About 进入 About 页面

主要返回了服务端 Config 中配置的信息

代码语言:javascript
复制
public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Email(),
            };
        }

课程链接

http://video.jessetalk.cn/course/explore

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-05-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DotNet NB 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 任务16:oauth2 + oidc 实现 client部分
    • 注释 Program 的 MigrateDbContext
      • RegisterViewModel
        • 在 startup 的 ConfigureServices 中添加 Authentication
          • 在 startup 的 Configure 中的 UseMvc 前添加 Authentication
            • 在 Program 的 CreateWebHostBuilder 中配置 Urls
              • mvcCookieAuthSample 的 Program
                • 修改服务端的 Config 配置跳转地址
                  • 客户端的 Controller 打上 Authorize 标签
                    • 修改客户端 launchSettings.json 中的 applicationUrl
                      • 在客户端 About.cshtml 页面显示 identity 的 claims
                      • 课程链接
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档