码迷,mamicode.com
首页 > 其他好文 > 详细

15-oauth2+oidc实现Server部分

时间:2018-08-20 00:34:53      阅读:364      评论:0      收藏:0      [点我收藏+]

标签:prope   utc   mes   val   ack   back   dex   config   dsc   

1-我们使用之前项目的mvcCookieAuthSampe2进行改造

1.1  增加IdentityServer4

2-增加Config.cs文件,对IdentityServer提供相关的配置数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Test;
using IdentityServer4.Models;
using IdentityServer4;

namespace MvcCookieAuthSample
{
    public class Config
    {
        public static IEnumerable<ApiResource> GetApiResources() {
            return new List<ApiResource>() {
                 new ApiResource("api1","api DisplayName")
            };
        }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>() {
                 new Client(){
                     ClientId="mvc",
                      AllowedGrantTypes= GrantTypes.Implicit,
                      ClientSecrets= new List<Secret>(){
                          new Secret("secret".Sha256())
                      },
                      RedirectUris = {"http://localhost:5001/signin-oidc" },
                      PostLogoutRedirectUris = { "http://localhost/signout-callback-oidc"},
                      RequireConsent=false,
                      AllowedScopes={
                         IdentityServerConstants.StandardScopes.Profile,
                          IdentityServerConstants.StandardScopes.OpenId
                      }
                 }
            };
        }

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

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

    }
}

2-在Startup.cs文件启用IdentityServer

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddTestUsers(Config.GetTestUsers())  ;
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseIdentityServer(); //主要加了这段代码启用Identity4 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

 

3-在AccountController.cs提供登陆功能

        private TestUserStore _testUserStore;
        public AccountController(TestUserStore testUserStore)
        {
            _testUserStore = testUserStore;
        }

        public IActionResult Login(string returnUrl = null)
        {
            ViewData["returnUrl"] = returnUrl;
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(ViewModel.LoginViewModel loginModel, string returnUrl = null)
        {
            var findUser = _testUserStore.FindByUsername(loginModel.UserName);
            //  string returnUrl = Request.Form["returnUrl"];
            if (findUser == null)
            {
                ModelState.AddModelError(nameof(loginModel.UserName), "用户不存在");
            }
            else
            {
                if (_testUserStore.ValidateCredentials(loginModel.UserName, loginModel.Password))
                {
                    var profiles = new AuthenticationProperties()
                    {
                        IsPersistent = true,
                        ExpiresUtc = System.DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                    };

                    await Microsoft.AspNetCore.Http.AuthenticationManagerExtensions.SignInAsync(HttpContext, findUser.SubjectId, findUser.Username, profiles);

                    return string.IsNullOrEmpty(returnUrl) ? Redirect("/home/index") : Redirect(returnUrl);
                }
                ModelState.AddModelError(nameof(loginModel.Password), "密码不正确");
            }
            return View();

        }

 

15-oauth2+oidc实现Server部分

标签:prope   utc   mes   val   ack   back   dex   config   dsc   

原文地址:https://www.cnblogs.com/qinzb/p/9503303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!