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.
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 fromsecuritycontextholder.getcontext().getauthentication().
.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..antmatchers("/app/rest/question/useroperation/list/**").permitall()and ignore url in websecurityweb.ignoring()..antmatchers("/app/rest/question/useroperation/list/**")Insecurityconfigurationas 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(); } } }
permitall()Still requires theauthenticationobject to be present in thesecuritycontext.
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:anonymousauthenticationfilterto the filter chain that populatesanonymousauthenticationtokenas authentication information, in case there is no ## insecuritycontext#authenticationObject
/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 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!
Related labels:
source:stackoverflow.com
Previous article:Spring 3.2 cannot find @RestController
Next article:Why does primitive not need the .equals method in java?
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
Latest Articles by Author
-
2024-08-28 22:30:36
-
2024-08-28 21:42:19
-
2024-08-28 21:34:23
-
2024-08-28 21:34:09
-
2024-08-28 21:32:58
-
2024-08-28 21:31:11
-
2024-08-28 21:30:39
-
2024-08-28 21:29:30
-
2024-08-28 21:26:30
-
2024-08-28 21:18:30
Latest Issues
spring security
I'm developing a basic CRUD web application using React and Spring. Since the frontend isn...
From 2023-09-15 17:55:14
0
1
167
Popular Recommendations
-
-
-
-
-
Popular Tutorials
More>
JAVA Beginner's Video Tutorial
2364704
Latest Downloads
More>
-
-
-
-
-
-
-
-
-
About us
Disclaimer
Sitemap
-
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!