0

I already implemented webapi without authentication and it is working perfectly. but now I want to implement the authorization for the WebAPI.

I tried to create new project with "Individual User Accounts" and add my controllerFile to controller folder and then add <Authorize> in controllerFile but it works only for this default database.

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-IRAApi-20150211114242.mdf;Initial Catalog=aspnet-IRAApi-20150211114242;Integrated Security=True"
          providerName="System.Data.SqlClient" />

I just want to set my own database for the same functionality. My Database have same table's name as default database have.

Or is there any other way to do that if person is logged in then generate access token and then person is able to access the web api otherwise not.

I am working on visual studio 2013 and dotnet framework 4.5.

1 Answer 1

1

I would create a new project using the "Web API" template (not Empty and not MVC with Web API checked). If you select "Individual User Accounts" it will generate the infrastructure for token-based authentication. It will also automatically generate the help API, so you can navigate to:

http://localhost:[port]/help/

To see the documentation. The template scaffolds a password-type grant, so you can post new users to /api/Account/Register and then log them in with a post to /Token using grand type "password" and the user's name and password.

To see this in action look at this video: https://channel9.msdn.com/Series/Web-API-Design/05

The source code is available on GitHub: https://github.com/MicrosoftLearning/WebAPIDesign/tree/master/05%20-%20Security/05cTokenBasedAuthentication

The main code you're probably looking for is under App_Start/Startup.Auth.cs:

OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };

The entire module covers security front-to-back.

Sign up to request clarification or add additional context in comments.

1 Comment

as i mentioned in a question that i have already tried "Individual User Accounts" but that only works for default database which is automatically generate with the project and i want to use my own database instead of default database. by changing just connection string will not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.