Token auth in asp mvc 6

霸气de小男生 提交于 2019-12-09 19:36:44

问题


It seems like there is not a lot of information about how to do authorization with the new MVC version. Since ASP 5 now is in RC 1 one could guess that you now can start trying to understand how its going to work...

What I want to do is just a simple example of an auth token that contains the user's name and roles. A link like http://bitoftech.net/2015/03/11/asp-net-identity-2-1-roles-based-authorization-authentication-asp-net-web-api/ would help greatly but seems hard to find


回答1:


You can try OpenIddict for that. You need RC2 to use it, but it's quite easy to set up:

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 posted a detailed walkthrough on his blog: http://capesean.co.za/blog/asp-net-5-jwt-tokens/.




回答2:


You can use OpenIdConnect.Server. You can set it up like this

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);
    }
}

Then on the Controller or Action you want to use Authorization, you can use the Authorize Attribute like this

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


来源:https://stackoverflow.com/questions/35040996/token-auth-in-asp-mvc-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!