oauth2 + oidc 实现 server部分

学习分享 丨作者 / 郑 子 铭 丨公众号 / DotNet NB / CloudNative NB

任务15:oauth2 + oidc 实现 server部分

基于之前快速入门的项目(MvcCookieAuthSample): https://www.cnblogs.com/MingsonZheng/p/11614686.html https://www.cnblogs.com/MingsonZheng/p/11623815.html

mvcCookieAuthSample2下载地址: http://video.jessetalk.cn/course/5/material/217/download

把这个 MVC 注册登录的网站变成一个单点登录,现在它是自己登录自己使用,我们需要把它的登录信息返回给第三方

添加 identityserver4 引用

在 startup 中

using IdentityServer4;

按照之前的文章添加 Config.cs

using System.Collections;
using System.Collections.Generic;
using IdentityServer4.Models;
using IdentityServer4.Test;

namespace mvcCookieAuthSample
{
    public class Config
    {
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client()
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.Implicit,// 隐式模式
                    ClientSecrets = 
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = {"api"},
                }
            };
        }

        public static IEnumerable<ApiResource> GetApiResource()
        {
            return new List<ApiResource>
            {
                new ApiResource("api", "My Api")
            };
        }

        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Email(),
            };
        }

        public static List<TestUser> GetTestUsers()
        {
            return new List<TestUser>
            {
                new TestUser
                {
                    SubjectId = "1",
                    Username = "mingsonzheng",
                    Password = "123456"
                }
            };
        }
    }
}

startup 的 ConfigureServices

startup 的 Configure 中 UseIdentityServer

我们已经把 IdentityServer4 添加到 MVC 程序中,接着需要在 Controller 中实现这个逻辑

首先注释 AccountController 原先的登录逻辑

Logout 中使用 HttpContext.SignOutAsync 替换

接着改造登录的逻辑,我们需要验证用户名和密码,前面我们在 Config 中添加了 TestUser,它被放在 TestUserStore 中,可以通过依赖注入引用进来,有了它之后就可以在登录的时候拿到用户名和密码

因为 TestUser 本身不提供 Email 登录,所以我们需要修改 LoginViewModel 以及 Login.cshtml

LoginViewModel

Login.cshtml

改造登录的逻辑

这样,我们就实现了一个通过 IdentityServer4 下的方法来实现了一个登录逻辑,然后做了一个跳转,下一节再把客户端加进来

Last updated