search
HomeBackend DevelopmentC#.Net TutorialIdentityServer4 authorization configuration AllowedScopes instance

1. Business scenario

AllowedScopes in the IdentityServer4 authorization configurationClient sets the specific API site name, which is the ## set by the user. #ApiName, sample code:

//授权中心配置new Client
{
    ClientId = "client_id_1",
    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
    AllowOfflineAccess = true,
    AccessTokenLifetime = 3600 * 6, //6小时SlidingRefreshTokenLifetime = 1296000, //15天ClientSecrets =
    {new Secret("secret".Sha256())
    },
    AllowedScopes = 
    {"api_name1"},
}//API 服务配置app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = $"http://localhost:5000",
    ApiName = "api_name1",
    RequireHttpsMetadata = false});
The above two

api_name1 configurations must be consistent. The problem arises because the scope## of the authorization center #The configuration is the entire API service. If we have multiple Client configurations, such as a frontend and a backend, and then both need to access api_name1, some problems will occur. For example, an interface service configuration code in the

api_name1

service:

[Authorize()]
[Route("api/values")]
[HttpGet]public IActionResult Get()
{return Ok();
}

Authorize()

configuration, description api/valuesThe interface needs to be accessed after authorization. If the authorization center is configured with two Client (frontend and backend), and scope both contain api_name1 , now there will be two situations:

    front desk
  1. Client

    and backend Client, both require authorization to access api/valuesInterface: No problem.

  2. Front desk
  3. Client

    does not require authorization for access, backgroundClient requires authorization for access: There is a problem, front deskClient There is no way to access it because the api/values interface is set with Authorize().

  4. Actually, to explain more clearly, how to let the API service specify
Client

to authorize access? For example: [Authorize(ClientId = 'client_id_1')]. 2. Solution

There is no

[Authorize(ClientId = 'client_id_1')]

this solution, but you can use [Authorize(Roles = ' admin')]. The

ResourceOwnerPasswordValidator

code of the authorization center is modified as follows:

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{private readonly IUserService _userService;public ResourceOwnerPasswordValidator(IUserService userService)
    {
        _userService = userService;
    }public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {var user = await _userService.Login(context.UserName, context.Password);if (user != null)
        {var claims = new List<Claim>() { new Claim("role", "admin") }; //根据 user 对象,设置不同的 rolecontext.Result = new GrantValidationResult(user.UserId.ToString(), OidcConstants.AuthenticationMethods.Password, claims);
        }
    }
}

The
startup

configuration of the authorization center is modified as follows

var builder = services.AddIdentityServer();
builder.AddTemporarySigningCredential()//.AddInMemoryIdentityResources(Config.GetIdentityResources()).AddInMemoryApiResources(new List<ApiResource>
        {new ApiResource("api_name1", "api1"){ UserClaims = new List<string> {"role"}}, //增加 role claimnew ApiResource("api_name2", "api2"){ UserClaims = new List<string> {"role"}}
        })
        .AddInMemoryClients(Config.GetClients());

API service interface only needs to be configured as follows:

[Authorize()]
[Route("api/values")]
[HttpGet]public IActionResult Get()
{return Ok();
}

[Authorize(Roles = "admin")]
[Route("api/values2")]
[HttpGet]public IActionResult Get2()
{return Ok();
}

[Authorize(Roles = "admin,normal")]
[Route("api/values3")]
[HttpGet]public IActionResult Get3()
{return Ok();
}

It should be noted that although the
api/values

interface does not Set specific Roles, but each Role is accessible.

The above is the detailed content of IdentityServer4 authorization configuration AllowedScopes instance. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何将win10企业版2016长期服务版升级为专业版如何将win10企业版2016长期服务版升级为专业版Jan 03, 2024 pm 11:26 PM

当我们不想要继续使用当前的win10企业版2016长期服务版的时候可以选择切换成专业版,方法也很简单,只需要改一些内容然后进行系统镜像的安装就可以了。win10企业版2016长期服务版怎么改专业版1、按下win+R,然后输入“regedit”2、直接在上面的地址栏里面粘贴下面的这个路径:计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion3、然后找到EditionID,将里面的内容替换成“professional”确

