

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:
<pre class='brush:php;toolbar:false;'>@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());
}</pre>
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
