我已遵循本教程Create a RESTful API with authentication using Web API and Jwt
我设法使身份验证部分起作用,但授权部分却不起作用(接近本教程的结尾)。如果我在授权标头中添加带有单词bearer的jwt令牌,则会给我401授权被拒绝。
我在想也许我需要创建一个自定义授权属性。
Startup.Auth.cs
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings["Issuer"];
var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["Secret"]);
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { "Any" },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
}
});
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat(issuer)
});
}
}
CustomOAuthProvider
public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var blSecurity = new BLSecurity();
var user = blSecurity.LogonUser(context.UserName, context.Password);
if (!(user.ResponseType == Global.Response.ResponseTypes.Success))
{
context.SetError("Authentication Error", "The user name or password is incorrect");
return Task.FromResult<object>(null);
}
var ticket = new AuthenticationTicket(SetClaimsIdentity(context, user.LoggedOnUser), new AuthenticationProperties());
context.Validated(ticket);
return Task.FromResult<object>(null);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult<object>(null);
}
private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context, User user)
{
//Add User Claims
var identity = new ClaimsIdentity("JWT");
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("bn", user.BranchName));
identity.AddClaim(new Claim("fn", user.FirstName));
identity.AddClaim(new Claim("ln", user.LastName));
//Add User Role Claims
var blRole = new BLRole();
var roles = blRole.GetRolesByUserId(user.UserID);
if (roles != null && roles.Count > 0)
{
foreach (var role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role.RoleName));
}
}
return identity;
}
}
CustomJwtFormat
public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
private static readonly byte[] _secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
private readonly string _issuer;
public CustomJwtFormat(string issuer)
{
_issuer = issuer;
}
public string Protect(AuthenticationTicket data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
var signingKey = new HmacSigningCredentials(_secret);
var issued = data.Properties.IssuedUtc;
var expires = data.Properties.ExpiresUtc;
return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(_issuer, null, data.Identity.Claims, issued.Value.UtcDateTime.ToLocalTime(), expires.Value.UtcDateTime.ToLocalTime(), signingKey));
}
public AuthenticationTicket Unprotect(string protectedText)
{
throw new NotImplementedException();
}
}
答案 0 :(得分:1)
我设法通过应用某人在评论部分中发布的内容来解决该问题。参见下面引用。
罗马Shramko 2016年6月23日 上面的代码中有一个错误。 JwtBearerAuthenticationOptions配置为
AllowedAudiences = new [] {“任何”},
但实际上,令牌内容不包含任何受众,因此您的请求将被拒绝。
解决此问题的最快方法(而不是最好的方法)是,从以下位置更改您在CustomJwtFormat类的Protect方法中创建令牌的方式:
新的JwtSecurityToken(_issuer,null,data.Identity.Claims,已发布.Value.UtcDateTime,expires.Value.UtcDateTime,signingKey);
对此
新的JwtSecurityToken(_issuer,“任何”,data.Identity.Claims,已发行。Value.UtcDateTime,expires.Value.UtcDateTime,signingKey);
即传递“ Any”而不是null作为第二个构造函数参数。