Аутентификация OWIN и Bearer Token в службе Windows - PullRequest
0 голосов
/ 12 октября 2018

У меня есть автономный сервер аутентификации и несколько серверов ресурсов, которые совместно используют ключ компьютера.Запуск на серверах ресурсов выглядит примерно так:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);

        app.UseWebApi(config);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

Я создал службу Windows и у меня есть этот класс запуска

class Startup
{
    //Type valuesControllerType = typeof(OWINTest.API.ValuesController);

    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);

        //tried it with the listener and without

        HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];
        listener.AuthenticationSchemes =    //AuthenticationSchemes.IntegratedWindowsAuthentication |
                                            AuthenticationSchemes.Anonymous;
        HttpConfiguration config = new HttpConfiguration();

        //tried it with this and without
        config.SuppressDefaultHostAuthentication();

        //tried it with this and without
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        config.MapHttpAttributeRoutes();
        app.UseWebApi(config);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
        {
            Provider = new HeaderTokenProvider(),
            AccessTokenProvider = new AuthenticationTokenProvider(),
        });
    }
}

Но часть аутентификации не работает.Мне отказывают в авторизации, когда мои контроллеры украшены [Authorize]

{"Message": "Авторизация была отклонена для этого запроса".}

Теперь я не был уверен, что промежуточное ПО правильно подбирает ключ машины.Итак, я реализовал AccessTokenProvider, как показано ниже

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
    Provider = new HeaderTokenProvider(),
    AccessTokenProvider = new AuthenticationTokenProvider(),
});

 public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
    var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
    AuthenticationTicket ticket = secureDataFormat.Unprotect(context.Token.Replace("Bearer ", ""));


    //context.DeserializeTicket(context.Token); //this does not seem to work
    context.SetTicket(ticket);

    //when I print the line below I get true and my username
    ticket.Identity.IsAuthenticated + " identity IS  " + ticket.Identity.Name

    //so the ticket has the correct info and I can manually un-encrypt it and get the correct properties.
}

Итак, как мне действовать отсюда, принцип windows не установлен в конвейере ... могу ли я установить его вручную.

Я пробовал такие вещи:

context.OwinContext.Authentication.User = new System.Security.Claims.ClaimsPrincipal();
context.OwinContext.Authentication.User.AddIdentity(ticket.Identity);
//

//var principal = new ClaimsPrincipal(ticket.Identity);
//context.Request.User = principal;
//WindowsPrincipal user = principal as WindowsPrincipal;
//context.OwinContext.Authentication.User = principal;

Любая помощь приветствуется.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...