Как проверить сообщение - PullRequest
       21

Как проверить сообщение

0 голосов
/ 22 января 2020

Это dotnet asp core 3 react приложение.

My startup.cs выглядит следующим образом:

public class JwtAuthentication
{
    public string SecurityKey { get; set; }
    public string ValidIssuer { get; set; }
    public string ValidAudience { get; set; }

    public SymmetricSecurityKey SymmetricSecurityKey => new SymmetricSecurityKey(Convert.FromBase64String(SecurityKey));
    public SigningCredentials SigningCredentials => new SigningCredentials(SymmetricSecurityKey, SecurityAlgorithms.HmacSha256);
}

public class ConfigureJwtBearerOptions : IPostConfigureOptions<JwtBearerOptions>
{
    private readonly IOptions<JwtAuthentication> _jwtAuthentication;

    public ConfigureJwtBearerOptions(IOptions<JwtAuthentication> jwtAuthentication)
    {
        _jwtAuthentication = jwtAuthentication ?? throw new System.ArgumentNullException(nameof(jwtAuthentication));
    }

    public void PostConfigure(string name, JwtBearerOptions options)
    {
        var jwtAuthentication = _jwtAuthentication.Value;

        options.ClaimsIssuer = jwtAuthentication.ValidIssuer;
        options.IncludeErrorDetails = true;
        options.RequireHttpsMetadata = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateActor = true,
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = jwtAuthentication.ValidIssuer,
            ValidAudience = jwtAuthentication.ValidAudience,
            IssuerSigningKey = jwtAuthentication.SymmetricSecurityKey,
            NameClaimType = ClaimTypes.NameIdentifier
        };
    }
}

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        var connectionStringOs =
           "Server=xx.xx.xx.xxIntegrated Security=false;Trusted_Connection=false;Database=Options;User Id=xx;Password=xx;Connection Timeout=60";
        var connectionStringDs =
           "Server=xx.xx.xx.x;Integrated Security=false;Trusted_Connection=false;Database=DY;User Id=xx;Password=xx";

        services.AddDbContext<OptionsDbContext>(o =>
               o.UseSqlServer(connectionStringOs));

        services.AddDbContext<DYDbContext>(o =>
               o.UseSqlServer(connectionStringDs));


        //services.AddRazorPages();
        services.AddMvc();
        services.AddMvc(option => option.EnableEndpointRouting = false);  

        services.Configure<JwtAuthentication>(Configuration.GetSection("JwtAuthentication"));
        // I use PostConfigureOptions to be able to use dependency injection for the configuration
        // For simple needs, you can set the configuration directly in AddJwtBearer()
        services.AddSingleton<IPostConfigureOptions<JwtBearerOptions>, ConfigureJwtBearerOptions>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                                                              .AddJwtBearer();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    //public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    public void Configure(IApplicationBuilder app,
           //IHostingEnvironment env,
           IHostEnvironment env,
           OptionsDbContext optionsDbContext)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            //app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            //{
            //    HotModuleReplacement = true
            //});
        }

        app.UseStaticFiles();

        /// Endpoint aware middleware. 
        // Middleware can use metadata from the matched endpoint.
        //app.UseCookiePolicy();
        app.UseAuthorization();
        app.UseAuthentication();


        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default", 
                template: "{controller=Home}/{action=Index}/{id:int?}");

        });
    }
}

Я добавляю контроллер, чтобы получить token:

using System;
using System.Linq;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using System.ComponentModel.DataAnnotations;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication.JwtBearer;

using OptionsAPI.Entities;

[Route("user/[controller]")]
public class UserController : Controller
{
    private readonly IOptions<JwtAuthentication> _jwtAuthentication;

    public UserController(IOptions<JwtAuthentication> jwtAuthentication)
    {
        _jwtAuthentication = jwtAuthentication ?? throw new ArgumentNullException(nameof(jwtAuthentication));
    }

    [HttpPost]
    [AllowAnonymous]
    public IActionResult GenerateToken([FromBody]GenerateTokenModel model)
    {
        // TODO use your actual logic to validate a user
        if (model.Password != "654321")
            return BadRequest("Username or password is invalid");

        var token = new JwtSecurityToken(
            issuer: _jwtAuthentication.Value.ValidIssuer,
            audience: _jwtAuthentication.Value.ValidAudience,
            claims: new[]
            {
                // You can add more claims if you want
                new Claim(JwtRegisteredClaimNames.Sub, model.Username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            },
            expires: DateTime.UtcNow.AddDays(30),
            notBefore: DateTime.UtcNow,
            signingCredentials: _jwtAuthentication.Value.SigningCredentials);

        return Ok(new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token)
        });
    }

    public class GenerateTokenModel
    {
        [Required]
        public string Username { get; set; }
        [Required]
        public string Password { get; set; }
    }
}

У меня есть файл html для проверки:

<script type="text/javascript"> 
const response = await fetch("http://www.awebsite.com/user/generatetoken", {
        method: "POST",
        body: JSON.stringify({
            username: "foo@bar",
            password: "654321"
        }),
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
    });
const json = await response.json();
const token = json.token;
console.log(token);

</script>

Когда я загружаю это в браузер, ничего не происходит. Не знаете, как проверить вызов контроллера, который передает токен для использования API, или если в этом коде отсутствует что-то для t ie всего этого вместе?

1 Ответ

0 голосов
/ 22 января 2020

Прежде всего, используйте инструменты разработчика Fiddler или браузера для отслеживания запроса и проверки сообщения об ошибке. Но имейте в виду, что для вызова функции с использованием ключевого слова await она должна быть внутри функции asyn c:

async function postData(url = '', data = {}) {

    const response = await fetch(url, {
        method: 'POST', 
        headers: {
        'Content-Type': 'application/json',
        "Accept": "application/json"
        },
        body: JSON.stringify(data) 
    });
    return await response.json(); 
}

postData('http://www.awebsite.com/user/generatetoken', {
        username: "foo@bar",
        password: "654321"
    })
.then((data) => {
    console.log(data.token); 
});

или с использованием:

fetch('http://www.awebsite.com/user/generatetoken', {
        method: "POST",
        body: JSON.stringify({
            username: "foo@bar",
            password: "654321"
        }),
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
})
.then(response => response.json()).then(data => {
       alert(data.token)
});

Будьте осторожны других потенциальных проблем, таких как CORS.

...