Table of Contents
Question content
Workaround
Home Java 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
spring security

Security is an important consideration when developing web applications. To protect user data and prevent unauthorized access, we need to use a reliable authentication and authorization mechanism. Spring Security is a powerful and widely used security framework that provides a complete set of solutions to protect our applications. In this article, we will explore how to get user information for authenticated and unauthenticated users in Spring Security. PHP editor Baicao will show you how to use the functions of Spring Security to obtain user information and share user information between different services. Whether you are a beginner or an experienced developer, this article will provide you with detailed information about Spring Security and help you improve the security of your application.

Question content

I have a spring rest 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 Authenticated users, but unauthenticated users get a 401 error.
  • If I .antmatchers("/app/rest/question/useroperation/list/**").permitall() and ignore url in websecurity web.ignoring()..antmatchers("/app/rest/question/useroperation/list/**") In securityconfiguration as shown below, then all users can call service, but I can't get the user information from the securitycontext.

How do I configure my spring security to call urls for authenticated and unauthenticated users and get the user information from the securitycontext when the user logs in.

@configuration
@enableresourceserver
protected static class resourceserverconfiguration extends resourceserverconfigureradapter {

    @inject
    private http401unauthorizedentrypoint authenticationentrypoint;

    @inject
    private ajaxlogoutsuccesshandler ajaxlogoutsuccesshandler;

    @override
    public void configure(httpsecurity http) throws exception {
        http
                .exceptionhandling()
                .authenticationentrypoint(authenticationentrypoint)
                .and()
                .logout()
                .logouturl("/app/logout")
                .logoutsuccesshandler(ajaxlogoutsuccesshandler)
                .and()
                .csrf()
                .requirecsrfprotectionmatcher(new antpathrequestmatcher("/oauth/authorize"))
                .disable()
                .headers()
                .frameoptions().disable()
                .sessionmanagement()
                .sessioncreationpolicy(sessioncreationpolicy.stateless)
                .and()
                .authorizerequests()
                .antmatchers("/views/**").permitall()
                .antmatchers("/app/rest/authenticate").permitall()
                .antmatchers("/app/rest/register").permitall()
                .antmatchers("/app/rest/question/useroperation/list/**").permitall()
                .antmatchers("/app/rest/question/useroperation/comment/**").authenticated()
                .antmatchers("/app/rest/question/useroperation/answer/**").authenticated()
                .antmatchers("/app/rest/question/definition/**").hasanyauthority(authoritiesconstants.admin)
                .antmatchers("/app/rest/logs/**").hasanyauthority(authoritiesconstants.admin)
                .antmatchers("/app/**").authenticated()
                .antmatchers("/websocket/tracker").hasauthority(authoritiesconstants.admin)
                .antmatchers("/websocket/**").permitall()
                .antmatchers("/metrics/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/health/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/trace/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/dump/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/shutdown/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/beans/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/info/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/autoconfig/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/env/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/trace/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/api-docs/**").hasauthority(authoritiesconstants.admin)
                .antmatchers("/protected/**").authenticated();

    }

}
Copy after login

Security Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Inject
    private UserDetailsService userDetailsService;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new StandardPasswordEncoder();
    }

    @Inject
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
            .antMatchers("/bower_components/**")
            .antMatchers("/fonts/**")
            .antMatchers("/images/**")
            .antMatchers("/scripts/**")
            .antMatchers("/styles/**")
            .antMatchers("/views/**")
            .antMatchers("/i18n/**")
            .antMatchers("/swagger-ui/**")
            .antMatchers("/app/rest/register")
            .antMatchers("/app/rest/activate")
            .antMatchers("/app/rest/question/useroperation/list/**")
            .antMatchers("/console/**");
    }


    @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
    private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }

    }
}
Copy after login

Workaround

permitall() Still requires the authentication object to be present in the securitycontext.

For non-oauth users, this can be achieved by enabling anonymous access:

@override
public void configure(httpsecurity http) throws exception {
   http
//some configuration
     .and()
        .anonymous() //allow anonymous access
     .and()
        .authorizerequests()
           .antmatchers("/views/**").permitall()
//other security settings
Copy after login

Anonymous access will add an additional filter: anonymousauthenticationfilter to the filter chain that populates anonymousauthenticationtoken as authentication information, in case there is no ## in securitycontext #authenticationObject

I have this security configuration for checking authuser via

/public/authphpcnendcphp Chinese:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().authorizeRequests()
           .antMatchers("/api/skills/**", "/api/profile/**", "/api/info/**").authenticated()
           .antMatchers("/api/**").hasAuthority(Role.ROLE_ADMIN.getAuthority())
           .antMatchers("/public/auth").permitAll()
           .and().httpBasic()
           .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
           .and().csrf().disable();
}

@GetMapping(value = "/public/auth")
private ResponseEntity<User> getAuthUser(@AuthenticationPrincipal AuthUser authUser) {
    return authUser == null ? 
               ResponseEntity.notFound().build() :
               ResponseEntity.ok(authUser.getUser());
}
Copy after login

The above is the detailed content of Spring Security gets user information for authenticated and unauthenticated users in remaining services. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks 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

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

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

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