我需要我的一个驱动程序来访问ClaimsIdentity中存储的某些信息。 在我的方法GrantResourceOwnerCredentials()下面。
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
string rol = null;
if (context.Request.Headers.ContainsKey("X-Role"))
{
rol = context.Request.Headers.Get("X-Role");
switch (rol)
{
case "user":
bool isValidCredentials = await //Logica que verifica credenciales.
if (isValidCredentials)
{
//Crea y prepara el objeto ClaimsIdentity
var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
var data = new Dictionary<string, string>
{
{"email", context.UserName}
};
var properties = new AuthenticationProperties(data);
var ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
return;
}
else
{
context.SetError("Invalid user or password.");
return;
}
case "things":
//Logica para autenticar things.
return;
default:
context.SetError("The role is not valid.");
return;
}
}
else
{
context.SetError("The role header is required.");
return;
}
}
我需要访问声明的控制器dodne的部分代码如下
[Route("{email}")]
[Authorize(Roles="user")]
public async Task<Customer> Get([FromUri] string email)
{
//here I need to obtain the value of the claim that refers to userName associated with this identity.
}
如何实现这种行为?我知道至少获得了Role的价值,因为这使[Authorize(Roles =“ user”)]起作用。
答案 0 :(得分:0)
我希望您的控制器类继承自# -*- coding: utf-8 -*-
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class test_widget(QWidget):
m_play_state = False
def __init__(self):
super(test_widget, self).__init__()
self.__ui__()
def __ui__(self):
t_lay_parent = QVBoxLayout()
self.m_label_gif = QLabel()
self.m_button_play = QPushButton("Play")
t_lay_parent.addWidget(self.m_label_gif)
t_lay_parent.addWidget(self.m_button_play)
self.m_movie_gif = QMovie("loding.gif")
self.m_label_gif.setMovie(self.m_movie_gif)
self.m_label_gif.setScaledContents(True)
self.m_label_gif.hide()
self.setLayout(t_lay_parent)
self.m_button_play.clicked.connect(self.slt_play)
def slt_play(self):
if self.m_play_state:
self.m_label_gif.hide()
self.m_movie_gif.stop()
self.m_play_state = False
else:
self.m_label_gif.show()
self.m_movie_gif.start()
self.m_play_state = True
if __name__ == "__main__":
app = QApplication(sys.argv)
win = test_widget()
win.show()
sys.exit(app.exec_())
。
在这种情况下,您可以通过以下方式访问用户声明。
首先获得一个ClaimsIdentity:
System.Web.Http.ApiController
或
ClaimsIdentity claimsIdentity = (this.User as ClaimsPrincipal)?.Identities.FirstOrDefault();
然后访问声明:
var claimsIdentity = this.User?.Identity as ClaimsIdentity;