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);
}
}
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;
}
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;
}
Actually, OWIN handle almost everything for you. If you use ASP.NET API v2 Server to receives requests. You just have to pass your token in the your http requests in the right format.
1. Send http request
There are 2 ways to pass your token :
2. Authenticate your request
You can use (ClaimsPrincipal)Thread.CurrentPrincipal.Identity.IsAuthenticated
to check if the requested token
is valid
3. Authorize your request
You can use [Authorize]
attribute or You can write your own AuthorizeAttribute
If you implement your own Attribute , you can do more interesting things: connect to Database to do complex authorization.
I think, This is a good document to start with OAUTH2 in ASP.NET Web Api: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/