Maui Blazor 中文社区 QQ群:645660665

Blazor OIDC 单点登录授权实例3-服务端管理组件

目录:

  1. OpenID 与 OAuth2 基础知识
  2. Blazor wasm Google 登录
  3. Blazor wasm Gitee 码云登录
  4. Blazor OIDC 单点登录授权实例1-建立和配置IDS身份验证服务
  5. Blazor OIDC 单点登录授权实例2-登录信息组件wasm
  6. Blazor OIDC 单点登录授权实例3-服务端管理组件
  7. Blazor OIDC 单点登录授权实例4 - 部署服务端/独立WASM端授权
  8. Blazor OIDC 单点登录授权实例5 - 独立SSR App (net8 webapp)端授权
  9. Blazor OIDC 单点登录授权实例6 - Winform 端授权
  10. Blazor OIDC 单点登录授权实例7 - Blazor hybird app 端授权

(目录暂时不更新,跟随合集标题往下走)

源码

BlazorOIDC/Server

BlazorOIDC.Server 项目

1. 服务端默认工程改为 Blazor ssr

  • 最新版vs模板建立的net7 blazor wasm 托管工程主机端是空工程,需要改造一下变为服务端

具体代码比较多, 直接看提交或者源码

  • 添加Pages目录以及文件
  • 添加Shared目录以及文件
  • 添加_Imports.razor文件
  • 添加App.razor文件

2. 添加简单管理页面

Pages/DataAdmin.razor

<h4>用户表</h4>

<TablePollo TItem="AspNetUsers"
       IncludeByPropertyNames="@IncludeAspNetUsers"
       ItemDetails="AspNetUserRoles"
       SubAddAsync="OnSubAddAsync"
       ItemDetailsII="NullClass"
       ItemDetailsIII="NullClass"
       ShowColumnList
       ShowExportButton
       ShowDetailRowS
       Field="@nameof(AspNetUsers.Id)"
       FieldD="@nameof(AspNetUserRoles.UserId)"
       ExportToStream="false"
       ExportBasePath="temp" />

用户身份以及角色分配刷新两次后自动分配到测试数据

3. 用户身份以及角色分配

登录 test@test.com 后点击登录信息, 可以看到用户身份以及角色分配已经能读取出来了

点击Wasm菜单,切换到wasm项目,在wasm项目也重新登录,点击登录信息,可以看到用户身份以及角色分配也已经更新了

4. API授权

添加 Controllers/UserController.cs

using BlazorOIDC.Server.Models;
using Densen.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace BlazorOIDC.Server.Controllers;

[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{

    private readonly ILogger<UserController> _logger;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

    public UserController(ILogger<UserController> logger, SignInManager<ApplicationUser> signInManager,
        UserManager<ApplicationUser> userManager)
    {
        _logger = logger;
        _signInManager = signInManager;
        _userManager = userManager;
    }
    /// <summary>
    /// jwt登录测试
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <param name="code"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<IActionResult> Post(string username = "test@test.com", string password = "1qaz2wsx")
    {

        var signedUser = await _userManager.FindByEmailAsync(username);
        if (signedUser == null)
        {
            _logger.LogWarning("登录失败.");
            ModelState.AddModelError(string.Empty, "登录失败.请检查用户名或者密码.");
            return BadRequest("用户名密码错误");
        }

        var result = await _signInManager.PasswordSignInAsync(signedUser, password, false, lockoutOnFailure: false);

        var userId = await _userManager.GetUserIdAsync(signedUser);
        return Ok(new { result });
    }

    [Authorize]
    [HttpGet]
    public async Task<object> Get()
    {
        //获取用户Claim信息
        var userClaims = HttpContext.User.Claims.Select(it => $"{it.Type}:{it.Value}");
        var user = await _userManager.GetUserAsync(User);
        return new
        {
            user.UserName,
            roles = await _userManager.GetRolesAsync(user),
            userClaims
        };
    }

    [Authorize(Roles = nameof(AuthorizeRoles.Superuser))]
    [HttpGet("{id}")]
    public async Task<object> Get(int id)
    {
        var user = await _userManager.GetUserAsync(User);
        return new
        {
            user.UserName,
            roles = await _userManager.GetRolesAsync(user)
        };
    } 
 

}

为了配合下一章OIDC部署到服务器使用,需要把 launchSettings.json 配置改一下

"applicationUrl": "https://localhost:5001;http://localhost:5000",

5. 测试API授权

测试登录

测试用户验证

posted @ 2024-01-17 10:36  AlexChow  阅读(847)  评论(0编辑  收藏  举报