我正在使用 ASP.NET Core 应用程序。我正在尝试实现基于 token 的身份验证,但不知道如何使用新的 Security System对于我的情况。 我经历了examples但他们对我帮助不大,他们要么使用 cookie 身份验证,要么使用外部身份验证(GitHub、Microsoft、Twitter)。
我的场景是:angularjs 应用程序应该请求 /token url 传递用户名和密码。 WebApi 应授权用户并返回 access_token,angularjs 应用程序将在后续请求中使用它。
我找到了关于在当前版本的 ASP.NET 中实现我所需要的内容的好文章 - Token Based Authentication using ASP.NET Web API 2, Owin, and Identity .但我不清楚如何在 ASP.NET Core 中做同样的事情。
我的问题是:如何配置 ASP.NET Core WebApi 应用程序以使用基于 token 的身份验证?
最佳答案
David Fowler(ASP .NET Core 团队的架构师)组合了一组非常简单的任务应用程序,包括 simple application demonstrating JWT .我很快就会将他的更新和简单化的风格融入到这篇文章中。
此答案的先前版本使用 RSA;如果您生成 token 的相同代码也在验证 token ,那真的没有必要。但是,如果您要分配责任,您可能仍想使用 Microsoft.IdentityModel.Tokens.RsaSecurityKey 的实例来执行此操作。 .
创建一些我们稍后会用到的常量;这是我所做的:
const string TokenAudience = "Myself";
const string TokenIssuer = "MyProject";
将此添加到您的 Startup.cs 的 ConfigureServices .稍后我们将使用依赖注入(inject)来访问这些设置。我假设你的 authenticationConfiguration是 ConfigurationSection或 Configuration对象,这样您就可以为调试和生产使用不同的配置。确保安全地存储您的 key !它可以是任何字符串。
var keySecret = authenticationConfiguration["JwtSigningKey"];
var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret));
services.AddTransient(_ => new JwtSignInHandler(symmetricKey));
services.AddAuthentication(options =>
{
// This causes the default authentication scheme to be JWT.
// Without this, the Authorization header is not checked and
// you'll get no results. However, this also means that if
// you're already using cookies in your app, they won't be
// checked by default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters.ValidateIssuerSigningKey = true;
options.TokenValidationParameters.IssuerSigningKey = symmetricKey;
options.TokenValidationParameters.ValidAudience = JwtSignInHandler.TokenAudience;
options.TokenValidationParameters.ValidIssuer = JwtSignInHandler.TokenIssuer;
});
我看到其他答案更改了其他设置,例如 ClockSkew ;默认设置使其适用于时钟不完全同步的分布式环境。这些是您唯一需要更改的设置。
设置身份验证。你应该在任何需要你的中间件之前有这行 User信息,例如 app.UseMvc() .
app.UseAuthentication();
请注意,这不会导致您的 token 与 SignInManager 一起发出或其他任何东西。您需要提供自己的 JWT 输出机制 - 见下文。
您可能想要指定一个 AuthorizationPolicy .这将允许您使用 [Authorize("Bearer")] 指定仅允许 Bearer token 作为身份验证的 Controller 和操作。 .
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
.RequireAuthenticatedUser().Build());
});
棘手的部分来了:构建 token 。
class JwtSignInHandler
{
public const string TokenAudience = "Myself";
public const string TokenIssuer = "MyProject";
private readonly SymmetricSecurityKey key;
public JwtSignInHandler(SymmetricSecurityKey symmetricKey)
{
this.key = symmetricKey;
}
public string BuildJwt(ClaimsPrincipal principal)
{
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: TokenIssuer,
audience: TokenAudience,
claims: principal.Claims,
expires: DateTime.Now.AddMinutes(20),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
然后,在您想要 token 的 Controller 中,如下所示:
[HttpPost]
public string AnonymousSignIn([FromServices] JwtSignInHandler tokenFactory)
{
var principal = new System.Security.Claims.ClaimsPrincipal(new[]
{
new System.Security.Claims.ClaimsIdentity(new[]
{
new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Demo User")
})
});
return tokenFactory.BuildJwt(principal);
}
在这里,我假设您已经有了校长。如果您使用身份,则可以使用 IUserClaimsPrincipalFactory<> 改造你的 User进入ClaimsPrincipal .
测试:获取 token ,将其放入 jwt.io 的表单中.我上面提供的说明还允许您使用配置中的 secret 来验证签名!
如果您在 HTML 页面的部分 View 中呈现它并结合 .Net 4.5 中的仅承载身份验证,您现在可以使用 ViewComponent做同样的事情。它与上面的 Controller Action 代码基本相同。
关于c# - ASP.NET Core 中基于 token 的身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29048122/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
似乎无法为此找到有效的答案。我正在阅读Rails教程的第10章第10.1.2节,但似乎无法使邮件程序预览正常工作。我发现处理错误的所有答案都与教程的不同部分相关,我假设我犯的错误正盯着我的脸。我已经完成并将教程中的代码复制/粘贴到相关文件中,但到目前为止,我还看不出我输入的内容与教程中的内容有什么区别。到目前为止,建议是在函数定义中添加或删除参数user,但这并没有解决问题。触发错误的url是http://localhost:3000/rails/mailers/user_mailer/account_activation.http://localhost:3000/rails/mai
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL