By Robin


2014-11-05 11:01:12 8 Comments

First I'll sketch my project:

For my internship I need to add functionality to an existing system. A 3rd party client must be able to access data from AX Webservices once he is authorised by the user via OAuth2. I understand that I need to make a 'proxy web service' whereto the client can make its calls and that calls the AX services but I am a bit unsure about the OAuth2 part. Most tutorials and guides are about using ASP.NET's Identity for Facebook or Google-logins. I do not need that, I need to use existing credentials so I need to make my own OAuth2 service.

I find it hard to find tutorials, guides or explanations on this. I understand OAuth2 and what needs to be done, but I have never done such a thing before and find it hard to start. The closest thing to what I need that I found is this github repo link, but the solution does not build.

What I had in mind is making an ASP.NET MVC Website where clients (3rd parties) can register themselves and acquire their Client ID's. With ASP.NET API I wanted to create the API that take the required tokens and parameters, and then access the Dyn AX services.

Is this correct or am I entirely wrong? Any help or links regarding building your own oauth2 server/service would be nice.

4 comments

@Kai Hartmann 2015-04-01 14:05:32

I also struggled finding articles on how to just generate the token part. I never found one and wrote my own. So if it helps:

The things to do are:

  • Create a new web application
  • Install the following NuGet packages:
    • Microsoft.Owin
    • Microsoft.Owin.Host.SystemWeb
    • Microsoft.Owin.Security.OAuth
    • Microsoft.AspNet.Identity.Owin
  • Add a OWIN startup class

Then create a HTML and a JavaScript (index.js) file with these contents:

var loginData = 'grant_type=password&[email protected]&password=test123';

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        alert(xmlhttp.responseText);
    }
}
xmlhttp.open("POST", "/token", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(loginData);
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="index.js"></script>
</body>
</html>

The OWIN startup class should have this content:

using System;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using OAuth20;
using Owin;

[assembly: OwinStartup(typeof(Startup))]

namespace OAuth20
{
    public class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            OAuthOptions = new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath = new PathString("/token"),
                Provider = new OAuthAuthorizationServerProvider()
                {
                    OnValidateClientAuthentication = async (context) =>
                    {
                        context.Validated();
                    },
                    OnGrantResourceOwnerCredentials = async (context) =>
                    {
                        if (context.UserName == "[email protected]" && context.Password == "test123")
                        {
                            ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                            context.Validated(oAuthIdentity);
                        }
                    }
                },
                AllowInsecureHttp = true,
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1)
            };

            app.UseOAuthBearerTokens(OAuthOptions);
        }
    }
}

Run your project. The token should be displayed in the pop-up.

@pomber 2015-05-04 01:46:07

Nice, I like how minimalist your solution is. You should put the code here in your answer.

@Kai Hartmann 2015-05-04 06:37:16

Thanks, I tried to show the bare minimum required. I put the main steps into the answer itself.

@webworm 2016-06-27 21:11:42

I really like how you didn't bring in ASP Identity or Entity Framework. Most articles I have seen integrate these with the OAuth solution. Your solution focuses on OAuth and the issuance of the token. Very nice. Thanks also for posting on your blog.

@webworm 2016-06-28 14:39:19

@Kai - Where does Microsoft ASP.NET Identity Owin come into play? Are you using ASP.NET Identity for your user authentication? If not, is this NuGet package still needed?

@Kai Hartmann 2016-06-29 06:32:12

@webworm - The line app.UseOAuthBearerTokens(OAuthOptions); wont work without Microsoft ASP.NET Identity Owin. It does not recognize the method UseOAuthBearerTokens.

@Muhammed Afsal 2017-12-15 07:36:51

missing package : Microsoft.Owin.Host.SystemWeb, Microsoft ASP.NET Identity Owin

@vibs2006 2018-03-22 15:11:38

I just want to add one thing i.e if you too are getting Newtonsoft.Json invalid assembly error (in .NET 4.6 and above) then please update Newtonsoft.Json to version 11 or above.

@Ramachandran 2016-02-26 06:40:11

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

@Bartho Bernsmann 2016-05-06 14:59:28

