1. 程式人生 > >.NET Core IdentityServer4實戰 第Ⅴ章-單點登入

.NET Core IdentityServer4實戰 第Ⅴ章-單點登入

  OiDc可以說是OAuth的改造版,在最初的OAuth中,我們需要先請求一下認證伺服器獲取下Access_token,然後根據Access_token去Get資源伺服器, 況且OAuth1 和 2 完全不相容,易用性差,而OIDC可以在登陸的時候就把資訊返回給你,不需要你在請求一下資源伺服器。下面我們根據Oidc來做一個單點登入。

  新建三個專案(.NET Core Mvc)兩個Client(埠5001,5002),一個Server(5000),首先在Server中新增IdentityServer4的引用。

  在Server中Config.cs用於模擬配置。

    public class Config
    {
        public static IEnumerable<ApiResource> GetApiResource()
        {
            return new List<ApiResource>
            {
                new ApiResource("api","My Api App")
            };
        }
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client()
                {
                    ClientId = "mvc",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    ClientSecrets ={
                        new Secret("secret".Sha256())
                    },
                    RequireConsent = false,
                    RedirectUris = {"http://localhost:5001/signin-oidc",
                        "http://localhost:5002/signin-oidc" } ,
                    PostLogoutRedirectUris = {"http://localhost:5001/signout-callback-oidc" ,
                        "http://localhost:5002/signout-callback-oidc" },
                    AllowedScopes = {
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.OpenId
                    }
                }
            };
        }
        public static List<TestUser> GetTestUsers()
        {
            return new List<TestUser>
            {
                new TestUser()
                {
                    SubjectId = "10000",
                    Username = "zara",
                    Password = "112233"
                }
            };
        }
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Email()
            };
        }
    }

GetClient方法中欄位為RedirectUris是登陸成功返回的地址,並且我們採用隱式模式(因為只是傳統web中傳遞Access_Token),RequireConsent是否出現同意授權頁面,這個我們後續再細說.寫完Config.cs後,我們需要依賴注入到IdentityServer中。

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;
            });
        //config to identityServer Services services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryClients(Config.GetClients()) .AddTestUsers(Config.GetTestUsers()) .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApiResource()); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }

 在Configure中新增程式碼 app.UseIdentityServer(); .我們還需要新增一個登陸頁面,名為Account.cshtml.

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

@using mvcWebFirstSolucation.Models;
@model LoginVM;

<div class="row">
    <div class="col-md-4">
        <section>
            <form method="post" asp-controller="Account" asp-action="Login" asp-route-returnUrl="@ViewData["returnUrl"]">
                <h4>Use a local to log in .</h4>
                <hr />
                <div class="from-group">
                    <label asp-for="UserName"></label>
                    <input asp-for="UserName" class="form-control">
                    <span asp-validation-for="UserName" class="text-danger"></span>
                </div>
                <div class="from-group">
                    <label asp-for="PassWord"></label>
                    <input asp-for="PassWord" type="password" class="form-control">
                    <span asp-validation-for="UserName" class="text-danger"></span>
                </div>
                <div class="from-group">
                    <button type="submit" class="btn btn-default">log in </button>
                </div>
            </form>
        </section>
    </div>
</div>
@section Scripts
{
    @await Html.PartialAsync("_ValidationScriptsPartial")
}

在控制器中我們寫一個建構函式,用於將IdentityServer.Text給我們封裝好的物件傳過來,這個物件是我們在Config.cs中新增的使用者資訊,也就是GetClients的返回值,全都在 TestUserStore 中。其中還有一個提供好的方法,來給我們用,如果驗證通過我們直接跳轉到了傳遞過來的ReturnUrl.

    public class AccountController : Controller
    {
        private readonly TestUserStore _users;
        public AccountController(TestUserStore ussotre)
        {
            _users = ussotre;
        }
        [HttpGet]
        [Route("/Account/Login")]
        public IActionResult Index(string ReturnUrl = null)
        
{
            ViewData["returnUrl"] = ReturnUrl;
            return View();
        }
        private IActionResult RediretToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction(nameof(HomeController.Index),"Home");
        }
        [HttpPost]
        public async Task<IActionResult> Login(LoginVM vm,string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                ViewData["returnUrl"] = returnUrl;
                var user =  _users.FindByUsername(vm.UserName);
                if (user==null)
                {
                    ModelState.AddModelError(nameof(LoginVM.UserName), "userName is exists");
                }
                else
                {
                    if(_users.ValidateCredentials(vm.UserName, vm.PassWord))
                    {
                        var props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                        };
                        await Microsoft.AspNetCore.Http
                            .AuthenticationManagerExtensions
                                .SignInAsync( HttpContext, user.SubjectId, user.Username, props );

                        return RediretToLocal(returnUrl);
                    }

                    ModelState.AddModelError(nameof(LoginVM.PassWord), "Wrong Password");
                }
            }
            return View();
        }
    }

這個時候最基本的服務端已經配置成功了,我們開始配置受保護的客戶端吧。

在客戶端中我們不需要引入IdentityServer,因為我們只是去請求服務端然後看看cookies有沒有在而已,所以我們只需要給受保護的客戶端的Api做好安全判斷就好.

在受保護的控制器中新增 [Authorize] 標識。然後再Startup.cs中新增安全驗證。並且在Configure中use下 app.UseAuthentication(); 

public void ConfigureServices(IServiceCollection services)
        {
            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 = "mvc";
                options.ClientSecret = "secret";
                options.SaveTokens = true;
            });

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

在首頁中最好遍歷下Claims物件,這個是通過OIDC直接給我們返回回來的.(最後另一個客戶端也這麼幹!)

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

現在我們啟動專案看一下效果吧。

 

&n