asp mvc 6 中的令牌授权

Token auth in asp mvc 6

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

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

你可以试试 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/

您可以使用 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() { }