14
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;
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
b_in_U
  • 640
  • 2
  • 7
  • 22
  • 1
    Just talking out of my hat here but if the bearer token is passed back in the Authorization header then a simple call to User.Identity.IsAuthenticated should tell you whether the token is valid or not. – Mark Aug 02 '14 at 18:29
  • 1
    @Mark - could be, however, what happens when the method is called via an Ajax request and there is no User.Identity attached to the request? – Catchops Oct 02 '14 at 16:24
  • @Catchops You have to pass your token in the request Authorization header (e.g. Authorization: Bearer YOUR_TOKEN) when you make the AJAX request. – Mark Oct 03 '14 at 01:11
  • 1
    Yes...Got it. I was originally mixed up in how I was implementing my authorization (OWIN vs ASP.NET v2 OOTB). I am now putting the OWIN generated token into the the authorization header and reading it via a ClaimsIdentity property. After a while of wandering in the wilderness, the light finally clicked on! – Catchops Oct 10 '14 at 14:25

1 Answers1

4

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/

Dennis Meissel
  • 1,825
  • 1
  • 21
  • 33
Hung Doan
  • 1,167
  • 12
  • 19
  • Hi, what if we send the token in a cookie, then how do we set the Authorization Header? Do we do it in the `AuthorizeAttribute` or is it too later by then? – DevEng Feb 20 '18 at 20:40