The user is explicitally stating that he doesn't want to use Facebook or Gmail logins.

@Korayem 2015-11-25 07:36:25

I am researching the same thing and stumbled upon identityserver which implements OAuth and OpenID on top of ASP.NET. It integrates with ASP.NET identity and Membership Reboot with persistence support for Entity Framework.

So, to answer your question, check out their detailed document on how to setup an OAuth and OpenID server.

@Robin 2014-11-05 13:12:36

I will look at is but from the chapter names I think it is again not what I search as it focuses on Identity and facebook/ google login identity providers.

@MichaelS 2014-11-05 13:19:17

Only part 4 is about facebook and google. I implemented my own authentication controller based on these tutorials two months ago. And I was using my own user database too.

@Robin 2014-11-06 09:18:10

I have one more question, where do these tokens get stored? Does Identity take care of this entirely?

@Taiseer Joudeh 2014-11-15 22:47:16

@MichaelS thanks for referring to my blog posts, glad it was helpful for your project :)

@Joe.wang 2015-08-17 15:00:24

@MichaelS I doubted if the way of Token based authentication is security enough for the rest api . because if I can got the user's token in his browser. I think it can be achieved because token is stored in the request header Authentication . I can do everything I want like get / post/ put / delete.

@MichaelS 2015-08-20 08:43:10

@Joe.wang you are right. But it's more secure than cookies. Tokens are save agains CSRF, cookies are not.

@Joe.wang 2015-08-20 15:44:47

@MichaelS Thank your nice reply, In these days , I was stuck with finding a more security way than the way of token-based. the problem is the server hosting the restful api only can authenticate the client with the user credential . But that is all. nothing else. It doesn't care if the request is from the client who initiate the token request. right ? thanks.

@Joe.wang 2015-08-20 15:46:32

@MichaelS Or did I think about too much of it ? Hopefully can get some guide . Thanks .

@MichaelS 2015-08-21 07:35:04

@Joe.wang Unfortunately there is no 100% security. An attacker has to compromise your website with XSS to get the token. It's your turn to prevent that. And using TLS reduces the risk of a Man-in-the-middle attack. Do you see other risks?

@Joe.wang 2015-08-21 07:48:55

@MichaelS I mean , We should know what exactly component (code or application)should take the responsibility to take care of the every aspect of security. It seems token based authentication implemented with code is just take care of the security of business level. not the application level security like what you mentioned XSS and Man-in-the-middle it should take care. So Is it necessary to take all the issues into consideration when we still in the code level? My thought is we should consider the XSS , Man-in-middle issue in the deployment of our application. not in the code level. Thanks.

@Nisar 2015-09-07 11:55:07

I tried to login with google... but failed with Error: redirect_uri_mismatch. @TaiseerJoudeh your blog wasted my valuable time.. ;(

@Nisar 2015-09-07 12:02:27

Finally i am using Hello.js in NODE for asp.net

@Ryan Mann 2015-12-08 04:42:35

Every example I see is using Entity Framework. I want to know how to build that part too.

@Scott Fraley 2016-06-14 15:49:32

I'd love to see an example of using AD/LDAP for user login over (instead of) Identity. Also, some discussion about whether or not you should keep a store of active tokens on the server for expiration checking.

@webworm 2016-06-28 17:40:53

@MichaelS - How did you decouple OAuth from ASP.NET Identity? I am looking to do the same thing as you described ... using my own authentication.

Related Questions

Sponsored Content

36 Answered Questions

[SOLVED] How do you create a dropdownlist from an enum in ASP.NET MVC?

25 Answered Questions

[SOLVED] ASP.NET Web Site or ASP.NET Web Application?

9 Answered Questions

8 Answered Questions

[SOLVED] Compile Views in ASP.NET MVC

1 Answered Questions

OAuth authorize endpoint returns invalid_request in ASP NET Web API

35 Answered Questions

3 Answered Questions

[SOLVED] restful api authentication confusion with oauth2

2 Answered Questions

[SOLVED] Building a Web-API with Oauth2/OpenID connect

0 Answered Questions

Oauth2 with asp.net mvc and dynamics ax

Sponsored Content