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.
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.