Table of Contents
Question content
Workaround
Home Java Spring Security role-based authorization issue: 403 Forbidden error

Spring Security role-based authorization issue: 403 Forbidden error

Feb 09, 2024 am 11:21 AM
spring security

Spring Security is a powerful security framework for protecting applications from malicious attacks. When using Spring Security, role authorization issues may cause 403 Forbidden errors. PHP editor Banana introduces this problem to you in detail and provides a solution to help you successfully solve the problem of role authorization. Whether you are a beginner or an experienced developer, this article will help you deeply understand Spring Security's role authorization mechanism and learn to handle 403 Forbidden errors correctly.

Question content

Question:

I'm trying to create a spring based web server with role based authentication but I keep getting a 403 forbidden error. I have implemented a custom userdetails class and I suspect there may be a problem with my configuration.

Code:

Custom userdetails:

public class customuserdetails implements userdetails {
    private static final long serialversionuid = 1l;
    private final user user;

    public customuserdetails(user user) {
        this.user = user;
    }

    @override
    public collection<? extends grantedauthority> getauthorities() {
        return user.getroles().stream().map(r -> new simplegrantedauthority("role_" + r.getname())).tolist();
    }

    // ... other userdetails methods
}
Copy after login

securityfilterchain Implementation:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http
        .csrf(csrf -> csrf.disable())
        .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeHttpRequests(requests -> requests
            .requestMatchers("/api/**").permitAll()
            .requestMatchers("/secret/**").hasAuthority("USER")
            .anyRequest().authenticated())
        .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
        .addFilterBefore(authorizeFilter, UsernamePasswordAuthenticationFilter.class)
        .build();
}
Copy after login

I have implemented a custom userdetails class and configured spring security for role based authentication. However, even though I believe the roles are assigned correctly, I still get a 403 forbidden error. I tried using both hasrole and hasauthority but the problem persists. What's missing in my configuration?

Any insights or suggestions would be greatly appreciated. Thanks!

Workaround

For resource servers with JWT, permissions are set by the authentication converter.

The default authentication converter is JwtAuthenticarionConverter, which delegates permission conversion to a configurable permissions converter (defaults to using the scope entry in the statement added SCOPE_ prefix).

You can provide a JwtAuthenticationConverter configured with another permission converter (one that uses another claim as the permission source), or switch to a completely different Converter<Jwt,? Use <code>http.oauth2ResourceServer to extend AbstractAuthenticationToken>(oauth2-> oauth2.jwt(Jwt -> jwt.jwtAuthenticationConverter(...))

You may also consider this additional launcher I maintain it using a configurable permissions converter application property (unless you provide your own permissions or authentication converter in the conf)

You can try to open spring's TRACE log and find out where the problem occurs. This suggestion may not help you directly, but it does help us find the reason why the API returns 403 when migrating to Springboot3.0

The above is the detailed content of Spring Security role-based authorization issue: 403 Forbidden error. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Spring Security 6: cors() is deprecated and marked for removal Spring Security 6: cors() is deprecated and marked for removal Feb 10, 2024 pm 11:45 PM

I have the following code: publicSecurityFilterChainsecurityFilterChain(HttpSecurityhttp)throwsException{returnhttp.httpBasic().disable().cors().and().csrf().disable().authorizeHttpRequests().requestMatchers("

How to develop a Spring Security SAML-based single sign-on system using Java How to develop a Spring Security SAML-based single sign-on system using Java Sep 22, 2023 am 08:49 AM

How to use Java to develop a single sign-on system based on SpringSecuritySAML Introduction: With the rapid development of the Internet, more and more applications are developed. In these applications, user login is one of the most common features. However, for enterprise-level applications, users need to log in in multiple systems, which will lead to a very poor user login experience. In order to solve this problem, the single sign-on system (SingleSign-On, referred to as SSO) came into being. simple

GO authenticate access token (keycloak) GO authenticate access token (keycloak) Feb 09, 2024 am 09:30 AM

I'm trying to implement access token validation using GO. But the examples I've seen online seem to just use TOKEN_SECRET to verify it. But I'm used to programming in Javaspring and don't need to use TOKEN_SECRET. I just provide the jwk-set-uri and it checks for validity (auto-security filters etc.) and I know it talks to the oauth server and does this validation. Is there no library in Go to check if the token is valid by making a request to the oauth server? I know I know I can do this manually by making a request to the oauth server's userinfo endpoint: http://localh

Spring Security permission control framework usage guide Spring Security permission control framework usage guide Feb 18, 2024 pm 05:00 PM

In back-end management systems, access permission control is usually required to limit different users' ability to access interfaces. If a user lacks specific permissions, he or she cannot access certain interfaces. This article will use the waynboot-mall project as an example to introduce how common back-end management systems introduce the permission control framework SpringSecurity. The outline is as follows: waynboot-mall project address: https://github.com/wayn111/waynboot-mall 1. What is SpringSecurity? SpringSecurity is an open source project based on the Spring framework, aiming to provide powerful and flexible security for Java applications.

How to use Java to develop a single sign-on system based on Spring Security OAuth2 How to use Java to develop a single sign-on system based on Spring Security OAuth2 Sep 20, 2023 pm 01:06 PM

How to use Java to develop a single sign-on system based on SpringSecurityOAuth2 Introduction: With the rapid development of the Internet, more and more websites and applications require users to log in, but users do not want to remember for each website or application. An account number and password. The single sign-on system (SingleSign-On, referred to as SSO) can solve this problem, allowing users to access multiple websites and applications without repeated authentication after logging in once. This article will introduce

The Java RESTful API cookbook: Building the perfect service for every application The Java RESTful API cookbook: Building the perfect service for every application Mar 27, 2024 pm 12:11 PM

Introduction In today's interconnected world, RESTful APIs have become a key mechanism for communication between applications. With Java, a powerful programming language, you can build efficient, scalable, and well-maintained RESTful APIs. Chapter 1: RESTfulAPI Basics Principles and Best Practices of RESTful Architecture Http methods, status codes and response headers Data formats such as JSON and XML Chapter 2: Design and Modeling RESTfulAPI RESTfulAPI Design Principles Resource Modeling and URI Design Version Control and HATEOAS Chapter 3: Using SpringBoot to build RESTful API SpringBoot introduction and getting started building and

Spring Security gets user information for authenticated and unauthenticated users in remaining services Spring Security gets user information for authenticated and unauthenticated users in remaining services Feb 08, 2024 pm 11:00 PM

I have a springrest service and I want to use it for both authenticated and unauthenticated users. If the user is authenticated, I want to get the user information from securitycontextholder.getcontext().getauthentication(). If I use .antmatchers("/app/rest/question/useroperation/list/**").permitall() in the ouath2 configuration as shown below, then I can get the user information of the authenticated user, but not Authenticated users will appear 40

How do the vue framework and the springboot framework interact with the front and back ends? How do the vue framework and the springboot framework interact with the front and back ends? Apr 06, 2024 am 01:51 AM

Vue.js and Spring Boot interact through: RESTful API: Vue.js uses Axios to send asynchronous HTTP requests, and Spring Boot provides a RESTful API implementation. Data passing: Data is passed through requests and responses, such as the request body or query parameters. Request method: HTTP request methods such as GET, POST, PUT, and DELETE are used to specify the operation. Routing: Spring Boot @RequestMapping annotation defines controller routing, and Vue.js uses Vue Router to define interface routing. State management: Vu