C# 总是得到;此请求的授权已被拒绝。”;在标识2中使用承载令牌?
我可以使用邮递员申请代币,如下所示:C# 总是得到;此请求的授权已被拒绝。”;在标识2中使用承载令牌?,c#,authorization,asp.net-identity-2,bearer-token,C#,Authorization,Asp.net Identity 2,Bearer Token,我可以使用邮递员申请代币,如下所示: { "access_token": "N1FL606bmDkZyLplpkLAihaviMQhB042z-rhY262M_W5nSWIv8fDOQiYkEn6GCuDnrxpdOWBS7lpxlBazHYlwnP1RvpDFED1i_ml89QNspyGOWB6TcMkT1MmfUAZ617k9MNvl5UJh2jKzUwvDDeXMURG9tEtmE3UX2L2D-1VA9kqYOzOB1UYbpMAfdTi84jsbR0lhLkNkReQ5fqg
{
"access_token": "N1FL606bmDkZyLplpkLAihaviMQhB042z-rhY262M_W5nSWIv8fDOQiYkEn6GCuDnrxpdOWBS7lpxlBazHYlwnP1RvpDFED1i_ml89QNspyGOWB6TcMkT1MmfUAZ617k9MNvl5UJh2jKzUwvDDeXMURG9tEtmE3UX2L2D-1VA9kqYOzOB1UYbpMAfdTi84jsbR0lhLkNkReQ5fqg4B3IFbbWNGWu5ONb1uuf00ixL-BIMqSvEaNn58_zCyAVFWVzcH2tayYTGT5p_AItKfYiWaYHKC0pDoZ_OBdlpB7Odc7ScwjwFM5vtpBZE81rpk8yjXnrTEk_j9n0eiloJnpWwA",
"token_type": "bearer",
"expires_in": 899,
"refresh_token": "60da311d10f043b892c703c7fb7ab061",
"as:client_id": "Erp",
"userName": "bbauer",
".issued": "Tue, 30 Jun 2015 17:56:10 GMT",
".expires": "Tue, 30 Jun 2015 18:11:10 GMT"
}
我还可以从未受保护的资源获取信息,如:
从这一点上,我看到用户处于“管理员”角色。当我尝试获取受保护的资源时,我总是会得到以下信息:“此请求的授权已被拒绝。”
以下是控制器中的方法:
[Authorize(Roles = "Administrator")]
[Route("user/{id:int}", Name = "GetUserById")]
public async Task<IHttpActionResult> GetUser(int id)
{
var user = await AppUserManager.FindByIdAsync(id);
if (user != null)
{
return Ok(TheModelFactory.Create(user));
}
return NotFound();
}
[授权(角色=“管理员”)]
[路由(“user/{id:int}”,Name=“GetUserById”)]
公共异步任务GetUser(int-id)
{
var user=await-AppUserManager.FindByIdAsync(id);
如果(用户!=null)
{
返回Ok(modelFactory.Create(user));
}
返回NotFound();
}
以下是我在postman中的设置:
内容类型:应用程序/json
接受:应用程序/json
授权:持票人6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6日,6月6月6日,6月6日,6日,6月6月6日,6月6月6日,6月6日,6月6日,6日,6月6月6月6日,6月6日,6月6日,6月6日,6月6日,6日,6月6月6月6日,6月6日,6日,6月6月6月6日,6月6月6日,6月6月6月6日,6月6月6月6日,6日,6日,U j9n0eiloJnpWwA 我可以使用fiddler来验证是否发送了授权标头。另一件需要注意的事情是,当我传入access_令牌以获取未受保护的/user/username资源时,我可以插入代码并查看具有以下设置的ClaimsPrincipal:
身份验证类型:承载人
已验证:正确
名称:bbauer 然而,如果我测试User.IsInRole(“管理员”),它总是错误的。为什么是假的?AspNetUserRole表有一个条目,当我获取该用户时,我看到他的一个角色是“管理员”。。。在上帝的绿色地球上,我错过了什么 这是我的创业课程,如果有帮助的话:
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
public static string PublicClientId { get; private set; }
public void Configuration(IAppBuilder app)
{
var httpConfig = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(httpConfig);
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(httpConfig);
}
public void ConfigureOAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
PublicClientId = "self";
OAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(15),
Provider = new SimpleAuthorizationServerProvider(PublicClientId),
RefreshTokenProvider = new SimpleRefreshTokenProvider(),
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
}
公共类启动
{
公共静态OAuthAuthorizationServerOptions OAuthServerOptions{get;private set;}
公共静态OAuthBeareAuthenticationOptions OAuthBeareOptions{get;private set;}
公共静态字符串PublicClientId{get;private set;}
公共无效配置(IAppBuilder应用程序)
{
var httpConfig=new HttpConfiguration();
配置OAuth(应用程序);
WebApiConfig.Register(httpConfig);
应用程序UseCors(CorsOptions.AllowAll);
app.UseWebApi(httpConfig);
}
公共void配置OAuth(IAppBuilder应用程序)
{
//将db上下文和用户管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationRoleManager.Create);
PublicClientId=“self”;
OAuthServerOptions=新的OAuthAuthorizationServerOptions
{
AllowInsecureHttp=true,
TokenEndpointPath=新路径字符串(“/Token”),
AccessTokenExpireTimeSpan=TimeSpan.FromMinutes(15),
Provider=新的SimpleAuthorizationServerProvider(PublicClientId),
RefreshTokenProvider=新的SimpleRefreshTokenProvider(),
};
使用OAuthAuthorizationServer(OAuthServerOptions);
OAuthBearerOptions=新的OAuthBeareAuthenticationOptions();
应用程序使用OAuthBeareAuthentication(OAuthBeareOptions);
}
}
事实证明,我需要在SimpleAuthorizationServerProvider的GrantResourceOwnerCredentials方法中将角色添加到我的ClaimsEntity中。以下是代码(请参见注释部分):
public override异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext)
{
var allowedOrigin=context.OwinContext.Get(“as:clientAllowedOrigin”)??“*”;
context.OwinContext.Response.Headers.Add(“访问控制允许源代码”,new[]{allowedOrigin});
var userManager=context.OwinContext.GetUserManager();
ApplicationUser user=await userManager.FindAsync(context.UserName,context.Password);
if(user==null)
{
SetError(“无效的授权”,“用户名或密码不正确”);
回来
}
var identity=newclaimsidentity(context.Options.AuthenticationType);
AddClaim(新声明(ClaimTypes.Name,context.UserName));
identity.AddClaim(新声明(“sub”,context.UserName));
//这个循环是角色作为声明添加的地方
foreach(userManager.GetRoles(user.Id)中的var角色)
{
identity.AddClaim(新声明(ClaimTypes.Role,Role));
}
var props=新的AuthenticationProperties(新字典
{
{
“as:client_id”,context.ClientId??string.Empty
},
{
“用户名”,context.userName
}
});
var票证=新的身份验证票证(身份、道具);
上下文。已验证(票证);
}
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
public static string PublicClientId { get; private set; }
public void Configuration(IAppBuilder app)
{
var httpConfig = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(httpConfig);
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(httpConfig);
}
public void ConfigureOAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
PublicClientId = "self";
OAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(15),
Provider = new SimpleAuthorizationServerProvider(PublicClientId),
RefreshTokenProvider = new SimpleRefreshTokenProvider(),
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("sub", context.UserName));
//this loop is where the roles are added as claims
foreach (var role in userManager.GetRoles(user.Id))
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id", context.ClientId ?? string.Empty
},
{
"userName", context.UserName
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
}