如何使用JWT令牌ASP.NET MVC



对不起,这是一条很长的消息,但需要澄清(我希望(我根据本文设置了一个AuthorizationServerProvider,并允许任何拥有JWT令牌的人在我的代码中调用某个API。但是,当我试图调用我的MVC项目的任何控制器或API控制器方法时,我会收到一条未授权的消息。

这是当我请求令牌(更新(时

这是当我尝试调用具有[authorize属性]的方法时

这是有效载荷

以下是我的ValidateClientAuthentication和GrantResourceOwnerCredentials方法:

using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;
using MyProject.Models;
using Microsoft.Owin.Security;
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();

}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = "*";
//
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;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); // maybe this is the problem
// oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "User"));
// oAuthIdentity.AddClaim(new Claim(ClaimTypes.Authentication, "AudienceID"));
var ticket = new AuthenticationTicket(oAuthIdentity, null);
context.Validated(ticket);
}
}

在我的Startup.Auth.cs中,我提出了两种方法,使具有[Authorize]属性的Api控制器可以使用JWT进行验证。这里的部分类别:

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security.OAuth;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading.Tasks;
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{  
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(10),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});    
/*Other Types of Authentication*/        
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(3),
Provider = new AuthorizationServerProvider(),
AccessTokenFormat = new CustomJwtFormat("https://localhost:44391")
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
}
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = "https://localhost:44391";
string audienceId = ConfigurationManager.AppSettings["AudienceID"]; //its value is "AudienceID"
byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["SecretKey"]);
string[] AllowedAud = new[] { audienceId };
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = AllowedAud,
// IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[],
IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
{
new SymmetricKeyIssuerSecurityKeyProvider(issuer, audienceSecret)
}
}) ;
}
}

我在ConfigureAuth(IAppBuilder应用程序(中调用这些方法。所以在经历了这一切之后,我不明白为什么我不能获得授权。有什么想法吗?

如果这有帮助:我正在使用Microsoft.Owin:Security.Jwt v4.1.1

我用这种方法生成令牌:

using Microsoft.Owin.Security;
using System;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
private readonly string _issuer = string.Empty;
public CustomJwtFormat(string issuer)
{
_issuer = issuer;
}
/*This Generate JWT*/
public string Protect(AuthenticationTicket data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
string username = data.Identity.Name;
string audienceId = ConfigurationManager.AppSettings["AudienceID"]; // "AudienceID"
string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["SecretKey"];

var keyByteArray = Convert.FromBase64String(symmetricKeyAsBase64);

var issued = data.Properties.IssuedUtc;

var expires = data.Properties.ExpiresUtc;

var securityKey = new SymmetricSecurityKey(keyByteArray);

var signingCredentials = new SigningCredentials(securityKey, algorithm: SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(issuer:_issuer, audience: audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials) ;

var handler = new JwtSecurityTokenHandler();

var jwt = handler.WriteToken(token);
return jwt;
}
public AuthenticationTicket Unprotect(string protectedText)
{
throw new NotImplementedException();
}
}

这是启动

using Microsoft.Owin;
using Owin;
using System.Web.Http;
[assembly: OwinStartupAttribute(typeof(MyProject.Startup))]
namespace MyProject
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
}
}

除非另有特别配置,否则会有一些强制性检查作为令牌身份验证的一部分。

  1. 令牌是由预期的发行者发行的
  2. 代币是为预期受众准备的
  3. 令牌由预期的安全密钥签名

您应该始终仔细检查1(和2(的配置,使用类似的令牌查看器https://jwt.ms/以了解有效载荷。

从这个角度来看,我可以看到你的代币中的受众是AudienceId

{
"alg": "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"typ": "JWT"
}.{
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "199c43cc-c189-4d72-a21e-0c4828f37c8f",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "UsernameTest@aaa.com",
"http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider": "ASP.NET Identity",
"AspNet.Identity.SecurityStamp": "5cb5b86f-9580-44eb-9a8f-a188262d849d",
"nbf": 1603013411,
"exp": 1603013591,
"iss": "https://localhost:44391",
"aud": "AudienceID"
}.[Signature]

在你的代币验证参数上,你说的是

string audienceId = ConfigurationManager.AppSettings["ClientID"];

您已经提到这个值是AccountTest,但是您的令牌具有值AudienceID。若要实现此功能,应用程序设置ClientID的值必须AudienceID。确保这两个值匹配-令牌中的aud声明值,以及您在配置中为AllowedAudiences设置的值。

您的验证设置必须与令牌负载中的设置完全相同,否则请求将被拒绝。您可以在令牌的验证中添加一些日志记录,以了解被拒绝的确切内容,看看这个链接

https://stackoverflow.com/a/52370255/1538039

最新更新