我有Asp.Net Web App作为授权服务器使用url:http://localhost:46947/并在其中创建CustomJwtFormat.cs:
public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
private readonly string _issuer = string.Empty;
public CustomJwtFormat(string issuer)
{
_issuer = issuer;
}
public string Protect(AuthenticationTicket data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
string audienceId = "d7f620e1-766b-4eda-b235-18bff11ceec8";
string secKeyPlain = "7ca47d80-06b1-4c14-94c1-e3d9da83ef2a";
string secKeyBase64 = Base64Encode(secKeyPlain);
var secKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.Default.GetBytes(secKeyPlain));
var signingKey = new Microsoft.IdentityModel.Tokens.SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
var issued = data.Properties.IssuedUtc;
var expires = data.Properties.ExpiresUtc;
var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);
return jwt;
}
public AuthenticationTicket Unprotect(string protectedText)
{
throw new NotImplementedException();
}
private static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
}
在Startup ConfigureAuth中添加CustomJwt:
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 http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(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);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true,
AccessTokenFormat = new CustomJwtFormat("http://localhost:46947")
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
}
我还有另一个带有URL的WebApp:http://localhost:43678/,它有一些我想要保护的资源。在他的Startup.cs中,我在WebApi midlleware之前调用了下面的方法:
public void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = "http://localhost:46947";
string audienceId = "d7f620e1-766b-4eda-b235-18bff11ceec8";
string audienceSecret = "7ca47d80-06b1-4c14-94c1-e3d9da83ef2a";
string audienceSecretBase64 = Base64Encode(audienceSecret);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecretBase64)
}
});
}
不,我可以通过调用此端点获得Jwt访问令牌:
使用Post动词,用户名,密码和grant_type作为密码当我接受accessstoken并尝试从资源应用程序获取任何受保护的资源时,如下所示: GET:http://localhost:43678/api/books
授权:Bearer x.y.z
每次回归:
"Message": "Authorization has been denied for this request."
我想提一下,我试图通过jwt debugger验证jwt令牌,但每次它都返回无效,即使我放了我的密钥