skip to Main Content

It’s been a few years since I made my own project and I am trying to wrap my head around the newer way of doing things.

Right now I want to have a website built in reactjs that will have asp.net web api as the backend.

This will allow me in the future to make mobile apps and whatever I want as everything would go though my web api.

One thing that confuses me is authentication and where it actually happens.

What part of my application is doing the authentication? Is it The Web Api or the website or both?

My website will only support ouath(google,facebook, Microsoft, etc) and have no traditional login screen.

A user would come to my webpage signup through their provider(say google) and then be allowed to restrict pages and start doing whatever they want to do(adding a course for example).

When they hit “create” it would make a request to my api, lookup the user in my database and see if they have permissions to create a new course. If so let them create it and save it. If not reject it.

If they have not signed in and try to hit the web api with say postman they should be rejected.

I know their is the OWIN for Web api but I don’t know if I need that and then something like OWIN for my react website.

I also don’t want to use the OWIN built in database tables as it seems to add alot more functionality then I want(I just want to authorize users).

As you can probably tell I am kinda confused. Hopefully someone can help me understand this all.

2

Answers


  1. Here is a complete tutorial of what you’re trying to do that may help you better understand how a web app interacts with a REST api in .NET

    https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-webapi-dotnet/

    Now you mentioned that you want to use Google, FB, MSFT, etc as identity providers, so I would recommend checking out the following new product Microsoft has just put into general availability. It makes it dead simple to integrate multiple IDP’s (identity providers) into your application. It also has complete code samples to help you get started.

    aka.ms/aadb2c

    Just for general learning I would highly recommend checking out this link that explains some theory and basics about tokens, OpenID Connect, and what’s inside an access token.

    http://connect2id.com/learn/openid-connect

    Login or Signup to reply.
  2. This is a bit complex so Im going to explain what you have to do.

    1) The first thing is use an OAuth provider. Microsoft is improving Identity Server.

    Identity server give to you Authorization and Authentication, based on openid.

    2) Identity server must be compile in another project and will create 18 tables in data base to control users and your clients.

    A client is the app with access, for example, Android app, angular app or resource server. Depending on you application you must to choose a work flow. In identity server you can choose between 5 of them

    https://github.com/IdentityServer

    Identity server 3 is for asp.net mvc 4.5+ and Identity server 4 is for ASP.NET Core 1

    I guess your server will be a resource server so if you will save user accounts you must to do 2 sign up, a sign up in identity server and then in your resource server.

    To configure you resource server and understand the communication between both, you must to configure your StartUp.cs with something like this:

     public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // Any connection or hub wire up and configuration should go here
                var clientId = (string)ConfigurationManager.AppSettings["oauth2.clientid"];
                var authority = (string)ConfigurationManager.AppSettings["oauth2.authority"];
    
                app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = authority,
                    ValidationMode = ValidationMode.ValidationEndpoint,
                    RequiredScopes = new[] { clientId },
                });
    
                app.UseResourceAuthorization(new AuthorizationManager());
    
            }
    
    
            private void ConfigureOAuth()
            {
                var formatters = GlobalConfiguration.Configuration.Formatters;
                var jsonFormatter = formatters.JsonFormatter;
                var settings = jsonFormatter.SerializerSettings;
                settings.Formatting = Formatting.Indented;
            }
        }
    

    When you provide a token and you call the service by REST you will send in your http header the next thing:

    header.add(“Authorization”, “TypeToken Token”);

    The most used type token is Bearer

    This token is provided by identity server when you do a loggin with the identity.client class in C# giving to you an awesome tool to do the hardest part.

    Configure client:

      private TokenClient GetTokenClient()
            {
                var clientId = (string)ConfigurationManager.AppSettings["oauth2.clientid"];
                var clientSecret = (string)ConfigurationManager.AppSettings["oauth2.client-secret"];
                var tokenEndPoint = (string)ConfigurationManager.AppSettings["openid.endpoints.token"];
    
                var client = new TokenClient(
                    tokenEndPoint,
                    clientId,
                   clientSecret
                );
    
                return client;
            }
    

    Getting Token:

    Route("LoginOAUth")]
            [HttpPost]
            public async Task<TokenResponse> LoginOAUth(LoginViewModel credentials)
            {
                var result = await GetTokenClient().RequestResourceOwnerPasswordAsync(credentials.Correo, credentials.Password,
                                "offline_access AppNameExample-IdentityClient-morgan");
    
                return result;
            }
    
      public class LoginModel
        {
            public string Email { get; set; }
            public string Password { get; set; }
        }
    

    This token must be stored by the client, and also each time you do a call to the end points your resource server will do a internal call to Identity server to check if your token is valid or not, and if your token is expired or not.

    In the token you get 2 kind information scopes and claims, those scopes and claim say to you the “rights on the resources” and the user data information like id, email, name, etc. To read those attributes here is an example of a custom AuthorizationAttribute:

      public class AuthorizationManager : ResourceAuthorizationManager
        {
    
            public override Task<bool> CheckAccessAsync(ResourceAuthorizationContext context)
            {
    
                switch (context.Resource.First().Value)
                {
                    case "claims":
                        return AuthorizeValues(context);
                    default:
                        return Nok();
                }
            }
    
            Task<bool> AuthorizeValues(ResourceAuthorizationContext context)
            {
                switch (context.Action.First().Value)
                {
                    case "read":
                        return Eval(context.Principal.HasClaim("role", "api-read"));
                    default:
                        return Nok();
                }
            }
    
        }
    

    Is really complex and I spended 1 months studuying the OAuth 2.0 protocol and how works identity server. I wish you the best of lucks

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search