How to Authorize the service object for a specific user - c#

In google docs api Developer's guide at many places it says
// TODO: Authorize the service object for a specific user
Can any one please tell how to do that exactly..
especailly in my case where for authentication I'm sending a POST request to https://www.google.com/accounts/ClientLogin and then parsing Authentication token.

You can use the following code to have the library perform ClientLogin for you:
service.setUserCredentials(username, password);
For more details, check https://developers.google.com/google-apps/documents-list/#authorizing_requests_with_clientlogin

Related

Simple OAuth2 authentication - Request an access token

I have been struggling with this now for a while. So if someone could help me it would be great.
I am trying to get a simple access token from the TwitchTV API. I am referring to this link: https://dev.twitch.tv/docs/authentication/#getting-tokens
GET https://id.twitch.tv/oauth2/authorize
?client_id=<your client ID>
&redirect_uri=<your registered redirect URI>
&response_type=<type>
&scope =<space-separated list of scopes>
So thats where I begin to struggle already. How exactly do I make such requests in an ASP.NET MVC application? I see that I have an Startup.Auth.cs class where I can configure OAuth Authentications. But how does such authentication have to look like?
It then says in the documentation:
If the user authorizes your application, the user is sent to your
redirect URI, with an ID token and optionally an access token (if that
was requested):
https://<your registered redirect URI>#id_token=<an id
token>&access_token=<an access token>
Now how do I access this token? Can someone please give me a small Code example of how I should start with this API? I really dont have any experience with such technology. How do I have to configure my Startup.Auth.cs and how does my Action have to look like, that starts the authentication?
Please refer to the link above in your answer. Thank you!
You can create a redirect URI as callback URL.
when a user logged in in your app the callback will be triggered containing the Access Token and other information.
here is the sample snippet in PHP (https://yourhost.com/outhcallback.php)
<?php
$acccesstoken=$_REQUEST["access_token"];
$id_token=$_REQUEST["id_token"];
store_to_session(accesstoken);
?>
now you have the token. if this token you require in server-side store to the session and if require in client-side store to local storage.

In WCF/WIF how to merge up claims from two different client's custom sts's tokens

I'm trying to create something like: Client authenticates and gets token from custom STS1, next client authorizes with machine key and is issued token on custom STS2 and gets another token. With last token, client requests methods on RP service.
All services are hosted on IIS and are using active federation scenario.
Both STS's have endpoints with ws2007Federation and ws2007Http bindings, and RP use ws2007FederationBinding with STS2 as an issuer.
If I create channel with CreateChannelWithIssuedToken I can see only token from STS1 and can't get token from STS2.
So I decided to pass token from STS1 as ActAs RST's property on request to STS2 token. And that failed - cannot decrypt token.
How can I pass both tokens to STS2 and merge up claims in them?
Is it a bad idea - to send with RST just extracted claims from STS1 token?
Generally you will only want to utilize one token at each step. So if you need to merge up claims, you will want to do that at the claims transformation step of the second STS.
So the flow would be authenticate with STS1, then authenticate with STS2 with the token from STS1. At that point you would pass through the claims and transform to add additional claims as needed. Then the resulting Token would be ready to consume from the RP application.
I have actually started a blog series about a really similar scenario that we recently architected. Not to be overly self promoting, but it doesn't make me any money, so I'll post it in case it is helpful.
http://www.livingthearchitecture.com/mixing-sso-with-existing-technologies/
I would be glad to go more in depth, but depending on the specifics of your scenario, the specifics of the solution will change greatly. I think the above expresses the general approach you will want. Let me know if I can help any more.

How to make sure that all call to asp web api is authorized?

I'm building an saas application using asp web api 2 and asp identity. This api will be consumed by web, mobile and desktop applications. How do i make sure that all calls to my web api method is authorized? In web, we can ask user to login before going to certain page, but how bout mobile/desktop? Does user need to provide login and password on each call? Are there better solution for this? I've been searching and havent found any article about this. A sample or articles will be much appreciated.
Usually when using api's as a back-end you have to authenticate the user on every request.
(it actually also happens with other frameworks, such as mvc.net, but they keep track of the user using cookies which are send back and forth with every request)
I would suggest you use token based authentication (e.g. OAuth). In such a case you set the token in the header of the request. This token will be used to authenticate (and potentially authorize) the user.
If you need more info i can always explain it a bit more.
== Edit: Added Code sample ==
You could use a request handler to validate that the header of the request includes a valid token:
public class AuthorizationHeaderHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage pRequest, CancellationToken pCancellationToken)
    {
        IEnumerable<string> apiKeyHeaderValues = null; 
        if (!pRequest.Headers.TryGetValues("Authorization", out apiKeyHeaderValues)
|| !TokenRepo.IsVallidToken(apiKeyHeaderValues))
        {
var response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Content = new StringContent("{\"error\": \"invalid_token\"}")
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return Task.Factory.StartNew(() => response);
}
return base.SendAsync(pRequest, pCancellationToken);
}
}
All you have to do is keep which token is associated with which user, and make sure tokens have an expiration period. Once this is passed, it is also not valid anymore.
I hope this clarifies it a bit.
Again, if you have more questions, do not hesitate to ask.

