b_i*_*n_U 14 c# authorization access-token oauth-2.0 asp.net-web-api
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
bool isvalidUser = AuthenticateUser(context.UserName, context.Password);// validate my user&password
if (!isvalidUser)
{
context.Rejected();
return;
}
// create identity
var id = new ClaimsIdentity(context.Options.AuthenticationType);
id.AddClaim(new Claim("sub", context.UserName));
id.AddClaim(new Claim("role", "user"));
// create metadata to pass on to refresh token provider
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{ "as:client_id", context.ClientId }
});
var ticket = new AuthenticationTicket(id, props);
context.Validated(ticket);
}
}
Run Code Online (Sandbox Code Playgroud)
Login time I'm using this SimpleAuthorizationServerProvider(in Web Api) I can get and send access token to client. Again Login user need to access other Pages, How can I validate my custom Oauth2 access token in server side (in Web Api)
From Client side I'm generation token like this
private static TokenResponse GetToken()
{
var client = new OAuth2Client(new Uri("http://localhost:1142/token"), "client1", "secret");
var response = client.RequestResourceOwnerPasswordAsync(uid, pwd).Result;
Console.WriteLine(response.AccessToken);
return response;
}
Run Code Online (Sandbox Code Playgroud)
And call particular web api after authentication like this
private static void CallProfile(string token)
{
var client = new HttpClient();
client.SetBearerToken(token);
var response = client.GetStringAsync(new Uri("http://localhost:1142/api/Profile?id=1")).Result;
}
Run Code Online (Sandbox Code Playgroud)
事实上,OWIN几乎可以为您处理所有事情。如果您使用 ASP.NET API v2 Server 来接收请求。您只需以正确的格式在 http 请求中传递令牌即可。
1.发送http请求
有两种方法可以传递您的令牌:
2. 验证您的请求
您可以用来 (ClaimsPrincipal)Thread.CurrentPrincipal.Identity.IsAuthenticated检查是否requested token有效
3. 授权您的请求
您可以使用[Authorize]属性或者您可以编写自己的属性AuthorizeAttribute
如果你实现自己的 Attribute ,你可以做更多有趣的事情:连接到数据库进行复杂的授权。
我认为,这是在 ASP.NET Web Api 中开始使用 OAUTH2 的一个很好的文档: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin -asp-net-身份/
| 归档时间: |
|
| 查看次数: |
16878 次 |
| 最近记录: |