Обновление asp net mvc до ядра asp + угловой - PullRequest
0 голосов
/ 16 февраля 2019

Я обновляю старое приложение в asp net mvc до новой версии с asp core + angular 7. В старом приложении у нас была внешняя служба, вызывающая наш API, и отправляющая токен аутентификации в URL, потому что он не могне делайте иначе.

Я перехватываю его, чтобы вставить токен в заголовок следующим образом:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_PreSendRequestHeaders()
    {
        Response.Headers.Remove("X-Frame-Options");
        Response.AddHeader("X-Frame-Options", "AllowAll");
    }

    private void Application_BeginRequest(object sender, EventArgs e)
    {
        var header = HttpContext.Current.Request;
        var url = HttpContext.Current.Request.Url;
        var Params = HttpContext.Current.Request.Params;
        if (ReferenceEquals(null, HttpContext.Current.Request.Headers["Authorization"]))
        {
            var token = HttpContext.Current.Request.Params["access_token"];
            if (!String.IsNullOrEmpty(token))
            {
                HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + token);
            }
        }
    }

    protected void Application_Start()
    {
        //DashboardConfig.RegisterService(RouteTable.Routes);
        DevExtremeBundleConfig.RegisterBundles(BundleTable.Bundles);

        C_Interface_Meta.IntialiserBdd();
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        //GlobalConfiguration.Configure(WebApiConfig.Register);
        ASPxWebControl.CallbackError += Application_Error;

        BundleConfig.RegisterBundles(BundleTable.Bundles);
        DisableApplicationInsightsOnDebug();
    }

    /// <summary>
    /// Disables the application insights locally.
    /// </summary>
    [Conditional("DEBUG")]
    private static void DisableApplicationInsightsOnDebug()
    {
        TelemetryConfiguration.Active.DisableTelemetry = true;
    }

    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new PrettyPrintFilterAttribute());
    }

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = HttpContext.Current.Server.GetLastError();
        if (exception is HttpUnhandledException)
            exception = exception.InnerException;
        AddToLog(exception.Message, exception.StackTrace);
    }

    public static void AddToLog(string message, string stackTrace)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine(DateTime.Now.ToLocalTime().ToString());
        sb.AppendLine(message);
        sb.AppendLine();
        sb.AppendLine("Source File: " + HttpContext.Current.Request.RawUrl);
        sb.AppendLine();
        sb.AppendLine("Stack Trace: ");
        sb.AppendLine(stackTrace);
        for (int i = 0; i < 150; i++)
            sb.Append("-");
        sb.AppendLine();
        HttpContext.Current.Application["Log"] += sb.ToString();
        sb.AppendLine();
    }
}

Каков эквивалентный способ сделать это в приложении с угловым asp-ядром?После долгих поисков я ничего не нашел.

Ответы [ 2 ]

0 голосов
/ 18 февраля 2019
  1. Похоже, вы используете канал-носитель JWT и отправляете токен через строку запроса.Если это так, вы можете просто использовать обработчик событий OnMessageReceived для динамической установки токена:
public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options=> {
            options.TokenValidationParameters = new TokenValidationParameters{
                // ValidIssuer, ValidAudience, IssuerSigningKey , ...
            };
            options.Events = new JwtBearerEvents() {
                OnMessageReceived = async (context) =>{
                    // get bearer From Header/QueryString as you like
                    var bearer=context.HttpContext.Request.Query["access_token"].FirstOrDefault();
                    if(!String.IsNullOrEmpty(bearer)){
                        context.Token = bearer; // simply set the token
                    }
                },
            };
        });
    // other services ...
}
Или, как предлагает Razgort , вы можете зарегистрировать промежуточное ПО для установки токена.Будьте осторожны при заказе промежуточного программного обеспечения.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // register it before other middlewares that rely on this token
    app.Use(async(context,next)=>{
        var bearer = context.Request.Headers["Authorization"].FirstOrDefault();
        if(bearer==null){
            bearer=context.Request.Query["access_token"].FirstOrDefault();
            if(!String.IsNullOrEmpty(bearer)){
                context.Request.Headers.Add("Authorization", "Bearer " + bearer);
            }  
        }
        await next();
    });

    // other middlewares ...
    app.UseMvc(...)//
}
0 голосов
/ 16 февраля 2019

Я думаю, вы ищете угловых перехватчиков , которые в значительной степени делают то же самое.Вы хотите ввести токены примерно так:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Get the auth token from the service.
    const authToken = this.auth.getAuthorizationToken();

    // Clone the request and replace the original headers with
    // cloned headers, updated with the authorization.
    const authReq = req.clone({
      headers: req.headers.set('Authorization', authToken)
    });

    // send cloned request with header to the next handler.
    return next.handle(authReq);
  }
}
...