Asp.net web api MVC5中基于令牌的授权实现
首先,让我用演员阵容来搭建舞台:Asp.net web api MVC5中基于令牌的授权实现,asp.net-web-api,oauth,Asp.net Web Api,Oauth,首先,让我用演员阵容来搭建舞台: mvc5应用程序 WebAPI 我需要实现基于令牌的安全性,以便从#1访问#2 我已经: 在#2中创建了一个启动类 互联网上随处可见的标准代码 这是MyServerProvider中的代码,也是#2中的代码 另一个类也在#3中提供令牌 到目前为止还不错 问题1。现在,当来自控制器的请求命中api或api 称为表单JavaScript,会发生什么? 问题2。哪种方法来自 有人打电话吗 第三季度。GrantResourceOwnerCredentials做什么
问候。你有什么进展吗。我也在尝试做同样的事情。Aaron发现了一些非常有用的信息。此外,我还创建了一个通用控制器,其中包含身份验证密钥生成和其他一些有用的功能。让我知道如果你想知道更多关于我做了什么的信息,我会寄给你的。不能把它作为对这篇文章的回答。
public void Configuration(IAppBuilder app)
{
// token generation
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
Provider = new MyServerProvider()
});
// token consumption
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
var httpConfiguration = new HttpConfiguration();
WebApiConfig.Register(new HttpConfiguration());
app.UseWebApi(httpConfiguration);
}
public class MyServerProvider: OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
await Task.FromResult(0);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
if (context.UserName == "one" && context.Password == "two")
{
var id = new ClaimsIdentity(context.Options.AuthenticationType);
id.AddClaim(new Claim("name", context.UserName));
id.AddClaim(new Claim("role", "user"));
context.Validated(id);
}
else
{
context.Rejected();
}
await Task.FromResult(0);
}
}
public class TokenProvider
{
public TokenResponse _tokenValue { get; set; }
public string _accessToken { get; set; }
public string GetToken(string tokenEndpoint, string userName, string password)
{
var client = new OAuth2Client(new Uri(tokenEndpoint));
var tokenResponse = client.RequestResourceOwnerPasswordAsync(userName, userName).Result;
_tokenValue = tokenResponse;
_accessToken = _tokenValue.AccessToken;
return _accessToken;
}
}