java bearer token_从Web API在MVC中存储Bearer Token的位置

我设法提出了一些我觉得可以很好用的东西 .

我正在使用Owin Middleware进行Cookie身份验证 .

在MVC应用程序中,我有一个Owin Startup文件,其中配置了Cookie身份验证: -

public class Startup

{

public void Configuration(IAppBuilder app)

{

// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

app.UseCookieAuthentication(new CookieAuthenticationOptions()

{

AuthenticationType = "ApplicationCookie",

LoginPath = new PathString("/Account/Login"),

});

}

}

然后我创建了一个AccountController,其中包含两个用于登录和注销的Action方法: -

Logging In.

public ActionResult Login(LoginModel model,string returnUrl)

{

var getTokenUrl = string.Format(ApiEndPoints.AuthorisationTokenEndpoint.Post.Token, ConfigurationManager.AppSettings["ApiBaseUri"]);

using (HttpClient httpClient = new HttpClient())

{

HttpContent content = new FormUrlEncodedContent(new[]

{

new KeyValuePair("grant_type", "password"),

new KeyValuePair("username", model.EmailAddress),

new KeyValuePair("password", model.Password)

});

HttpResponseMessage result = httpClient.PostAsync(getTokenUrl, content).Result;

string resultContent = result.Content.ReadAsStringAsync().Result;

var token = JsonConvert.DeserializeObject(resultContent);

AuthenticationProperties options = new AuthenticationProperties();

options.AllowRefresh = true;

options.IsPersistent = true;

options.ExpiresUtc = DateTime.UtcNow.AddSeconds(int.Parse(token.expires_in));

var claims = new[]

{

new Claim(ClaimTypes.Name, model.EmailAddress),

new Claim("AcessToken", string.Format("Bearer {0}", token.access_token)),

};

var identity = new ClaimsIdentity(claims, "ApplicationCookie");

Request.GetOwinContext().Authentication.SignIn(options, identity);

}

return RedirectToAction("Index", "Home");

}

Logging Out

public ActionResult LogOut()

{

Request.GetOwinContext().Authentication.SignOut("ApplicationCookie");

return RedirectToAction("Login");

}

Protecting the Resources

[Authorize]

public class HomeController : Controller

{

private readonly IUserSession _userSession;

public HomeController(IUserSession userSession)

{

_userSession = userSession;

}

// GET: Home

public ActionResult Index()

{

ViewBag.EmailAddress = _userSession.Username;

ViewBag.AccessToken = _userSession.BearerToken;

return View();

}

}

public interface IUserSession

{

string Username { get; }

string BearerToken { get; }

}

public class UserSession : IUserSession

{

public string Username

{

get { return ((ClaimsPrincipal)HttpContext.Current.User).FindFirst(ClaimTypes.Name).Value; }

}

public string BearerToken

{

get { return ((ClaimsPrincipal)HttpContext.Current.User).FindFirst("AcessToken").Value; }

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值