WebApi 2 Oauth2 Android client

点点圈 提交于 2020-01-15 07:24:48

问题


I want my android app to communicate with an Asp.net WebApi2 secured by Oauth2. All samples I've found only show how it is done for websites. I'm able to get an access token from the "/token" endpoint and I add this token to the http header in the Autorization attribute. However, I always get: "Authorization has been denied for this request."

My Startup Auth looks like:

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

    public static string PublicClientId { get; private set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);



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


        app.UseOAuthAuthorizationServer(OAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());


    }
}

My SimmpleApplicationOAuthProvider looks like:

 public class SimmpleApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public SimmpleApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
        {
            throw new ArgumentNullException("publicClientId");
        }

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }

    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

}


 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // Enforce HTTPS
        //config.Filters.Add(new LocalAccountsApp.Filters.RequireHttpsAttribute());
    }
}

I'm using Wireshark to analyse network traffic. This is my GET request:

GET /LocalAccountsApp/api/values HTTP/1.1
Content-Type: application/json; charset=utf-8
Authorization: Bearer SXFPTU5Sb2JVZWh6M3ZIcEtMRzdiMVVZd3hleTBWbHI2eFZtR2xFSFJQT...
User-Agent: Dalvik/2.1.0 (Linux; U; Android 5.0; LG-D855 Build/LRX21R.A1421650137)
Host: 192.168.1.7
Connection: Keep-Alive
Accept-Encoding: gzip

I placed a breakpoint in "GrantResourceOwnerCredentials" and it is hit both times (for /token and for /api/values). So where is my call rejected?


回答1:


OAuthBearerAuthenticationOptions is double if you remove one then have a look



来源:https://stackoverflow.com/questions/31891898/webapi-2-oauth2-android-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!