IAM _D_SWEL See also: DevSecOps, principle of least privilege (PoLP)

Resource And Scope Based Authorization in Keycloak

Resumo

  • Para API não usar nenhuma anotação, uma vez que já tem a visão SCOPE RESOURCE, exemplo POST USER
  • Questão : como fazer o “expand” de um user em roles lembro de ter visto um cache algo assim
  • E depois fazer o GLUE para SpringBoot - Somente vi Role Based, not Resouce based
  • Como fica a questão de performance com estas consultas? Precisa de cache, algo assim?
  • Depois um GLUE com o API Gateway? (ou Kubernetes)
  • E depois fazer o GLUE com ANGULAR? Tipo um discovery, algo assim?

Ponto dinamismo aqui - por resource:

http.authorizeHttpRequests(authorizeRequests ->  
authorizeRequests  
.requestMatchers("/home/admin/**")  
.hasRole("ADMIN_WRITE")  
.requestMatchers("/home/public/**")  
.hasRole("USER_READ")  
.requestMatchers("/auth/**").permitAll()  
.anyRequest().authenticated()  
)

Ref: https://medium.com/@wahyubagus1910/securing-spring-boot-with-keycloak-b352f05575f2

☐ Backend - Spring Boot + IAM ☐ Frontend - API Discovery

Pesquisa

IAM solutions vs Spring Security Este foi o melhor que eu achei


Resource: A resource is any real-world entity that is used in the application. Scope: scope is the operation that we will perform on resource/entity

Post /user

import { Resource, Scopes } from 'nest-keycloak-connect';  
@Controller('/entity')  
@Resource('entity')  
export class entityController {  
constructor(private readonly userService: UserService) {}  
  
@Get()  
@Scope('GET)  
getEntity(): string {  
return this.entityService.read();  
}  
  
@Post()  
@Scope('POST')  
createEntity(): string {  
return this.entityService.create();  
}  

thats have we fixed hard coded role problem at the backend side now let’s configure this in keycloak.

In Keycloak mainly there are two types of roles.

  1. Client Roles: These roles are specific to a particular client application. Clients are created in the Keycloak administration interface and can be assigned to users within a specific client.
  2. Realm Roles: These roles represent a realm, which can be a real or virtual application domain. Realm roles are applicable to all clients within a realm and can be assigned to users across the entire realm.

SRC: https://medium.com/javarevisited/keycloak-integration-with-spring-security-6-37999f43ec85

Keycloak Integration with Spring Security 6 | by Aziz Kale | Javarevisited | Medium Está por role based e não por resouce based.

Master @RolesAllowed in Spring Security | Medium

@RolesAllowed("ROLE_ADMIN")  
@PreAuthorize("hasIpAddress('192.168.1.0/24')")  
@GetMapping("/admin-data")  
public ResponseEntity<String> fetchAdminData() {  
return ResponseEntity.ok("Data exclusive for admins from a specific IP range.");  
}

Conclusão Não precisa de roles aqui, se vai ser resource based

JAVA - Geral

Java

Authentication and Authorization using JWT Token and Roles-Based Access Control | Quarkus Tutorial

Spring Boot

Introduction to Spring Method Security Nenhuma novidade, @PreAuthorize and @PostAuthorize Annotations @RolesAllowed

Keycloak

Resource And Scope Based Authorization in Keycloak | by Padmakar Kasture | Medium

Muito bom, tem o passo a passo das telas:

https://keycloak.discourse.group/t/list-user-permissions-via-rest-api/972/5

Authorization services overview

Keycloak supports fine-grained authorization policies and is able to combine different access control mechanisms such as:

  • Attribute-based access control (ABAC)

  • Role-based access control (RBAC)

  • User-based access control (UBAC)

  • Context-based access control (CBAC)

  • Rule-based access control

  • Time-based access control

  • Support for custom access control mechanisms (ACMs) through a Service Provider Interface (SPI)

https://www.keycloak.org/docs/latest/authorization_services/index.html#_overview

Protection API

The Protection API provides a UMA-compliant set of endpoints providing:

  • Resource Management

    With this endpoint, resource servers can manage their resources remotely and enable policy enforcers to query the server for the resources that need protection.

  • Permission Management

    In the UMA protocol, resource servers access this endpoint to create permission tickets. Keycloak also provides endpoints to manage the state of permissions and query permissions.

  • Policy API

    Keycloak leverages the UMA Protection API to allow resource servers to manage permissions for their users. In addition to the Resource and Permission APIs, Keycloak provides a Policy API from where permissions can be set to resources by resource servers on behalf of their users.

An important requirement for this API is that only resource servers are allowed to access its endpoints using a special OAuth2 access token called a protection API token (PAT). In UMA, a PAT is a token with the scope uma_protection.

REF: https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_whatis_obtain_pat

Machine-to-machine communication

  • Machine-to-machine communication also uses a token from Keycloak after providing a client_id and a client_secret.

From <https://www.krakend.io/docs/authorization/keycloak/>

KeyCloak vs Node Glue

Em node - https://www.npmjs.com/package/nest-keycloak-connect

KeyCloak vs Spring Boot Glue

Securing Spring Boot with Keycloak

O dinamismo deveria acontecer aqui

http.authorizeHttpRequests(authorizeRequests ->  
authorizeRequests  
.requestMatchers("/home/admin/**")  
.hasRole("ADMIN_WRITE")  
.requestMatchers("/home/public/**")  
.hasRole("USER_READ")  
.requestMatchers("/auth/**").permitAll()  
.anyRequest().authenticated()  
)

rest-authz-resource-server: Spring Boot REST Service Protected Using Keycloak Authorization Services - GitHub Code

OAuth2ResourceServerSecurityConfiguration.java

@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
				.authorizeHttpRequests((authorize) -> authorize
						.anyRequest().authenticated()
				)
				.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
				.addFilterAfter(createPolicyEnforcerFilter(), BearerTokenAuthenticationFilter.class);
		return http.build();
	}

KeyCloak vs AngularJS Glue

keycloak-angular - npm Keycloak-Angular integration: Practical tutorial for connecting your app to a powerful IAM system - Pretius

Permit.IO

Role-Based Access Control (RBAC) and Attribute-Based Access Control (ABAC) with Java, Spring Security and Permit.io Muito completo o exemplo.

Auth0

Auth0 vs Spring Boot Glue

Spring Boot Authorization Tutorial: Secure an API (Java) Bom artigo… usa uma implementação hasAutority

Implement Role-Based Access Control in Spring Boot  @PreAuthorize(“hasAuthority(‘update:items’)“)

Cognito

Implement fine-grained authorization in your .NET API using Amazon Cognito Custom Scopes | .NET on AWS Blog

KeyCloak vs Spring Boot Glue

Spring Method Level Security with Amazon Cognito and JWT Token