【问题标题】:Token auth in asp mvc 6asp mvc 6中的令牌身份验证
【发布时间】:2016-05-04 14:51:27
【问题描述】:

似乎没有很多关于如何使用新 MVC 版本进行授权的信息。由于 ASP 5 现在处于 RC 1 中,您可能会猜到您现在可以开始尝试了解它的工作原理......

我想要做的只是一个包含用户名和角色的身份验证令牌的简单示例。 http://bitoftech.net/2015/03/11/asp-net-identity-2-1-roles-based-authorization-authentication-asp-net-web-api/ 之类的链接会有很大帮助,但似乎很难找到

【问题讨论】:

    标签: asp.net asp.net-core-mvc


    【解决方案1】:

    你可以试试OpenIddict。您需要 RC2 才能使用它,但它很容易设置:

    public void ConfigureServices(IServiceCollection services) {
        services.AddMvc();
    
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
    
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddOpenIddict(); // Add the OpenIddict services after registering the Identity services.
    }
    
    public void Configure(IApplicationBuilder app) {
        app.UseOpenIddict();
    }
    

    Sean Walsh 在他的博客上发布了详细的演练:http://capesean.co.za/blog/asp-net-5-jwt-tokens/

    【讨论】:

      【解决方案2】:

      您可以使用OpenIdConnect.Server。你可以这样设置

      Startup.cs

      public class Startup {
          public IConfigurationRoot configuration { get; set; }
      
          public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) {
              IConfigurationBuilder builder = new ConfigurationBuilder();
              configuration = builder.Build();
          }
      
          public void ConfigureServices(IServiceCollection services) {
              services.AddIdentity<ApplicationUser, IdentityRole>(options => {
                  options.User.RequireUniqueEmail = true;
                  options.Password.RequireDigit = false;
                  options.Password.RequireLowercase = false;
                  options.Password.RequireUppercase = false;
                  options.Password.RequireNonLetterOrDigit = false;
                  options.Password.RequiredLength = 6;
              }).AddEntityFrameworkStores<DataModelContext>();
          }
      
          public void Configure(IApplicationBuilder app) {
              app.UseJwtBearerAuthentication(new JwtBearerOptions {
                  AutomaticAuthenticate = true,
                  AutomaticChallenge = true,
                  Audience = "OAuth:Audience",
                  Authority = "OAuth:Authority",
                  RequireHttpsMetadata = false
              });
      
              app.UseOpenIdConnectServer(options => {
                  options.Issuer = new Uri("OpenId:Issuer");
                  options.AllowInsecureHttp = true;
                  options.AuthorizationEndpointPath = PathString.Empty;
                  options.Provider = new AuthorizationProvider();
              });
          }
      }
      

      AuthorizationProvider.cs

      public class AuthorizationProvider : OpenIdConnectServerProvider {
          public override Task ValidateTokenRequest(ValidateTokenRequestContext context) {
              context.Skip();
              return Task.FromResult(0);
          }
      
          public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) {
              string username = context.UserName;
              string password = context.Password;
      
              UserManager<ApplicationUser> userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
              ApplicationUser user = userManager.FindByNameAsync(username).Result;
      
              if (userManager.CheckPasswordAsync(user, password).Result) {
                  ClaimsIdentity identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
                  identity.AddClaim(ClaimTypes.Name, username,
                      OpenIdConnectConstants.Destinations.AccessToken,
                      OpenIdConnectConstants.Destinations.IdentityToken);
      
                  List<string> roles = userManager.GetRolesAsync(user).Result.ToList();
                  foreach (string role in roles) {
                      identity.AddClaim(ClaimTypes.Role, role,
                          OpenIdConnectConstants.Destinations.AccessToken,
                          OpenIdConnectConstants.Destinations.IdentityToken);
                  }
      
                  AuthenticationTicket ticket = new AuthenticationTicket(
                      new ClaimsPrincipal(identity),
                      new AuthenticationProperties(),
                      context.Options.AuthenticationScheme);
                  ticket.SetResources("OAuth:Audience");
      
                  List<string> scopes = new List<string>();
                  if (context.Request.HasScope("offline_access")) {
                      scopes.Add("offline_access");
                  }
                  ticket.SetScopes(scopes);
      
                  context.Validate(ticket);
              } else {
                  context.Reject("invalid credentials");
              }
      
              return Task.FromResult(0);
          }
      }
      

      然后在想要使用Authorization的Controller或者Action上,可以这样使用Authorize Attribute

      [Authorize(Roles = "Administrator")]
      public void MyAction() { }
      

      【讨论】:

        猜你喜欢
        • 2010-09-12
        • 2021-11-13
        • 1970-01-01
        • 2021-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-13
        • 1970-01-01
        相关资源
        最近更新 更多