Send on SSO custom informations

I'm reading up on SSO with WIF STS and so on. Im ended up in this tutorial http://chris.59north.com/post/2013/04/09/Building-a-simple-custom-STS-using-VS2012-ASPNET-MVC.aspx .
I wonder how I can recive some custom data which I would like to send from the custom STS?
The Relying Party in this tutorial has no code which is evalulating the response from the STS. If I'm correct this is done by the Idendity.Model.Service.
How can I send data from the IdP and recive them in the RP? Is it also possible to send some custom information on the SSO from RP to IdP?
As per the article: "The second method, the GetOutputClaimsIdentity(), is just as simple. All that is need here, is to create a new ClaimsIdentity and add the required claims. In this case, I only set the Name and NameIdentifier claims."
So you can set any claims you want using this method - normally you would get the attributes from a repository like AD.
The RP is built using WIF so you have a bunch of built-in methods. Refer: WIF Claims Programming Model

DotNetOpenAuth - How does client authentificate with id and secret?

I'm just finishing authorization and resource server for OAuth2, using DotNetOpenAuth 4.3.4. For testing, I created test client by implementing OAuth2Client.
Because I'm using DNOA for all the communication and request parsing, I'm not sure if I fully understand what is going on under the hood. But this knowledge is very important when I make documentation.
So, could you please explain to me, how client authentification works in DNOA? I use authorization code as grant_type and when I use my test client to exchange code for access_token, the DNOA somehow validate the client_secret and client_id. I downloaded source code for DNOA, but it not helped.
When I set breakpoint to Oauth2 controller(token method) and parse the request as HttpRequestMessage, i see the request contains "grant_type", "code" and "redirect_uri". But where are client_id and client_secret?
Also, can you tell me where I can find any usable documentation for DNOA? I need to create documentation, which will be valid and usable for all platforms, not just C#, which can use DNOA.
Related question:
I somewhere read, that we should not create authorization codes for unauthentificated clients, but this is exactly what DNOA does (since I receive authorization code even if secret is wrong). Is it ok?
Edit:
This is the request I'm trying to read. It is token request made by DNOA client. I can not see the client_id and client_secret under other parameters like "code", "redirect_uri" and "grant_type". I tought they have to be together. Maybe I'm missing something important from http requests and responses.
When I let DNOA to HandleTokenRequest(request) to continue, it is successfully authenticate the client application (fails when bad secret is set in DNOA client app config).
Edit 2
private readonly WebServerClient Client;
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
{
var authorization = Client.ProcessUserAuthorization();
if (authorization != null)
return authorization.AccessToken;
else
return null;
}
This is my implementation of QueryAccessToken. It is from some sample. I think I created this at the beginning and did not change it, because it worked.
Going rought DNOA source I found out it is method from OAuth 1. THis can be the problem. But the question is, why it works ok with right client cerdentials and not working with bad ones.
Final edit
Looks like DNOA client uses http Basic authorization (client_id and secret are in header). But I need the DNOA server to be able to grab these parameters from POST.
If anyone know how to set DNOA to support client_id and client_secret in POST parameters, it would be awesome!
Thank you
The authorization code grant requires two steps.
The first step is the browser redirecting to the identity provider and displaying the logon ui. The authorization code is returned to the browser by the identity provider and then, from the browser to the client application. This step doesn't involve client secret! This is because the end user can debug this part of the flow and she should not learn the value of the client secret.
Then, when the client application has the onetime authorization code, it concacts the token endpoint directly (server-to-server) to exchange the authorization code for authorization token. This is where client id and client secret are used to verify that only legitimate client applications exchange codes for tokens.
The idea behind this flow is to protect the end user from exposing her password to the client application and also protect the client application from exposing its client secret to the end user.
Also note that the authorization code grant flow is the most complicated one as it involves both username/password (provided by the end user) and clientid/client secret (provided by the client application). There are other flows which allow to get the authorization token in slightly different way, namely:
resource owner grant which involves sending username/password directly by end user to the token endpoint of the identity provider. This flow is suited for desktop/mobile/native apps where the logon ui can be customized (but it also can raise suspicions and users could proably refuse to use it)
client credentials flow which involves sending clientid/client secret by the client application to the idntity provider. There is no end user but only the client application authenticating in the identity provider.
More on flows here:
http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified
As for DNOA, I found it clean and understandable but the docs are lacking. Fortunately, examples are great and although barely documented, you can find almost everything there. Nonetheless, I was able to set up oauth2 identity provider and resource server in three days and support all four oauth2 flows. I am not going to dig deeply into details as this is not what your question is about, however, if you have DNOA specific questions, just ask.
Edit:: regarding your QueryAccessToken implementation, it seems that you are using the WebServerClient internally. In my code I just initialize its properties:
WebServerClient client = ...
client.ClientIdentifier = "client_id";
client.ClientCredentialApplicator =
ClientCredentialApplicator.PostParameter( "client_secret" );
With these two configured, both client_id and client_secret are sent to the token service with the client_secret passed in POST params.

Categories