C# 如何使用JWT令牌ASP.NET MVC
对不起,这是一条很长的消息,但要说清楚(我希望) 我遵循这一点设置了AuthorizationServerProvider,并允许任何拥有JWT令牌的人在我的代码中调用某个API。但是,当我试图调用MVC项目的任何控制器或API控制器方法时,我会收到一条未经授权的消息 以下是我的ValidateClientAuthentication和GrantResourceOwnerCredentials方法:C# 如何使用JWT令牌ASP.NET MVC,c#,asp.net,asp.net-mvc,asp.net-web-api,jwt,C#,Asp.net,Asp.net Mvc,Asp.net Web Api,Jwt,对不起,这是一条很长的消息,但要说清楚(我希望) 我遵循这一点设置了AuthorizationServerProvider,并允许任何拥有JWT令牌的人在我的代码中调用某个API。但是,当我试图调用MVC项目的任何控制器或API控制器方法时,我会收到一条未经授权的消息 以下是我的ValidateClientAuthentication和GrantResourceOwnerCredentials方法: 使用Microsoft.AspNet.Identity.Owin; 使用Microsoft
使用Microsoft.AspNet.Identity.Owin;
使用Microsoft.Owin.Security.OAuth;
使用System.Security.Claims;
使用System.Threading.Tasks;
使用MyProject.Models;
使用Microsoft.Owin.Security;
公共类AuthorizationServerProvider:OAuthAuthorizationServerProvider
{
公共重写异步任务ValidateClientAuthentication(OAuthValidateClientAuthenticationContext)
{
context.Validated();
}
公共重写异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentials上下文)
{
var allowedOrigin=“*”;
//
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(“无效的授权”,“用户名或密码不正确”);
返回;
}
ClaimsIdentity oAuthIdentity=await user.GenerateUserIdentityAsync(userManager,“JWT”);//也许这就是问题所在
//oAuthIdentity.AddClaim(新声明(ClaimTypes.Role,“User”);
//oAuthIdentity.AddClaim(新声明(ClaimTypes.Authentication,“audenceId”);
var票证=新的身份验证票证(oAuthIdentity,null);
上下文。已验证(票证);
}
}
在我的Startup.Auth.cs中,我使用了两种方法让带有[Authorize]
属性的Api控制器可以通过JWT进行验证。
下面是部分类:
使用Microsoft.AspNet.Identity.EntityFramework;
使用Microsoft.AspNet.Identity.Owin;
使用Microsoft.IdentityModel.Tokens;
使用Microsoft.Owin.Security.OAuth;
使用制度;
使用System.IdentityModel.Tokens.Jwt;
使用System.Security.Claims;
使用System.Threading.Tasks;
公共部分类启动
{
public void ConfigureAuth(IAppBuilder应用程序)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
配置OAuthTokenGeneration(应用程序);
配置OAuthTokenConsumption(应用程序);
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Account/Login”),
Provider=新CookieAuthenticationProvider
{
OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(10),
regenerateIdentity:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器))
}
});
/*其他类型的身份验证*/
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));
app.useTowFactoryMemberBrowserCookie(DefaultAuthenticationTypes.TwoFactoryRememberBrowserCookie);
}
私有void配置OAuthTokenGeneration(IAppBuilder应用程序)
{
OAuthAuthorizationServerOptions OAuthServerOptions=新的OAuthAuthorizationServerOptions()
{
//仅适用于开发环境(在生产环境中应为AllowInsecureHttp=false)
AllowInsecureHttp=true,
TokenEndpointPath=新路径字符串(“/oauth/token”),
AccessTokenExpireTimeSpan=TimeSpan.FromMinutes(3),
Provider=新的AuthorizationServerProvider(),
AccessTokenFormat=新的CustomJwtFormat(“https://localhost:44391")
};
使用OAuthAuthorizationServer(OAuthServerOptions);
}
私有void配置OAuthTokenConsumption(IAppBuilder应用程序)
{
var发行人=”https://localhost:44391";
string audienceId=ConfigurationManager.AppSettings[“audienceId”];//其值为“audienceId”
byte[]AudienceCret=TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings[“SecretKey”]);
字符串[]AllowedAud=new[]{audenceId};
//具有[Authorize]属性的Api控制器将使用JWT进行验证
app.UseJwtBearerAuthentication(
新的JWTBeareAuthenticationOptions
{
AuthenticationMode=AuthenticationMode.Active,
允许的观众=允许的观众,
//IssuerSecurityTokenProviders=新的IIssuerSecurityTokenProvider[],
IssuerSecurityKeyProviders=新的IIssuerSecurityKeyProvider[]
{
新的SymmetriceIsuerSecurityKeyProvider(发行人、AudienceCret)
}
}) ;
}
}
我在ConfigureAuth(IAppBuilder应用程序)中调用这些方法。
所以在这一切之后,我不明白为什么我不能被授权。有什么想法吗
如果这有帮助:
我使用的是Microsoft.Owin:Security.Jwt v4.1.1
我使用此方法生成令牌:
使用Microsoft.Owin.Security;
使用制度;
使用系统配置;
使用System.IdentityModel.Tokens.Jwt;
使用System.Security.Claims;
使用Microsoft.IdentityModel.Tokens;
公共类CustomJwtFormat:ISecureDataFormat
{
私有只读字符串_issuer=string.Empty;
公共自定义JWTFormat(字符串颁发者)
{
_发行人=发行人;
}
/*这将生成JWT*/
公共图书馆
{
"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"];