

Spring Security gets user information for authenticated and unauthenticated users in remaining services
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 websecurityweb.ignoring()..antmatchers("/app/rest/question/useroperation/list/**")
Insecurityconfiguration
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(); } }
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(); } } }
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
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
/public/authphpcnendcphp Chinese: 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!
@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());
}

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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 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

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

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

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