Можно ли использовать API идентификации dotnet angular spa с другой платформой, такой как мобильное приложение?

#angular #api #asp.net-core #asp.net-identity

#angular #API #asp.net-core #asp.net-identity

Вопрос:

Использовал dotnet new angular -o SPA -au Individual и получил весь проект Angular с использованием dotnet core Indentity framework, я вижу в журналах конечные точки, к которым я прикасаюсь при просмотре тестового приложения.

Я бы с удовольствием использовал это, например, с помощью Postman, чтобы сопоставить все это и использовать в своем мобильном приложении, чтобы помочь пользователям проходить аутентификацию, используя одну и ту же учетную запись для обеих платформ, а также их данные.

Я создал API с использованием ядра Identity 3.1, но я действительно хочу перейти с этого проекта без какого-либо графического интерфейса на этот красивый каркасный проект, который просто работает из коробки.

Пожалуйста, дайте мне знать, как я могу коснуться этих конечных точек

 info: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      {
        "SubjectId": "anonymous",
        "RequestedScopes": "",
        "PromptMode": "",
        "Raw": {}
        "Endpoint": "Authorize",
        "Scopes": "",
        "Error": "invalid_request",
        "ErrorDescription": "Invalid client_id",
        "Category": "Token",
        "Name": "Token Issued Failure",
        "EventType": "Failure",
        "Id": 2001,
        "ActivityId": "0HM6K6NTM0G45:00000002",
        "TimeStamp": "2021-02-18T17:53:32Z",
        "ProcessId": 8248,
        "LocalIpAddress": "::1:5001",
        "RemoteIpAddress": "::1"
      }
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeCallbackEndpoint for /connect/authorize/callback
info: IdentityServer4.Events.DefaultEventService[0]
      {
        "ClientId": "SPA",
        "ClientName": "SPA",
        "RedirectUri": "https://localhost:5001/authentication/login-callback",
        "Endpoint": "Authorize",
        "SubjectId": "02397ed4-5c90-4652-a1f1-99482bbeceee",
        "Scopes": "SPAAPI openid profile",
        "GrantType": "authorization_code",
        "Tokens": [
          {
            "TokenType": "code",
            "TokenValue": "****09F7"
          }
        ],
        "Category": "Token",
        "Name": "Token Issued Success",
        "EventType": "Success",
        "Id": 2000,
        "ActivityId": "0HM6K6NTM0G47:00000011",
        "TimeStamp": "2021-02-18T18:07:15Z",
        "ProcessId": 8248,
        "LocalIpAddress": "127.0.0.1:5001",
        "RemoteIpAddress": "127.0.0.1"
      }
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryEndpoint for /.well-known/openid-configuration
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token
 

При попытке использовать эту конечную точку с postman, используя требуемые параметры и urlencoding, это не сработает

 info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
fail: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      client_id is missing or too long
{
        "SubjectId": "anonymous",
        "RequestedScopes": "",
        "PromptMode": "",
        "Raw": {}
      }
fail: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Request validation failed
 

Это мой стартап

 using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.EntityFrameworkCore;
using SPA.Data;
using SPA.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace SPA
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();
            services.AddControllersWithViews();
            services.AddRazorPages();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }
}

 

Комментарии:

1. SPA состоит из двух частей, маршрут настраивается в configure. Как вы настраиваете API идентификации, можете ли вы поделиться своим запуском.

2. Добавлен файл startup.cs, заметил видео, где кто-то использует это с flutter, ответит, если tit работает