1

I am new to Token Based authentication. With reference to below links, I am trying to understand Token Based authentication.

If the user credentials are valid, I am getting the desired token.

[AcceptVerbs("POST")]
    [HttpPost]
    public string Post([FromBody]User user)
    {
        if(user.Username == "hello" && user.Password == "123")
        {
            var accessTokenResponse = GenerateLocalAccessTokenResponse(user.Username);

            return accessTokenResponse.ToString();
        }
        else
        {
            return "User invalid";
        }
    }

Generated token

TWC1Q2rrenZC2p78KPnS4JblcepCg6q3XuxqBQIh7L003npbb6hlBAOYGRN03OvY_O55GWFkZp7UfCmhCgH9Z4rBsjvIrp8gyCp4HmxpP4axVKk10NM9fiG2ctgZWeSbw1jNOor42Wk3yMufbs4xP0RlNuvdpLtBLir52g9rPF053kiJtYryNGzPsbibXHRrNoy0wOR2384uLAJ5pNE9s1DwYpdPKB9uOLSAGhDQOVU,

Now when I try to access the secured resources

    [Authorize]
    [HttpGet]
    // GET api/orders/5
    public string Get()
    {
        return "This is a secure resource";
    }

I get "Access Denied Error".

How do I use the token to access such resources.

Any help/suggestion highly appreciated. Thanks.

Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • Perhaps this answer may give you some more insight: http://stackoverflow.com/questions/38661090/token-based-authentication-in-web-api-without-any-user-interface/38670221#38670221 –  Feb 09 '17 at 17:16

1 Answers1

2

usually you would not implement the token endpoint as a POST method in your controller, but create a separate class (SimpleAuthorizationServerProvide) for it as shown in the above mentioned tutorial. If everything is setup correctly, you have to add an Authorization header to your http request

Authorization: Bearer TWC1Q2rrenZC2p78KP...

and get a reply with status code 200(OK)

To get a token send a request (for example with the tool fiddler) to your token endpoint e.g. if your service is running on localhost on port 52180 it looks like this:

POST http://localhost:52180/token 

grant_type=password&username=admin&password=123&client_id=abc

the grant_type part is the request body. When you post the above request, you'll reach the token endpoint. Just as Taiseer wrote in Step 12 of the tutorial.

When you put a breakpoint at GrantResourceOwnerCredentials that should be reached as soon as you sent the above request.

The usual flow is: - client requests a token from http://localhost:52180/token

  • server authenticates user credentials in GrantResourceOwnerCredentials and issues a token

  • client reads the access_token from the token response

  • client adds an authorization header containing the access_token to a request

    http://localhost:52180/api/orders
    
    Authorization: Bearer TWC1Q2rrenZC2p78KP...
    
  • server reads Authorization header and grants access (if token is valid)

  • server processes request, eg, the GET request

  • client receives status 200 and desired data

The api controller shown above looks ok The [Authorize] attribute is all you need in your controller. That adds an AuthorizationFilter to the http request pipeline, which handles the authorization for you when the client adds the above mentioned Authoriztion header to the request.

jps
  • 20,041
  • 15
  • 75
  • 79
  • Agreed. But how do I add Authorization token to Get order. Please suggest – Kgn-web Feb 09 '17 at 13:15
  • I Cross checked everything seems matching. – Kgn-web Feb 09 '17 at 14:29
  • you say, everything is as it in the tutorial, but it's not working? Where do you send your token request? Should be the path configured in TokenEndpointPath, eg. http:/localhost:/token. Not to public string Post([FromBody]User user), you don't need that. – jps Feb 09 '17 at 14:34
  • put a breakpoint at GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context), that's the method that should be hit when you send the token request – jps Feb 09 '17 at 14:43
  • I have adding the relevant code-snippets here. 1) https://codepaste.net/7uy6po 2)https://codepaste.net/8otsfg 3)https://codepaste.net/n286c7 – Kgn-web Feb 09 '17 at 14:54
  • Can you pleaseeeeeeee have a look at the above links once? Sincere Thanks – Kgn-web Feb 09 '17 at 14:54
  • I uploaded the complete solution for quick reference here. https://www.dropbox.com/s/94z61n7nbe2ango/Token_123.zip?dl=0 Please check – Kgn-web Feb 09 '17 at 14:57
  • I think the LoginController is the problem and not needed at all, because you bypass the OWIN middleware. Please read and reply to my last two comments above. – jps Feb 09 '17 at 15:06
  • I read your comment of redirecting to /token but how to do it? I am really going crazy please edit the code-snippet, because its been now 2 days I am setting up this. – Kgn-web Feb 09 '17 at 15:15
  • Great. I reached the same point I redirected to /ticket & GrantResourceOwnerCredentials() got hit while validating the credentials & got the token also. But still I got _Authorization has been denied for this request._ – Kgn-web Feb 09 '17 at 15:40
  • checked your code: OAuthBearerOptions in ConfigureOAuth is empty. Refer to step 9 in the tutorial, maybe that's the problem – jps Feb 09 '17 at 15:56
  • From wherever you are calling your resource, probably using HttpClient I presume, are you adding the auth token you received in the Authorization Header? Unless you do this your resource wont receive it and wont let you access any authorized endpoint. – Jinish Feb 10 '17 at 08:58
  • @jps, can you please share your inputs on this?? – Kgn-web Feb 17 '17 at 12:32