zoukankan      html  css  js  c++  java
  • .net core web API使用Identity Server4 身份验证

    一、新建一个.net core web项目作为Identity server 4验证服务。

     选择更改身份验证,然后再弹出的对话框里面选择个人用户账户。

     

     nuget 安装Identity server相关的依赖包

     

     添加Identity server相关的配置,首先新建config文件加,然后添加IdentityServer.cs,文件中代码如下:

    对于相关配置想做详细了解的同学可以参考园友 晓晨Master的identity server 系列博客 https://www.cnblogs.com/stulzq/p/9019446.html

    using IdentityModel;
    using IdentityServer4;
    using IdentityServer4.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace WebIdentityServer.Config
    {
        public static class IdentityServer
        {
            public static List<Client> GetClients()
            {
                return new List<Client>()
                {
                    new Client
                    {
                        ClientId = "mvc",
                        ClientName = "MVC Client",
                        AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
    
                        RequireConsent = false,
    
                        ClientSecrets =
                        {
                            new Secret("secret".Sha256())
                        },
    
                        RedirectUris           = { "http://localhost:5002/signin-oidc" },
                        PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
    
                        AllowedScopes =
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            "api1"
                        },
                        AllowOfflineAccess = false,
                        AccessTokenType = AccessTokenType.Jwt,
                    }
                };
            }
    
            public static IEnumerable<IdentityResource> GetIdentityResources()
            {
                var customProfile = new IdentityResource(
                    name: "custom.profile",
                    displayName: "Custom profile",
                    claimTypes: new[] { "name", "email", "status" });
    
                return new List<IdentityResource>
                {
                    new IdentityResources.OpenId(),
                    new IdentityResources.Profile(),
                    customProfile
                };
            }
    
            public static IEnumerable<ApiResource> GetApiResources()
            {
                return new[]
                {
                    // simple API with a single scope (in this case the scope name is the same as the api name)
                    new ApiResource("api1", "Some API 1"),
    
                    // expanded version if more control is needed
                    new ApiResource
                    {
                        Name = "api2",
    
                        // secret for using introspection endpoint
                        ApiSecrets =
                        {
                            new Secret("secret".Sha256())
                        },
    
                        // include the following using claims in access token (in addition to subject id)
                        UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.Email },
    
                        // this API defines two scopes
                        Scopes =
                        {
                            new Scope()
                            {
                                Name = "api2.full_access",
                                DisplayName = "Full access to API 2",
                            },
                            new Scope
                            {
                                Name = "api2.read_only",
                                DisplayName = "Read only access to API 2"
                            }
                        }
                    }
                };
            }
        }
    }

    在Startup类中添加如下配置:

    1. 在ConfigureServices方法中添加如下代码配置

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<ApplicationDbContext>()
                    .AddDefaultTokenProviders();
    
                // Add application services.
                services.AddTransient<IEmailSender, EmailSender>();
    
                services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(IdentityServer.GetIdentityResources())
                .AddInMemoryApiResources(IdentityServer.GetApiResources())
                .AddInMemoryClients(IdentityServer.GetClients())
                .AddAspNetIdentity<ApplicationUser>();
    
                services.AddMvc();
            }    

     2. 在Configure方法中添加如下代码配置

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseBrowserLink();
                    app.UseDeveloperExceptionPage();
                    app.UseDatabaseErrorPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
    
                // app.UseAuthentication(); // not needed, since UseIdentityServer adds the authentication middleware
                app.UseIdentityServer();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }

    在程序包管理控制台使用Update-Database命令生成DB,然后再VS中打开Sql server 对象管理器中可以看到创建的数据库及表

     

     启动servers,然后看到以下界面,点击Register注册一个用户然后点击login用注册的用户登陆。

     

     如果能够登陆成功则说明我们的Identity server搭建成功,然后我们用postman单独拿取token:

     二、配置.net core web Api使用身份验证系统:

    1. 在Startup类的ConfigureServices中添加下列配置,Authority 是我们Identity server启动使用的url。

    services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;
                    options.Audience = "api1";
                });   

    2. 在Startup类的Configure中添加下列配置。

     app.UseAuthentication();

    3. Controller 添加属性(特性)[Authorize]

    [Route("api/[controller]")]
        [ApiController]
        [Authorize]
        public class ValuesController : ControllerBase

    然后我们验证是否可以Identity server验证token.

    1. 不添加token,发送请求得到401 bad request 错误

     2. 使用token,发送请求,得到200成功的状态码,并返回response。

  • 相关阅读:
    作业一:淘宝的创新点
    asp.net面试题130道
    windows7系统下怎么将“我的电脑”图标添加到任务栏
    用jquery控制html控件
    C# windows窗口项目
    无法从命令行或调试器启动服务,必须首先安装Windows服务(使用installutil.exe),然后用ServerExplorer、Windows服务器管理工具或NET START命令启动它
    c#用反射动态获取类型
    C# 提取逗号分割的字符串
    搜索框动态匹配——前端方式(只在页面加载时从后端获取一次数据)(推荐)
    汉字转拼音的代码——(js版)
  • 原文地址:https://www.cnblogs.com/ZhangDamon/p/11780608.html
Copyright © 2011-2022 走看看