У меня довольно стандартное веб-приложение на C#. Кажется, все в бэкэнде работает, поскольку я проверял это несколько раз. Теперь я пытаюсь добавить к нему пользовательский интерфейс внешнего интерфейса, используя платформу Angular.
Я добавил компонент навигационной панели, который должен отображать «Вход», если пользователь не вошел в систему, и «Выйти», если пользователь вошел в систему. В настоящее время, когда я нажимаю «Войти», меня отправляют в процесс Google OAuth, и когда я его завершаю, интерфейс по-прежнему показывает, что я не вошел в систему.Вот весь соответствующий код.
Бэкэнд
Startup.cs:
namespace g62.backofficeWebApplication
{
public class Startup
{
readonly bool DoBootstrap = false;
readonly bool DropTables = false; // not recomended to turn true without DoBootstrap also turning true
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.AddCors(options =>
{
options.AddPolicy("AllowAngularLocalhost", policy =>
{
policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
services.AddControllers();
services.AddDbContext(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
new MySqlServerVersion(new Version(8, 0, 0))
).ReplaceService());
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});
services.AddAuthorization();
services.AddScoped();
services.AddAuthorization(options => {
options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
options.AddPolicy("RequireDoctorRole", policy => policy.RequireRole("Admin"));
});
ConfigureMyServices(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Bootstrap bootstrap)
{
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage();
}
else
{
// 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.UseRouting();
app.UseCors("AllowAngularLocalhost");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
if (DropTables) {
bootstrap.DropTables();
}
if (DoBootstrap) {
bootstrap.DoBootstrap();
}
}
public void ConfigureMyServices(IServiceCollection services)
{
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient(typeof(Domain.Logs.Logger));
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
}
}
}
LoginController.cs:
namespace g62.backofficeWebApplication.Controllers {
public class LoginController : ControllerBase
{
private readonly UserService _service;
public LoginController(UserService service)
{
_service = service;
}
[HttpGet("login")]
public IActionResult Login()
{
if (User.Identity.IsAuthenticated)
{
Redirect("http://localhost:4200/");
}
var properties = new AuthenticationProperties{RedirectUri = Url.Action("GoogleResponse", "Login")};
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
[HttpGet("logout")]
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
Console.WriteLine("Logged out.");
return Redirect("http://localhost:4200/");
}
[HttpGet("GoogleResponse")]
public async Task GoogleResponse()
{
var authenticateResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
if (!authenticateResult.Succeeded)
return BadRequest("Authentication failed.");
var userName = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value;
var email = authenticateResult.Principal.FindFirst(ClaimTypes.Email)?.Value;
try
{
var user = await _service.GetByEmailAsync(email);
if (user.Active == "False")
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("http://localhost:4200/");
}
var claims = new List
{
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.Email, email),
new Claim(ClaimTypes.Role, user.Role.ToString())
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddHours(2)
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
// Redirect the user to the frontend application
return Redirect("http://localhost:4200/");
}
catch (Exception)
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("http://localhost:4200/");
}
}
[HttpGet("status")]
public IActionResult GetStatus()
{
if (HttpContext.User.Identity.IsAuthenticated)
{
return Ok(new
{
isAuthenticated = true,
userName = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value,
email = HttpContext.User.FindFirst(ClaimTypes.Email)?.Value,
role = HttpContext.User.FindFirst(ClaimTypes.Role)?.Value
});
}
else
{
return Ok(new { isAuthenticated = false });
}
}
}
}
Внешний интерфейс
auth.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
interface AuthStatus {
isAuthenticated: boolean;
userName?: string;
email?: string;
role?: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'https://your-backend-url.com'; // Replace with your backend URL
private userInfo: { userName: string; email: string; role: string } | null = null;
constructor(private http: HttpClient) {}
login(): void {
window.location.href = `${this.apiUrl}/login`;
}
logout(): Observable {
return this.http.get(`${this.apiUrl}/logout`, { withCredentials: true }).pipe(
tap(() => {
this.userInfo = null;
}),
catchError(this.handleError('logout'))
);
}
getStatus(): ObservableWebsite
Подробнее здесь: https://stackoverflow.com/questions/791 ... ular-front
Вход в Google OAuth не работает в веб-приложении с серверной частью C # и интерфейсом Angular ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
В чем разница между серверной частью ndk и серверной частью cpp в AOSP?
Anonymous » » в форуме Android - 0 Ответы
- 104 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как я могу интегрировать Stripe с интерфейсом Flutter и серверной частью PHP?
Anonymous » » в форуме Php - 0 Ответы
- 10 Просмотры
-
Последнее сообщение Anonymous
-