首页 存档 技术 查看内容

Asp.Net Core Authentication Middleware And Generate Token 拿到token后如何带入HTT ...

2018-3-30 13:00 |来自: 互联网 342 0

摘要: 或者应该包含什么信息呢?     1.这个人是谁?     2.这个人可以用此token访问什么样的内容?(scope)     3.token的过期时间 (expire)     4.谁发行的token。     5.其他任何你希望加入的声明 ...

或者应该包含什么信息呢?

    1.这个人是谁?

    2.这个人可以用此token访问什么样的内容?(scope)

    3.token的过期时间 (expire)

    4.谁发行的token。

    5.其他任何你希望加入的声明(Claims)

 那我们为什么要使用token呢?使用session或者用redis来实现stateServer不好吗?

    1.token是低(无)状态的,Statelessness

    2.token可以与移动端应用紧密结合

    3.支持多平台服务器和分布式微服务

拿到token后如何带入HTTP请求传给后台?

 答案是两种方式,Cookies和Authorization Header。那么什么时候放到Cookies中,什么时候又放到Authentication中呢?

第一,如果是在Web应用,则放到Cookies当中,并且应该是HttpOnly的,js不能直接对其进行操作,安全性会比将其存在Web Stroage中好一些,因为在Web Storage当中的内容,可以很容的被潜在的XSS脚本攻击并获取。在HttpOnly的cookies当中会相对安全一些,不过也有潜在的CSRF跨站伪造请求的危险,不过这种hack的手段成功率是很低的,有兴趣的朋友可以自行看一下CSRF原理。

第二,如果是手机移动端应用的话,那一定是存储在App本地,并由Authorization Header带到后台并得到身份认证。

WebApp Cookies Authentication

上一段前两周写的最原始的小Demo吧,没有数据库访问等,可根据demo自行改变 ,现在的新代码已经加入了很多业务在其中

startup.cs代码

using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Http.Authentication;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Logging;

using System.Collections.Generic;

using System.Security.Claims;

using Wings.AuthenticationApp.Middleware;


namespace Wings.AuthenticationApp

{

public class Startup

{

public Startup(IHostingEnvironment env)

{

var builder = new ConfigurationBuilder()

.SetBasePath(env.ContentRootPath)

.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

.AddEnvironmentVariables();

Configuration = builder.Build();


}


public IConfigurationRoot Configuration { get; }


// This method gets called by the runtime. Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)

{

// Add framework services.

services.AddMvc();

}


// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

loggerFactory.AddConsole(Configuration.GetSection("Logging"));

loggerFactory.AddDebug();


app.UseCookieAuthentication(CookieAuthMiddleware.GetOptions());

app.UseOwin();

app.UseCors(a =

声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

路过

雷人

握手

鲜花

鸡蛋

相关分类

返回顶部