You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于WSO2 IS实现.NET本地Web应用的用户名密码认证与跳转?

Step-by-Step Guide: .NET Web App with WSO2 IS Username/Password Login

Got it, let’s walk through this setup clearly—this is a standard integration scenario, so I’ll break it down into actionable steps for you as a WSO2 IS beginner.

Prerequisites

  • WSO2 Identity Server (v6.x or 7.x recommended) running locally on port 9443
  • .NET 6+ SDK installed
  • A test user created in WSO2 IS (head to Main > Identity > Users and Roles > Users in the WSO2 console to add one if you don’t have it)

1. Configure WSO2 IS as an OAuth2/OpenID Connect Provider

First, register your .NET app as a service provider in WSO2:

  1. Log into the WSO2 Management Console (https://localhost:9443/carbon) using admin credentials.
  2. Go to Main > Identity > Service Providers > Add, enter a name like DotNetWebApp, and click Register.
  3. On the provider details page, navigate to Inbound Authentication > OAuth/OpenID Connect Configuration and click Configure.
  4. Fill in these key fields:
    • Callback URL: https://localhost:<your-app-port>/signin-oidc (replace <your-app-port> with your .NET app’s port, e.g., 5001)
    • Leave other defaults as-is, then click Add.
  5. Save the generated Client ID and Client Secret—you’ll need these for your .NET app.

2. Set Up Your .NET Web Application

Let’s use an ASP.NET Core MVC app for this example:

  1. Create a new project in your terminal:
    dotnet new mvc -n WSO2LoginDemo
    cd WSO2LoginDemo
    
  2. Install required NuGet packages:
    dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
    dotnet add package Microsoft.Identity.Web
    

3. Implement Authentication Flow

Modify Program.cs to wire up WSO2 IS authentication:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

// Configure authentication
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie("Cookies")
.AddOpenIdConnect(options =>
{
    options.Authority = "https://localhost:9443/oauth2/token";
    options.MetadataAddress = "https://localhost:9443/oauth2/oidcdiscovery/.well-known/openid-configuration";
    options.ClientId = "<your-wso2-client-id>"; // Replace with your saved Client ID
    options.ClientSecret = "<your-wso2-client-secret>"; // Replace with your saved Client Secret
    options.ResponseType = "code";
    options.SaveTokens = true;
    options.CallbackPath = "/signin-oidc"; // Must match WSO2's callback URL
    options.SignedOutCallbackPath = "/signout-callback-oidc";
});

var app = builder.Build();

// Pipeline setup
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication(); // Enable authentication middleware
app.UseAuthorization();

// Route configuration
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

// Protected route for post-login redirect
app.MapControllerRoute(
    name: "protected",
    pattern: "/protected",
    defaults: new { controller = "Home", action = "Protected" });

app.Run();

Next, add a protected action in HomeController.cs:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace WSO2LoginDemo.Controllers;

public class HomeController : Controller
{
    public IActionResult Index() => View();

    [Authorize] // Requires authentication to access
    public IActionResult Protected()
    {
        // To redirect to your test virtual site instead, use:
        // return Redirect("https://your-test-url.com");
        
        var userName = User.FindFirst("sub")?.Value;
        ViewData["UserName"] = userName;
        return View();
    }

    public IActionResult Error() => View();
}

Create a Protected.cshtml view in Views/Home:

@{
    ViewData["Title"] = "Success!";
}

<h1>Welcome, @ViewData["UserName"]!</h1>
<p>WSO2 IS validated your credentials successfully.</p>
<p><a asp-action="Index">Back to Home</a></p>

Add an AccountController.cs to handle login/logout:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

namespace WSO2LoginDemo.Controllers;

public class AccountController : Controller
{
    public IActionResult Login()
    {
        // Redirect to WSO2 IS for login, then return to protected page
        return Challenge(new AuthenticationProperties { RedirectUri = "/protected" }, OpenIdConnectDefaults.AuthenticationScheme);
    }

    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync("Cookies");
        await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
        return RedirectToAction("Index", "Home");
    }
}

Update Index.cshtml to add login/logout links:

@{
    ViewData["Title"] = "Home";
}

<div class="text-center">
    <h1 class="display-4">WSO2 IS Login Demo</h1>
    @if (!User.Identity.IsAuthenticated)
    {
        <p><a asp-action="Login" asp-controller="Account">Log in with WSO2 IS</a></p>
    }
    else
    {
        <p>Hello, @User.Identity.Name! <a asp-action="Logout" asp-controller="Account">Log out</a></p>
        <p><a asp-action="Protected">Go to Protected Page</a></p>
    }
</div>

4. Test the Flow

  1. Start WSO2 IS if it’s not running.
  2. Run your .NET app:
    dotnet run --urls=https://localhost:5001
    
  3. Open https://localhost:5001, click "Log in with WSO2 IS", and enter your test user credentials.
  4. After successful validation, you’ll land on the protected page (or your test URL if you modified the redirect).

Troubleshooting Tips

  • Double-check that the callback URL in WSO2 IS exactly matches the one in your .NET app (including https and port).
  • If you get SSL errors, trust WSO2’s self-signed certificate (export it from your browser and add it to your system’s trusted root store).
  • Ensure your test user in WSO2 IS has no restricted login permissions (default users work fine).

内容的提问来源于stack exchange,提问作者munna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:58:03