如何使用Flask-Security实现用户认证和授权如何使用Flask-Security实现用户认证和授权Aug 04, 2023 pm 02:40 PM

如何使用Flask-Security实现用户认证和授权引言:在现代的Web应用程序中,用户认证和授权是必不可少的功能。为了简化这个过程,Flask-Security是一个非常有用的扩展,它提供了一系列工具和功能,使用户认证和授权变得简单而便捷。本文将介绍如何使用Flask-Security来实现用户认证和授权。一、安装Flask-Security扩展:在开始

如何使用JWT在PHP应用中实现身份验证和授权如何使用JWT在PHP应用中实现身份验证和授权Aug 03, 2023 pm 10:17 PM

如何使用JWT在PHP应用中实现身份验证和授权引言:随着互联网的快速发展,身份验证和授权在Web应用程序中变得日益重要。JSONWebToken(JWT)是一种流行的认证和授权机制,它在PHP应用中广泛应用。本文将介绍如何使用JWT在PHP应用中实现身份验证和授权,并提供代码示例,帮助读者更好地理解JWT的使用方法。一、JWT简介JSONWebTo

UniApp实现用户登录与授权的细节解析UniApp实现用户登录与授权的细节解析Jul 05, 2023 pm 11:54 PM

UniApp实现用户登录与授权的细节解析在现代移动应用开发中,用户登录和授权是必不可少的功能。UniApp作为一个跨平台的开发框架,提供了一种方便的方式来实现用户登录和授权。本文将探讨UniApp中实现用户登录和授权的细节,并附上相应的代码示例。一、用户登录功能的实现创建登录页面用户登录功能通常需要一个登录页面,该页面包含用户输入账号和密码的表单以及登录按钮

Flask中的用户身份验证和授权Flask中的用户身份验证和授权Jun 17, 2023 pm 06:02 PM

随着Web应用程序的广泛使用,安全性和数据保护已经成为Web应用程序开发的一个重要问题。为了确保Web应用程序的安全性,需要进行用户身份验证和授权。Flask作为一个流行的Web开发框架,提供了很多用于实现用户身份验证和授权的机制。用户身份验证用户身份验证是指在用户访问Web应用程序的时候,通过一定的身份验证方式来确定用户的身份是否合法。Flask提供了很多

如何通过Webman框架实现用户认证和授权功能?如何通过Webman框架实现用户认证和授权功能?Jul 07, 2023 am 09:21 AM

如何通过Webman框架实现用户认证和授权功能?Webman是一款基于Python的轻量级Web框架,它提供了丰富的功能和灵活的扩展性。在开发中,用户认证和授权是非常重要的功能,本文将介绍如何使用Webman框架实现这些功能。安装Webman首先,我们需要安装Webman。可以使用pip命令来安装:pipinstallwebman初

使用Go实现基本的API认证和授权使用Go实现基本的API认证和授权Jun 17, 2023 pm 07:51 PM

随着Web应用的不断发展,由于应用渐渐变得越来越庞大,需要保护API接口以防止随意访问,因此API认证和授权的机制变得越来越重要。在这篇文章中,我们将介绍如何使用Go来实现基本的API认证和授权。首先,我们来了解一下认证和授权的基本概念:认证:认证是一种身份验证机制,用于验证用户请求的身份是否合法。在Web应用中,认证可以通过用户名和密码进行或使用JWT等令

如何进行代码授权和加密保护?如何进行代码授权和加密保护?Jun 12, 2023 am 09:33 AM

在当前信息化时代,网络上存在着大量的软件、程序和代码文件,其中有不少代码是需要被保护的,以避免被盗版或恶意利用,同时也有些代码需要进行授权以获得经济收益。那么,问题就来了:如何进行代码授权和加密保护呢?一、代码授权代码授权是指在一定的条件下,授予使用或修改、发布软件或程序源代码的权利。此时,程序开发者作为版权人,需要明确在何种情况下允许其他人使用代码、以何

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft