Readdy Write

Asp Authorize : Zugriff einschränken über Rollen

22.02.2023 (👁13514)


In Asp .Net Core wird über das Attribute [Authorize] der Zugriff auf Web Api Entpunkte eingeschränkt.

Somit können nur Admins, oder Service Leute auf einen Endpunkt zugreifen, oder Personen, welche zumindest Eingelogged sind.

Ein Bild, das Text enthält.

Automatisch generierte Beschreibung

Im Controller wird über das Attribute

[Authorize] gesteuert, dass man zumindest eingelogged sein muss.

Über [Authorize (Roles ="Service")] wird nur der Endpoint erreicht, wenn in Claimtypes ein Text Service steht.

Zusätzlich kann über var roles = HttpContext.User.FindFirstValue(ClaimTypes.Role);

Die Rolle im Token über Code ausgelesen werden und dann individuel verarbeitet werden

using Azure.Core;

using DataModels;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.ViewFeatures;

using Microsoft.EntityFrameworkCore;

using System;

using System.ComponentModel.DataAnnotations;

using System.Reflection;

using System.Security.Claims;

using webapi_codedocu.Helpers;

using webapi_codedocu.Models.ClientModels;

using webapp_codedocu.Data;

 

namespace webapi_codedocu.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class ServiceController : ControllerBase

    {

        //--< Variables >--

        private readonly ILogger<ArticlesController> _logger;

        private readonly ApplicationDbContext _dbContext;

        //--</ Variables >--

 

        public ServiceController(ApplicationDbContext dbContext, ILogger<ArticlesController> logger)

        {

            //----< Init >----

            _dbContext = dbContext;

            _logger = logger;

            //----</ Init >----    

        }

 

        /// <summary>

        /// extracts Text from HTML

        /// </summary>

        /// <returns></returns>

        //[Authorize (Roles ="Service")] //only logged in

        [Authorize] //*only logged, but check ClaimTypes.Role in Code

        [HttpGet("correct_Text")]

        public async Task<ActionResult<string>>Correct_Text()

        {

            //--------< correct_Text() >--------

            _logger.LogWarning("---< Correkt_Text >----");

 

            //< check_owner >

            //get client User to check if is owner

            var roles = HttpContext.User.FindFirstValue(ClaimTypes.Role);

            if (roles == "")

            {

                return BadRequest("no rights");

            }

            else if (roles.Contains("Service")==false)

            {

                return BadRequest("no rights for service");

            }

            //</ check_owner >

 

            int i = 0;

 

            //load articles from db

            //load some columns

            //var articles = await _dbContext.tbl_Articles.Where(x=>x.Content_Text==null).Take(100).Select(a=>new Article_Html{ GuidArticle= a.GuidArticle,Content_Html= a.Content_Html ?? ""}).ToListAsync();

            //load full articles

            var articles = await _dbContext.tbl_Articles.Where(x=>x.Content_Text==null).Take(4000).ToListAsync();

            foreach( var article in articles)

            {

                //----< @Foreach: Articles >----

                try

                {

                    i++;

                    string sHtml = article.Content_Html ?? "";

                   

                    string sText = Html_Helper.HTML_to_Text(sHtml);                   

                    sText = sText.Trim();

                        //--< Save_new_Text >--

                        if (sText.Length > 0) {

                        if (i % 10 == 0) {

                            int i20 = 20;

                            if (sText.Length < 20) i20 = sText.Length;

                            _logger.LogDebug("-- Correkt_Text: " + i++ + " : " + sText?.Substring(0, i20));

                        }

                        //< update Server >

                        //Update only Field

                        //_dbContext.tbl_Articles.Attach(article).Property(x=>x.Content_Text).IsModified=true;

                        //await _dbContext.SaveChangesAsync();

                   

                        //Update only Field EntityFrameworkCore.7

                        _dbContext.tbl_Articles.Where(a => a.GuidArticle == article.GuidArticle)

                        .ExecuteUpdate(b => b.SetProperty(u => u.Content_Text, sText)    );

                        //</ update Server >

                        //--</ Save_new_Text >--

                    }

                }

                catch (Exception ex)

                {

                    return BadRequest("error: " + ex.Message);

                    throw;

                }

                //----</ @Foreach: Articles >----

            }

           

            //-< Final >-

            _logger.LogWarning("---</ Correkt_Text >----");

            string sResult = "---- < Fertig >----";

            return Ok(sResult);  //👍 better loading

            //-</ Final >-

            //--------</ correct_Text() >--------

        }

 

 

    }

}

Program.cs

In der Program.cs in Asp.Net Core wird die Authentifizierung aktiviert. In diesem Fall die JWT Token

using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.EntityFrameworkCore;

using Microsoft.IdentityModel.Tokens;

using Microsoft.OpenApi.Models;

using Swashbuckle.AspNetCore.Filters;

using System.Text;

using Services;

using webapp_codedocu.Data;

 

 

#region //==< Builder.Configure >==

//==< Builder >==

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

 

    //< get_config >

    string config_App_SignInKey = builder.Configuration.GetSection("AppSettings").GetValue<String>("App_SignInKey")

        ?? throw new InvalidOperationException("AppSignInKey missing in Config.AppSettings");

 

    string url_FrontEnd = builder.Configuration.GetSection("AppSettings").GetValue<String>("Url_FrontEnd")

        ?? throw new InvalidOperationException("UrlFrontEnd is missing in Config.AppSettings");

 

    string connectionString = builder.Configuration.GetConnectionString("DefaultConnection")

        ?? throw new InvalidOperationException("Connection string not found in Config");

 

    //</ get_config >

 

    //* Connect Database

    builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));

 

    builder.Services.AddControllers();

    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

    builder.Services.AddEndpointsApiExplorer();

 

    builder.Services.AddScoped<IUserService, UserService>();

    builder.Services.AddHttpContextAccessor();

 

    builder.Services.AddHttpClient("client",client=>client.Timeout=TimeSpan.FromMinutes(5)); //for service

 

    //builder.Services.AddSwaggerGen();

    builder.Services.AddSwaggerGen(options =>

    {

        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme

        {

            Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n

                      Enter 'Bearer' [space] and then your token in the text input below.

                      \r\n\r\nExample: 'Bearer 12345abcdef'",

            In = ParameterLocation.Header,

            Name = "Authorization",

            Type = SecuritySchemeType.ApiKey,

            Scheme = "Bearer" //#added

        });

 

        options.OperationFilter<SecurityRequirementsOperationFilter>();         //by Swashbuckle

    });

    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)  //by Microsoft.AspCore.Authentication

        .AddJwtBearer(options =>

        {

            options.TokenValidationParameters = new TokenValidationParameters

            {

                ValidateIssuerSigningKey = true,

                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config_App_SignInKey)), //*Decode AccessToken by App-Key

                ValidateIssuer = false,

                ValidateAudience = false

            };

        });

 

    //< CORS >

    //*allow calls from AngularUI

    builder.Services.AddCors(options => options.AddPolicy(

        //#TODO: policy.WithOrigins(url_FrontEnd) , problems on update

        name: "FrontendUI", policy => { policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }));

    //</ CORS > 

 

//==</ Builder >==

#endregion //==</ Builder.Configure >==

 

#region //==< APP >==

//==< APP >==

var app = builder.Build();

 

// Configure the HTTP request pipeline.

if (app.Environment.IsDevelopment())

{

    app.UseSwagger();

    app.UseSwaggerUI();

}

 

//< CORS >

app.UseCors("FrontendUI");

//</ CORS >

 

 

app.UseHttpsRedirection();

 

app.UseAuthentication();  //*Get User

app.UseAuthorization();

 

app.MapControllers();

 

app.Run();

//==</ APP >==

#endregion //==</ APP >==


0,00 €