AspNetCore Authentication运用

Aspnet Core认证授权,详细信息请查看:微软官方文档

1.基于策略的简单授权

//验证必要模型
public class TestPolicyRequirement : IAuthorizationRequirement
{
        public string Name { get; }
        public TestPolicyRequirement(string name)
        {
            //名称检验
            this.Name = name;
        }
}
//验证处理程序
public class TestAuthorizationHandler : AuthorizationHandler
{
     protected override Task 
    HandleRequirementAsync(AuthorizationHandlerContext context,AdultPolicyRequirement requirement)
        {
            //获取当前http请求的context对象
            var mvcContext = context.Resource as AuthorizationFilterContext;
            var age = mvcContext.HttpContext.Request.Query.FirstOrDefault(u => u.Key == "name");
            if (name !="admin")
            {
                //验证失败
                context.Fail();
            }
            else
            {
                //通过验证,这句代码必须要有
                context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }
}
//Startup 配置services
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //可以添加多种认证策略,这里只添加1种
            services.AddAuthorization(options =>
            {
                options.AddPolicy("admin", policy =>
                   policy.Requirements.Add(new AdultPolicyRequirement("admin")));
            });
            //添加策略验证handler          services.AddSingleton<IAuthorizationHandler,AdultAuthorizationHandler>();
        }
//到相应的控制器方法上添加对应策略特性:[Authorize("admin")]

2.中间件方式,当然中间件可不只这个作用。

//自定义一个中间件
public class AuthorizeMiddleware
    {
        private readonly RequestDelegate next;
        public AuthorizeMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context )
        {
            //这个例子只是修改一下response的header
            context.Response.OnStarting(state => {
                var httpContext = (HttpContext)state;
                httpContext.Response.Headers.Add("test2", "testvalue2");
                return Task.FromResult(0);
            }, context);
            await next(context);
            
        }
    }
//Startup Configrure方法最前面添加
app.UseMiddleware(typeof(AuthorizeMiddleware));

3.AspNetCore.Authentication其他验证方式

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Security.Claims;

namespace Authentication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://localhost:5000")
                .UseStartup<Startup>();
    }

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
                    {
                        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    })
                    .AddCookie(options =>
                    {
                        options.LoginPath = "/Account/Login";
                    });
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            app.UseAuthentication();
            app.UseMvcWithDefaultRoute();
        }
    }
}

namespace Authentication.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

    public class AccountController : Controller
    {
        public IActionResult Login()
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "timi"),
                new Claim(ClaimTypes.Role, "user")
            };
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
            return Ok();
        }

        public IActionResult Logout()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Ok();
        }
    }
}
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Authentication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://localhost:5000")
                .UseStartup<Startup>();
    }

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
                    {
                        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    })
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidIssuer = Settings.Issuer,
                            ValidAudience = Settings.Audience,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.Secret))
                        };
                        /* 自定义认证方式
                        options.SecurityTokenValidators.Clear();
                        options.SecurityTokenValidators.Add(new SecurityTokenValidator());
                        options.Events = new JwtBearerEvents
                        {
                            OnMessageReceived = (context) =>
                            {
                                context.Token = context.Request.Headers["Token"].FirstOrDefault(); // context.Request.Query["token"]
                                return Task.CompletedTask;
                            }
                        };
                        */
                    });
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            app.UseAuthentication();
            app.UseMvc();
        }
    }

    public class Settings
    {
        public const string Issuer = "http://localhost:5000";
        public const string Audience = "http://localhost:5000";
        public const string Secret = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
    }

    public class SecurityTokenValidator : ISecurityTokenValidator
    {
        public bool CanValidateToken => true;

        public int MaximumTokenSizeInBytes { get; set; }

        public bool CanReadToken(string securityToken)
        {
            return true;
        }

        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken = null;
            var claimsIdentity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            if (securityToken == "token")
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, "timi"));
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            }
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            return claimsPrincipal;
        }
    }
}

namespace Authentication.Controllers
{
    [Authorize]
    [Route("Resource")]
    public class ResourceController : ControllerBase
    {
        public IActionResult Get()
        {
            return Ok();
        }
    }

    [Route("Authenticate")]
    public class AuthenticateController : ControllerBase
    {
        public IActionResult Get()
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "timi"),
                new Claim(ClaimTypes.Role, "user")
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(Settings.Issuer, Settings.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(30), credentials);
            return Ok(new JwtSecurityTokenHandler().WriteToken(token));
        }
    }
}

 

posted @ 2020-07-07 21:23  天心~  阅读(696)  评论(0编辑  收藏  举报