


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
service:
[Authorize()] [Route("api/values")] [HttpGet]public IActionResult Get() {return Ok(); }Authorize()
configuration, description api/values
The 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
- Client
and backend
Client
, both require authorization to accessapi/values
Interface: No problem. Front desk - Client
does not require authorization for access, background
Client
requires authorization for access: There is a problem, front deskClient
There is no way to access it because theapi/values
interface is set withAuthorize()
. Actually, to explain more clearly, how to let the API service specify
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
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); } } }
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());
[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(); }
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!

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor