【发布时间】:2020-07-31 08:24:36
【问题描述】:
我已经在一个项目中添加了 ASP.NET Core 身份和 Identity Server4 和一个数据库,我想在所有其他项目中使用我的身份服务器。
IdentityServer4 启动类
public class Startup
{
public IConfigurationRoot Config { get; set; }
public Startup(IConfiguration configuration)
{
Config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.Build();
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
IdentityModelEventSource.ShowPII = true;
//=== Identity Config ===
string ConnectionString = Config.GetSection("AppSettings:DefaultConnection").Value;
var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
//-----------------------------------------------------------------
services.AddDbContext<MyIdentityDbContext>(options =>
options.UseSqlServer(ConnectionString, sql => sql.MigrationsAssembly(migrationAssembly)));
//-----------------------------------------------------------------
services.AddIdentity<MyIdentityUser, IdentityRole>(op =>
{
op.Password.RequireDigit = false;
op.Password.RequiredLength = 6;
op.Password.RequireUppercase = false;
op.Password.RequireLowercase = false;
op.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<MyIdentityDbContext>()
.AddDefaultTokenProviders();
//=== IdentityServer4 config ===
services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddDeveloperSigningCredential()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b => b.UseSqlServer(ConnectionString, sql => sql.MigrationsAssembly(migrationAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = b => b.UseSqlServer(ConnectionString, sql => sql.MigrationsAssembly(migrationAssembly));
})
.AddAspNetIdentity<MyIdentityUser>();
services.AddMvc(options => options.EnableEndpointRouting = false);
services.AddAuthorization();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
我的配置类,我用它作为我的身份数据库的种子:
public class Config
{
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Email(),
new IdentityResources.Profile(),
};
}
public static IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource("MyAPI", "My asp.net core web api"),
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client()
{
ClientId = "MyAndroidApp",
ClientName = "My Application for Android",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes=
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
IdentityServerConstants.StandardScopes.Address,
"MyAPI"
},
},
};
}
}
我在我的 IdentityServer4&Identity 项目的用户控制器中使用以下操作方法注册了一个角色为 Admin 的用户
[HttpPost]
public async Task<IActionResult> Post([FromBody]SignUpModel model)
{
MydentityUser NewUser = new MydentityUser ()
{
UserName = model.UserName,
};
IdentityResult result = await UserManager.CreateAsync(NewUser, model.Password);
if (result.Succeeded)
{
if (!RoleManager.RoleExistsAsync("Admin").Result)
{
IdentityResult r = RoleManager.CreateAsync(new IdentityRole("Admin")).Result;
r = RoleManager.CreateAsync(new IdentityRole("Member")).Result;
r = RoleManager.CreateAsync(new IdentityRole("Guest")).Result;
}
result = await UserManager.AddToRoleAsync(NewUser, "Admin");
if (result.Succeeded)
{
List<Claim> UserClaims = new List<Claim>() {
new Claim("userName", NewUser.UserName),
new Claim(JwtClaimTypes.Role, "Admin"),
};
result = await UserManager.AddClaimsAsync(NewUser, UserClaims.ToArray());
return Ok("Registered");
}
}
}
现在我有另一个 ASP.NET Web API 项目,我想在我的 android 应用程序中使用这个 api。
我的创业课
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://identity.mywebsite.ir";
options.RequireHttpsMetadata = false;
options.Audience = "MyAPI";
});
//I used below but not work too
//.AddIdentityServerAuthentication(options =>
//{
// options.Authority = "https://identity.mywebsite.ir";
// options.RequireHttpsMetadata = false;
// options.ApiName = "MyAPI";
// options.NameClaimType = ClaimTypes.Name;
// options.RoleClaimType = ClaimTypes.Role;
//});
services.AddOptions();
string cs = Configuration["AppSettings:DefaultConnection"];
services.AddDbContext<MyApiContext>(options =>
{
options.UseSqlServer(cs,
sqlServerOptions =>
{
sqlServerOptions.MigrationsAssembly("MyApi.Database");
});
});
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("default", policy =>
{
policy.WithOrigins("*")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("default");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
我的问题是当我在另一个项目中使用带有 ASP.NET Core Identity 的用户身份验证时,如何在我的 Webapi 中找到 userId,
我的两个项目(我的 webapi 和身份服务器和身份项目)中有以下操作方法。我从 /connect/token 地址获取了来自 android 应用程序的令牌,并在我的请求中发送了访问令牌。
public class TestController : ControllerBase
{
public async Task<IActionResult> Index()
{
string message = "";
if (User.Identity.IsAuthenticated)
{
message += "You are Registered ";
}
else
{
message += "You are not Registered ";
}
if (string.IsNullOrWhiteSpace(User.Identity.Name))
{
message += "UserId is null";
}
else
{
message += "UserId is not null";
}
return Ok(message);
}
}
我收到这条消息:
你没有注册 UserId 为空
如何在我的 WebAPI 中访问我的 UserId?为什么 User.Identity.Name 为空?为什么User.Identity.Claims.Count 0?
编辑
我已经在 jwt.io 网站输入了访问令牌,这是输出
{
"nbf": 1587133648,
"exp": 1587137248,
"iss": "https://identity.mywebsite.ir",
"aud": "MyAPI",
"client_id": "MyAndroidApp",
"sub": "7e904278-78cc-46a8-9943-51dfeb360d8e",// I want this in my api but i get null
"auth_time": 1587133648,
"idp": "local",
"scope": [
"openid",
"MyAPI"
],
"amr": [
"pwd"
]
}
MyApi 启动类
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://identity.mywebsite.ir";
options.RequireHttpsMetadata = false;
options.ApiName = "MyAPI";
});
services.AddOptions();
string cs = Configuration["AppSettings:DefaultConnection"];
services.AddDbContext<MyCommonDbContext>(options =>
{
options.UseSqlServer(cs,
sqlServerOptions =>
{
sqlServerOptions.MigrationsAssembly("MyAppProjectName");
});
});
services.AddDbContext<MyAppContext>(options =>
{
options.UseSqlServer(cs,
sqlServerOptions =>
{
sqlServerOptions.MigrationsAssembly("MyAppProjectName");
});
});
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://*.mywebsite.ir")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("default");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
【问题讨论】:
-
您需要在创建令牌时将 userId 存储在声明中。然后使用 ClaimPrinciple 像 "User.Claims.FirstOrDefault(x=>x.type == "userId");"
-
你可以在令牌中看到
UserId。但是当我想用User.Identity.Name得到它时,它是空的。事实上User.Claims.Count是0 -
您是否忘记在 API 的 ConfigureServices 方法中添加
services.AddAuthorization?还是您在示例中忽略了它? -
@Dennis1679 不,我的 api 中有这个,我将编辑问题以添加我的 Api Startup 类,我已经解决了我的问题,我很快就会回答我的问题,谢谢
标签: c# authentication authorization asp.net-identity identityserver4