2

I have a MVC web app and then added Web api in the same project. I saw many examples and everyone explaining it using an anonymous API controller. But if my REST API has a [Authorize] attribute then how a native app (Android) will be able to access it? Is there any way to enable bearer token in the MVC Web App?

Current login/signup methods that I have all are for the Web app and not for the Web Api. Do I have to copy the login/signup methods that comes in the Web API default template?

Thanks for looking into it and appreciate your help.

4
  • Did you try it? Authentication works with cookies, that get sent on both requests made by the user and by the browser. Commented Feb 19, 2015 at 7:59
  • By java script client you mean a script hosted in a page that requires authentication ? So you want your API to recognize the authentication cookie set after authenticating to see the MVC page ? Commented Feb 19, 2015 at 8:05
  • Sorry my bad I want to know how a native app (Android) will be able to access the restricted web api controller Commented Feb 19, 2015 at 8:24
  • @CodeCaster - I saw everyone asking to use token while accessing REST APIs from native app. But as my current authentication is cookie based (mvc web app template), so not sure whether native app will support cookie based authentication or not. Sorry never worked in Android app. Thanks again. Commented Feb 19, 2015 at 8:30

2 Answers 2

2

With that you can use cookie Authentication and Bearer Token Authentication

public static OAuthBearerAuthenticationOptions OAuthServerOptions { get; private set; }       

    public void ConfigureOAuth(IAppBuilder app)
    {

        // Configure the db context, the user manager, and the login manager to use a single instance per request.
        app.CreatePerOwinContext(ApplicationDbContext.Create);           

        // Token Generation
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
            Provider = new AuthorizationServerProvider()
        };
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        app.UseOAuthAuthorizationServer(OAuthServerOptions);


        // Enable application to use a cookie to store information for the logged-on user     
        // and to use a cookie to temporarily store information about a user who logs in with the third-party logon provider.
        // Configure the login cookie.
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            CookieSecure = CookieSecureOption.SameAsRequest,                     
            ExpireTimeSpan = new TimeSpan(0, 20, 0),
            SlidingExpiration = true,
            Provider = new CookieAuthenticationProvider
            {

                // Enables the application to check the security stamp when the user logs on.   
                // This is a security feature that is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(20),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when checking the second level in the two-step authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));


        // Enables the application to store the second login verification level (for example, phone or email).
        // If you enable this option, your second verification step is saved on the device from which you logged on during the login process.
        // This is similar to the RememberMe option when logging in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);



    }      

In your WebAPI.config you have to write this

config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter("Bearer"));  

Here is a nice article about Bearer and Cookie Authentication

Authentication

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

2 Comments

@maddin- thanks for your help. I got three errors for missing binaries - 'SuppressDefaultHostAuthentication', 'HostAuthenticationFilter' and for 'AuthorizationServerProvider'. First two got fixed after adding this package 'ASP.Net Web API 2.2 OWIN'. But still the last one is there. Can you please tell me what package I'm missing?
You have to install Microsoft.Owin.Security.OAuth
1

In case someone looking in this question, please follow the steps mentioned here. This worked for me. Now web api and mvc web app are in same project and I can access web api using token.

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

Comments

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.